babylon.max.js 3.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226
  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 Color3 = (function () {
  67. /**
  68. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  69. */
  70. function Color3(r, g, b) {
  71. if (r === void 0) { r = 0; }
  72. if (g === void 0) { g = 0; }
  73. if (b === void 0) { b = 0; }
  74. this.r = r;
  75. this.g = g;
  76. this.b = b;
  77. }
  78. /**
  79. * Returns a string with the Color3 current values.
  80. */
  81. Color3.prototype.toString = function () {
  82. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  83. };
  84. /**
  85. * Returns the string "Color3".
  86. */
  87. Color3.prototype.getClassName = function () {
  88. return "Color3";
  89. };
  90. /**
  91. * Returns the Color3 hash code.
  92. */
  93. Color3.prototype.getHashCode = function () {
  94. var hash = this.r || 0;
  95. hash = (hash * 397) ^ (this.g || 0);
  96. hash = (hash * 397) ^ (this.b || 0);
  97. return hash;
  98. };
  99. // Operators
  100. /**
  101. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  102. * Returns the Color3.
  103. */
  104. Color3.prototype.toArray = function (array, index) {
  105. if (index === undefined) {
  106. index = 0;
  107. }
  108. array[index] = this.r;
  109. array[index + 1] = this.g;
  110. array[index + 2] = this.b;
  111. return this;
  112. };
  113. /**
  114. * Returns a new Color4 object from the current Color3 and the passed alpha.
  115. */
  116. Color3.prototype.toColor4 = function (alpha) {
  117. if (alpha === void 0) { alpha = 1; }
  118. return new Color4(this.r, this.g, this.b, alpha);
  119. };
  120. /**
  121. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  122. */
  123. Color3.prototype.asArray = function () {
  124. var result = [];
  125. this.toArray(result, 0);
  126. return result;
  127. };
  128. /**
  129. * Returns the luminance value (float).
  130. */
  131. Color3.prototype.toLuminance = function () {
  132. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  133. };
  134. /**
  135. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  136. * Returns this new object.
  137. */
  138. Color3.prototype.multiply = function (otherColor) {
  139. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  140. };
  141. /**
  142. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  143. * Returns the current Color3.
  144. */
  145. Color3.prototype.multiplyToRef = function (otherColor, result) {
  146. result.r = this.r * otherColor.r;
  147. result.g = this.g * otherColor.g;
  148. result.b = this.b * otherColor.b;
  149. return this;
  150. };
  151. /**
  152. * Boolean : True if the rgb values are equal to the passed ones.
  153. */
  154. Color3.prototype.equals = function (otherColor) {
  155. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  156. };
  157. /**
  158. * Boolean : True if the rgb values are equal to the passed ones.
  159. */
  160. Color3.prototype.equalsFloats = function (r, g, b) {
  161. return this.r === r && this.g === g && this.b === b;
  162. };
  163. /**
  164. * Multiplies in place each rgb value by scale.
  165. * Returns the updated Color3.
  166. */
  167. Color3.prototype.scale = function (scale) {
  168. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  169. };
  170. /**
  171. * Multiplies the rgb values by scale and stores the result into "result".
  172. * Returns the unmodified current Color3.
  173. */
  174. Color3.prototype.scaleToRef = function (scale, result) {
  175. result.r = this.r * scale;
  176. result.g = this.g * scale;
  177. result.b = this.b * scale;
  178. return this;
  179. };
  180. /**
  181. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  182. */
  183. Color3.prototype.add = function (otherColor) {
  184. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  185. };
  186. /**
  187. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  188. * Returns the unmodified current Color3.
  189. */
  190. Color3.prototype.addToRef = function (otherColor, result) {
  191. result.r = this.r + otherColor.r;
  192. result.g = this.g + otherColor.g;
  193. result.b = this.b + otherColor.b;
  194. return this;
  195. };
  196. /**
  197. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  198. */
  199. Color3.prototype.subtract = function (otherColor) {
  200. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  201. };
  202. /**
  203. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  204. * Returns the unmodified current Color3.
  205. */
  206. Color3.prototype.subtractToRef = function (otherColor, result) {
  207. result.r = this.r - otherColor.r;
  208. result.g = this.g - otherColor.g;
  209. result.b = this.b - otherColor.b;
  210. return this;
  211. };
  212. /**
  213. * Returns a new Color3 copied the current one.
  214. */
  215. Color3.prototype.clone = function () {
  216. return new Color3(this.r, this.g, this.b);
  217. };
  218. /**
  219. * Copies the rgb values from the source in the current Color3.
  220. * Returns the updated Color3.
  221. */
  222. Color3.prototype.copyFrom = function (source) {
  223. this.r = source.r;
  224. this.g = source.g;
  225. this.b = source.b;
  226. return this;
  227. };
  228. /**
  229. * Updates the Color3 rgb values from the passed floats.
  230. * Returns the Color3.
  231. */
  232. Color3.prototype.copyFromFloats = function (r, g, b) {
  233. this.r = r;
  234. this.g = g;
  235. this.b = b;
  236. return this;
  237. };
  238. /**
  239. * Updates the Color3 rgb values from the passed floats.
  240. * Returns the Color3.
  241. */
  242. Color3.prototype.set = function (r, g, b) {
  243. return this.copyFromFloats(r, g, b);
  244. };
  245. /**
  246. * Returns the Color3 hexadecimal code as a string.
  247. */
  248. Color3.prototype.toHexString = function () {
  249. var intR = (this.r * 255) | 0;
  250. var intG = (this.g * 255) | 0;
  251. var intB = (this.b * 255) | 0;
  252. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  253. };
  254. /**
  255. * Returns a new Color3 converted to linear space.
  256. */
  257. Color3.prototype.toLinearSpace = function () {
  258. var convertedColor = new Color3();
  259. this.toLinearSpaceToRef(convertedColor);
  260. return convertedColor;
  261. };
  262. /**
  263. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  264. * Returns the unmodified Color3.
  265. */
  266. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  267. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  268. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  269. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  270. return this;
  271. };
  272. /**
  273. * Returns a new Color3 converted to gamma space.
  274. */
  275. Color3.prototype.toGammaSpace = function () {
  276. var convertedColor = new Color3();
  277. this.toGammaSpaceToRef(convertedColor);
  278. return convertedColor;
  279. };
  280. /**
  281. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  282. * Returns the unmodified Color3.
  283. */
  284. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  285. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  286. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  287. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  288. return this;
  289. };
  290. // Statics
  291. /**
  292. * Creates a new Color3 from the string containing valid hexadecimal values.
  293. */
  294. Color3.FromHexString = function (hex) {
  295. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  296. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  297. return new Color3(0, 0, 0);
  298. }
  299. var r = parseInt(hex.substring(1, 3), 16);
  300. var g = parseInt(hex.substring(3, 5), 16);
  301. var b = parseInt(hex.substring(5, 7), 16);
  302. return Color3.FromInts(r, g, b);
  303. };
  304. /**
  305. * Creates a new Vector3 from the startind index of the passed array.
  306. */
  307. Color3.FromArray = function (array, offset) {
  308. if (offset === void 0) { offset = 0; }
  309. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  310. };
  311. /**
  312. * Creates a new Color3 from integer values ( < 256).
  313. */
  314. Color3.FromInts = function (r, g, b) {
  315. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  316. };
  317. /**
  318. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  319. */
  320. Color3.Lerp = function (start, end, amount) {
  321. var r = start.r + ((end.r - start.r) * amount);
  322. var g = start.g + ((end.g - start.g) * amount);
  323. var b = start.b + ((end.b - start.b) * amount);
  324. return new Color3(r, g, b);
  325. };
  326. Color3.Red = function () { return new Color3(1, 0, 0); };
  327. Color3.Green = function () { return new Color3(0, 1, 0); };
  328. Color3.Blue = function () { return new Color3(0, 0, 1); };
  329. Color3.Black = function () { return new Color3(0, 0, 0); };
  330. Color3.White = function () { return new Color3(1, 1, 1); };
  331. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  332. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  333. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  334. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  335. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  336. return Color3;
  337. }());
  338. BABYLON.Color3 = Color3;
  339. var Color4 = (function () {
  340. /**
  341. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  342. */
  343. function Color4(r, g, b, a) {
  344. this.r = r;
  345. this.g = g;
  346. this.b = b;
  347. this.a = a;
  348. }
  349. // Operators
  350. /**
  351. * Adds in place the passed Color4 values to the current Color4.
  352. * Returns the updated Color4.
  353. */
  354. Color4.prototype.addInPlace = function (right) {
  355. this.r += right.r;
  356. this.g += right.g;
  357. this.b += right.b;
  358. this.a += right.a;
  359. return this;
  360. };
  361. /**
  362. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  363. */
  364. Color4.prototype.asArray = function () {
  365. var result = [];
  366. this.toArray(result, 0);
  367. return result;
  368. };
  369. /**
  370. * Stores from the starting index in the passed array the Color4 successive values.
  371. * Returns the Color4.
  372. */
  373. Color4.prototype.toArray = function (array, index) {
  374. if (index === undefined) {
  375. index = 0;
  376. }
  377. array[index] = this.r;
  378. array[index + 1] = this.g;
  379. array[index + 2] = this.b;
  380. array[index + 3] = this.a;
  381. return this;
  382. };
  383. /**
  384. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  385. */
  386. Color4.prototype.add = function (right) {
  387. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  388. };
  389. /**
  390. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  391. */
  392. Color4.prototype.subtract = function (right) {
  393. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  394. };
  395. /**
  396. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  397. * Returns the Color4.
  398. */
  399. Color4.prototype.subtractToRef = function (right, result) {
  400. result.r = this.r - right.r;
  401. result.g = this.g - right.g;
  402. result.b = this.b - right.b;
  403. result.a = this.a - right.a;
  404. return this;
  405. };
  406. /**
  407. * Creates a new Color4 with the current Color4 values multiplied by scale.
  408. */
  409. Color4.prototype.scale = function (scale) {
  410. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  411. };
  412. /**
  413. * Multiplies the current Color4 values by scale and stores the result in "result".
  414. * Returns the Color4.
  415. */
  416. Color4.prototype.scaleToRef = function (scale, result) {
  417. result.r = this.r * scale;
  418. result.g = this.g * scale;
  419. result.b = this.b * scale;
  420. result.a = this.a * scale;
  421. return this;
  422. };
  423. /**
  424. * Multipy an RGBA Color4 value by another and return a new Color4 object
  425. * @param color The Color4 (RGBA) value to multiply by
  426. * @returns A new Color4.
  427. */
  428. Color4.prototype.multiply = function (color) {
  429. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  430. };
  431. /**
  432. * Multipy an RGBA Color4 value by another and push the result in a reference value
  433. * @param color The Color4 (RGBA) value to multiply by
  434. * @param result The Color4 (RGBA) to fill the result in
  435. * @returns the result Color4.
  436. */
  437. Color4.prototype.multiplyToRef = function (color, result) {
  438. result.r = this.r * color.r;
  439. result.g = this.g * color.g;
  440. result.b = this.b * color.b;
  441. result.a = this.a * color.a;
  442. return result;
  443. };
  444. /**
  445. * Returns a string with the Color4 values.
  446. */
  447. Color4.prototype.toString = function () {
  448. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  449. };
  450. /**
  451. * Returns the string "Color4"
  452. */
  453. Color4.prototype.getClassName = function () {
  454. return "Color4";
  455. };
  456. /**
  457. * Return the Color4 hash code as a number.
  458. */
  459. Color4.prototype.getHashCode = function () {
  460. var hash = this.r || 0;
  461. hash = (hash * 397) ^ (this.g || 0);
  462. hash = (hash * 397) ^ (this.b || 0);
  463. hash = (hash * 397) ^ (this.a || 0);
  464. return hash;
  465. };
  466. /**
  467. * Creates a new Color4 copied from the current one.
  468. */
  469. Color4.prototype.clone = function () {
  470. return new Color4(this.r, this.g, this.b, this.a);
  471. };
  472. /**
  473. * Copies the passed Color4 values into the current one.
  474. * Returns the updated Color4.
  475. */
  476. Color4.prototype.copyFrom = function (source) {
  477. this.r = source.r;
  478. this.g = source.g;
  479. this.b = source.b;
  480. this.a = source.a;
  481. return this;
  482. };
  483. /**
  484. * Copies the passed float values into the current one.
  485. * Returns the updated Color4.
  486. */
  487. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  488. this.r = r;
  489. this.g = g;
  490. this.b = b;
  491. this.a = a;
  492. return this;
  493. };
  494. /**
  495. * Copies the passed float values into the current one.
  496. * Returns the updated Color4.
  497. */
  498. Color4.prototype.set = function (r, g, b, a) {
  499. return this.copyFromFloats(r, g, b, a);
  500. };
  501. /**
  502. * Returns a string containing the hexadecimal Color4 code.
  503. */
  504. Color4.prototype.toHexString = function () {
  505. var intR = (this.r * 255) | 0;
  506. var intG = (this.g * 255) | 0;
  507. var intB = (this.b * 255) | 0;
  508. var intA = (this.a * 255) | 0;
  509. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  510. };
  511. // Statics
  512. /**
  513. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  514. */
  515. Color4.FromHexString = function (hex) {
  516. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  517. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  518. return new Color4(0.0, 0.0, 0.0, 0.0);
  519. }
  520. var r = parseInt(hex.substring(1, 3), 16);
  521. var g = parseInt(hex.substring(3, 5), 16);
  522. var b = parseInt(hex.substring(5, 7), 16);
  523. var a = parseInt(hex.substring(7, 9), 16);
  524. return Color4.FromInts(r, g, b, a);
  525. };
  526. /**
  527. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  528. */
  529. Color4.Lerp = function (left, right, amount) {
  530. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  531. Color4.LerpToRef(left, right, amount, result);
  532. return result;
  533. };
  534. /**
  535. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  536. */
  537. Color4.LerpToRef = function (left, right, amount, result) {
  538. result.r = left.r + (right.r - left.r) * amount;
  539. result.g = left.g + (right.g - left.g) * amount;
  540. result.b = left.b + (right.b - left.b) * amount;
  541. result.a = left.a + (right.a - left.a) * amount;
  542. };
  543. /**
  544. * Creates a new Color4 from the starting index element of the passed array.
  545. */
  546. Color4.FromArray = function (array, offset) {
  547. if (offset === void 0) { offset = 0; }
  548. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  549. };
  550. /**
  551. * Creates a new Color4 from the passed integers ( < 256 ).
  552. */
  553. Color4.FromInts = function (r, g, b, a) {
  554. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  555. };
  556. Color4.CheckColors4 = function (colors, count) {
  557. // Check if color3 was used
  558. if (colors.length === count * 3) {
  559. var colors4 = [];
  560. for (var index = 0; index < colors.length; index += 3) {
  561. var newIndex = (index / 3) * 4;
  562. colors4[newIndex] = colors[index];
  563. colors4[newIndex + 1] = colors[index + 1];
  564. colors4[newIndex + 2] = colors[index + 2];
  565. colors4[newIndex + 3] = 1.0;
  566. }
  567. return colors4;
  568. }
  569. return colors;
  570. };
  571. return Color4;
  572. }());
  573. BABYLON.Color4 = Color4;
  574. var Vector2 = (function () {
  575. /**
  576. * Creates a new Vector2 from the passed x and y coordinates.
  577. */
  578. function Vector2(x, y) {
  579. this.x = x;
  580. this.y = y;
  581. }
  582. /**
  583. * Returns a string with the Vector2 coordinates.
  584. */
  585. Vector2.prototype.toString = function () {
  586. return "{X: " + this.x + " Y:" + this.y + "}";
  587. };
  588. /**
  589. * Returns the string "Vector2"
  590. */
  591. Vector2.prototype.getClassName = function () {
  592. return "Vector2";
  593. };
  594. /**
  595. * Returns the Vector2 hash code as a number.
  596. */
  597. Vector2.prototype.getHashCode = function () {
  598. var hash = this.x || 0;
  599. hash = (hash * 397) ^ (this.y || 0);
  600. return hash;
  601. };
  602. // Operators
  603. /**
  604. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  605. * Returns the Vector2.
  606. */
  607. Vector2.prototype.toArray = function (array, index) {
  608. if (index === void 0) { index = 0; }
  609. array[index] = this.x;
  610. array[index + 1] = this.y;
  611. return this;
  612. };
  613. /**
  614. * Returns a new array with 2 elements : the Vector2 coordinates.
  615. */
  616. Vector2.prototype.asArray = function () {
  617. var result = [];
  618. this.toArray(result, 0);
  619. return result;
  620. };
  621. /**
  622. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  623. * Returns the updated Vector2.
  624. */
  625. Vector2.prototype.copyFrom = function (source) {
  626. this.x = source.x;
  627. this.y = source.y;
  628. return this;
  629. };
  630. /**
  631. * Sets the Vector2 coordinates with the passed floats.
  632. * Returns the updated Vector2.
  633. */
  634. Vector2.prototype.copyFromFloats = function (x, y) {
  635. this.x = x;
  636. this.y = y;
  637. return this;
  638. };
  639. /**
  640. * Sets the Vector2 coordinates with the passed floats.
  641. * Returns the updated Vector2.
  642. */
  643. Vector2.prototype.set = function (x, y) {
  644. return this.copyFromFloats(x, y);
  645. };
  646. /**
  647. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  648. */
  649. Vector2.prototype.add = function (otherVector) {
  650. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  651. };
  652. /**
  653. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  654. * Returns the Vector2.
  655. */
  656. Vector2.prototype.addToRef = function (otherVector, result) {
  657. result.x = this.x + otherVector.x;
  658. result.y = this.y + otherVector.y;
  659. return this;
  660. };
  661. /**
  662. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  663. * Returns the updated Vector2.
  664. */
  665. Vector2.prototype.addInPlace = function (otherVector) {
  666. this.x += otherVector.x;
  667. this.y += otherVector.y;
  668. return this;
  669. };
  670. /**
  671. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  672. */
  673. Vector2.prototype.addVector3 = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  678. */
  679. Vector2.prototype.subtract = function (otherVector) {
  680. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  681. };
  682. /**
  683. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  684. * Returns the Vector2.
  685. */
  686. Vector2.prototype.subtractToRef = function (otherVector, result) {
  687. result.x = this.x - otherVector.x;
  688. result.y = this.y - otherVector.y;
  689. return this;
  690. };
  691. /**
  692. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  693. * Returns the updated Vector2.
  694. */
  695. Vector2.prototype.subtractInPlace = function (otherVector) {
  696. this.x -= otherVector.x;
  697. this.y -= otherVector.y;
  698. return this;
  699. };
  700. /**
  701. * Multiplies in place the current Vector2 coordinates by the passed ones.
  702. * Returns the updated Vector2.
  703. */
  704. Vector2.prototype.multiplyInPlace = function (otherVector) {
  705. this.x *= otherVector.x;
  706. this.y *= otherVector.y;
  707. return this;
  708. };
  709. /**
  710. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  711. */
  712. Vector2.prototype.multiply = function (otherVector) {
  713. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  714. };
  715. /**
  716. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  717. * Returns the Vector2.
  718. */
  719. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  720. result.x = this.x * otherVector.x;
  721. result.y = this.y * otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  726. */
  727. Vector2.prototype.multiplyByFloats = function (x, y) {
  728. return new Vector2(this.x * x, this.y * y);
  729. };
  730. /**
  731. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  732. */
  733. Vector2.prototype.divide = function (otherVector) {
  734. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  735. };
  736. /**
  737. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  738. * Returns the Vector2.
  739. */
  740. Vector2.prototype.divideToRef = function (otherVector, result) {
  741. result.x = this.x / otherVector.x;
  742. result.y = this.y / otherVector.y;
  743. return this;
  744. };
  745. /**
  746. * Returns a new Vector2 with current Vector2 negated coordinates.
  747. */
  748. Vector2.prototype.negate = function () {
  749. return new Vector2(-this.x, -this.y);
  750. };
  751. /**
  752. * Multiply the Vector2 coordinates by scale.
  753. * Returns the updated Vector2.
  754. */
  755. Vector2.prototype.scaleInPlace = function (scale) {
  756. this.x *= scale;
  757. this.y *= scale;
  758. return this;
  759. };
  760. /**
  761. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  762. */
  763. Vector2.prototype.scale = function (scale) {
  764. return new Vector2(this.x * scale, this.y * scale);
  765. };
  766. /**
  767. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  768. */
  769. Vector2.prototype.equals = function (otherVector) {
  770. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  771. };
  772. /**
  773. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  774. */
  775. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  776. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  777. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  778. };
  779. // Properties
  780. /**
  781. * Returns the vector length (float).
  782. */
  783. Vector2.prototype.length = function () {
  784. return Math.sqrt(this.x * this.x + this.y * this.y);
  785. };
  786. /**
  787. * Returns the vector squared length (float);
  788. */
  789. Vector2.prototype.lengthSquared = function () {
  790. return (this.x * this.x + this.y * this.y);
  791. };
  792. // Methods
  793. /**
  794. * Normalize the vector.
  795. * Returns the updated Vector2.
  796. */
  797. Vector2.prototype.normalize = function () {
  798. var len = this.length();
  799. if (len === 0)
  800. return this;
  801. var num = 1.0 / len;
  802. this.x *= num;
  803. this.y *= num;
  804. return this;
  805. };
  806. /**
  807. * Returns a new Vector2 copied from the Vector2.
  808. */
  809. Vector2.prototype.clone = function () {
  810. return new Vector2(this.x, this.y);
  811. };
  812. // Statics
  813. /**
  814. * Returns a new Vector2(0, 0)
  815. */
  816. Vector2.Zero = function () {
  817. return new Vector2(0, 0);
  818. };
  819. /**
  820. * Returns a new Vector2 set from the passed index element of the passed array or Float32Array.
  821. */
  822. Vector2.FromArray = function (array, offset) {
  823. if (offset === void 0) { offset = 0; }
  824. return new Vector2(array[offset], array[offset + 1]);
  825. };
  826. /**
  827. * Sets "result" from the passed index element of the passed array or Float32Array.
  828. * Returns the Vector2.
  829. */
  830. Vector2.FromArrayToRef = function (array, offset, result) {
  831. result.x = array[offset];
  832. result.y = array[offset + 1];
  833. };
  834. /**
  835. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  836. */
  837. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  838. var squared = amount * amount;
  839. var cubed = amount * squared;
  840. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  841. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  842. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  843. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  844. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  845. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  846. return new Vector2(x, y);
  847. };
  848. /**
  849. * 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".
  850. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  851. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  852. */
  853. Vector2.Clamp = function (value, min, max) {
  854. var x = value.x;
  855. x = (x > max.x) ? max.x : x;
  856. x = (x < min.x) ? min.x : x;
  857. var y = value.y;
  858. y = (y > max.y) ? max.y : y;
  859. y = (y < min.y) ? min.y : y;
  860. return new Vector2(x, y);
  861. };
  862. /**
  863. * Returns a new Vecto2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  864. */
  865. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  866. var squared = amount * amount;
  867. var cubed = amount * squared;
  868. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  869. var part2 = (-2.0 * cubed) + (3.0 * squared);
  870. var part3 = (cubed - (2.0 * squared)) + amount;
  871. var part4 = cubed - squared;
  872. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  873. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  874. return new Vector2(x, y);
  875. };
  876. /**
  877. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  878. */
  879. Vector2.Lerp = function (start, end, amount) {
  880. var x = start.x + ((end.x - start.x) * amount);
  881. var y = start.y + ((end.y - start.y) * amount);
  882. return new Vector2(x, y);
  883. };
  884. /**
  885. * Returns the dot product (float) of the vector "left" and the vector "right".
  886. */
  887. Vector2.Dot = function (left, right) {
  888. return left.x * right.x + left.y * right.y;
  889. };
  890. /**
  891. * Returns a new Vector2 equal to the normalized passed vector.
  892. */
  893. Vector2.Normalize = function (vector) {
  894. var newVector = vector.clone();
  895. newVector.normalize();
  896. return newVector;
  897. };
  898. /**
  899. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  900. */
  901. Vector2.Minimize = function (left, right) {
  902. var x = (left.x < right.x) ? left.x : right.x;
  903. var y = (left.y < right.y) ? left.y : right.y;
  904. return new Vector2(x, y);
  905. };
  906. /**
  907. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  908. */
  909. Vector2.Maximize = function (left, right) {
  910. var x = (left.x > right.x) ? left.x : right.x;
  911. var y = (left.y > right.y) ? left.y : right.y;
  912. return new Vector2(x, y);
  913. };
  914. /**
  915. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  916. */
  917. Vector2.Transform = function (vector, transformation) {
  918. var r = Vector2.Zero();
  919. Vector2.TransformToRef(vector, transformation, r);
  920. return r;
  921. };
  922. /**
  923. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  924. */
  925. Vector2.TransformToRef = function (vector, transformation, result) {
  926. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  927. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  928. result.x = x;
  929. result.y = y;
  930. };
  931. /**
  932. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  933. */
  934. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  935. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  936. var sign = a < 0 ? -1 : 1;
  937. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  938. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  939. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  940. };
  941. /**
  942. * Returns the distance (float) between the vectors "value1" and "value2".
  943. */
  944. Vector2.Distance = function (value1, value2) {
  945. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  946. };
  947. /**
  948. * Returns the squared distance (float) between the vectors "value1" and "value2".
  949. */
  950. Vector2.DistanceSquared = function (value1, value2) {
  951. var x = value1.x - value2.x;
  952. var y = value1.y - value2.y;
  953. return (x * x) + (y * y);
  954. };
  955. /**
  956. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  957. */
  958. Vector2.Center = function (value1, value2) {
  959. var center = value1.add(value2);
  960. center.scaleInPlace(0.5);
  961. return center;
  962. };
  963. /**
  964. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  965. */
  966. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  967. var l2 = Vector2.DistanceSquared(segA, segB);
  968. if (l2 === 0.0) {
  969. return Vector2.Distance(p, segA);
  970. }
  971. var v = segB.subtract(segA);
  972. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  973. var proj = segA.add(v.multiplyByFloats(t, t));
  974. return Vector2.Distance(p, proj);
  975. };
  976. return Vector2;
  977. }());
  978. BABYLON.Vector2 = Vector2;
  979. var Vector3 = (function () {
  980. /**
  981. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  982. * A Vector3 is the main object used in 3D geometry.
  983. * It can represent etiher the coordinates of a point the space, either a direction.
  984. */
  985. function Vector3(x, y, z) {
  986. this.x = x;
  987. this.y = y;
  988. this.z = z;
  989. }
  990. /**
  991. * Returns a string with the Vector3 coordinates.
  992. */
  993. Vector3.prototype.toString = function () {
  994. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  995. };
  996. /**
  997. * Returns the string "Vector3"
  998. */
  999. Vector3.prototype.getClassName = function () {
  1000. return "Vector3";
  1001. };
  1002. /**
  1003. * Returns the Vector hash code.
  1004. */
  1005. Vector3.prototype.getHashCode = function () {
  1006. var hash = this.x || 0;
  1007. hash = (hash * 397) ^ (this.y || 0);
  1008. hash = (hash * 397) ^ (this.z || 0);
  1009. return hash;
  1010. };
  1011. // Operators
  1012. /**
  1013. * Returns a new array with three elements : the coordinates the Vector3.
  1014. */
  1015. Vector3.prototype.asArray = function () {
  1016. var result = [];
  1017. this.toArray(result, 0);
  1018. return result;
  1019. };
  1020. /**
  1021. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1022. * Returns the Vector3.
  1023. */
  1024. Vector3.prototype.toArray = function (array, index) {
  1025. if (index === void 0) { index = 0; }
  1026. array[index] = this.x;
  1027. array[index + 1] = this.y;
  1028. array[index + 2] = this.z;
  1029. return this;
  1030. };
  1031. /**
  1032. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1033. */
  1034. Vector3.prototype.toQuaternion = function () {
  1035. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1036. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1037. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1038. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1039. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1040. var cosy = Math.cos(this.y * 0.5);
  1041. var siny = Math.sin(this.y * 0.5);
  1042. result.x = coszMinusx * siny;
  1043. result.y = -sinzMinusx * siny;
  1044. result.z = sinxPlusz * cosy;
  1045. result.w = cosxPlusz * cosy;
  1046. return result;
  1047. };
  1048. /**
  1049. * Adds the passed vector to the current Vector3.
  1050. * Returns the updated Vector3.
  1051. */
  1052. Vector3.prototype.addInPlace = function (otherVector) {
  1053. this.x += otherVector.x;
  1054. this.y += otherVector.y;
  1055. this.z += otherVector.z;
  1056. return this;
  1057. };
  1058. /**
  1059. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1060. */
  1061. Vector3.prototype.add = function (otherVector) {
  1062. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1063. };
  1064. /**
  1065. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1066. * Returns the current Vector3.
  1067. */
  1068. Vector3.prototype.addToRef = function (otherVector, result) {
  1069. result.x = this.x + otherVector.x;
  1070. result.y = this.y + otherVector.y;
  1071. result.z = this.z + otherVector.z;
  1072. return this;
  1073. };
  1074. /**
  1075. * Subtract the passed vector from the current Vector3.
  1076. * Returns the updated Vector3.
  1077. */
  1078. Vector3.prototype.subtractInPlace = function (otherVector) {
  1079. this.x -= otherVector.x;
  1080. this.y -= otherVector.y;
  1081. this.z -= otherVector.z;
  1082. return this;
  1083. };
  1084. /**
  1085. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1086. */
  1087. Vector3.prototype.subtract = function (otherVector) {
  1088. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1089. };
  1090. /**
  1091. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1092. * Returns the current Vector3.
  1093. */
  1094. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1095. result.x = this.x - otherVector.x;
  1096. result.y = this.y - otherVector.y;
  1097. result.z = this.z - otherVector.z;
  1098. return this;
  1099. };
  1100. /**
  1101. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1102. */
  1103. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1104. return new Vector3(this.x - x, this.y - y, this.z - z);
  1105. };
  1106. /**
  1107. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1108. * Returns the current Vector3.
  1109. */
  1110. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1111. result.x = this.x - x;
  1112. result.y = this.y - y;
  1113. result.z = this.z - z;
  1114. return this;
  1115. };
  1116. /**
  1117. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1118. */
  1119. Vector3.prototype.negate = function () {
  1120. return new Vector3(-this.x, -this.y, -this.z);
  1121. };
  1122. /**
  1123. * Multiplies the Vector3 coordinates by the float "scale".
  1124. * Returns the updated Vector3.
  1125. */
  1126. Vector3.prototype.scaleInPlace = function (scale) {
  1127. this.x *= scale;
  1128. this.y *= scale;
  1129. this.z *= scale;
  1130. return this;
  1131. };
  1132. /**
  1133. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1134. */
  1135. Vector3.prototype.scale = function (scale) {
  1136. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1137. };
  1138. /**
  1139. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1140. * Returns the current Vector3.
  1141. */
  1142. Vector3.prototype.scaleToRef = function (scale, result) {
  1143. result.x = this.x * scale;
  1144. result.y = this.y * scale;
  1145. result.z = this.z * scale;
  1146. return this;
  1147. };
  1148. /**
  1149. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1150. */
  1151. Vector3.prototype.equals = function (otherVector) {
  1152. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1153. };
  1154. /**
  1155. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1156. */
  1157. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1158. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1159. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1160. };
  1161. /**
  1162. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1163. */
  1164. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1165. return this.x === x && this.y === y && this.z === z;
  1166. };
  1167. /**
  1168. * Muliplies the current Vector3 coordinates by the passed ones.
  1169. * Returns the updated Vector3.
  1170. */
  1171. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1172. this.x *= otherVector.x;
  1173. this.y *= otherVector.y;
  1174. this.z *= otherVector.z;
  1175. return this;
  1176. };
  1177. /**
  1178. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1179. */
  1180. Vector3.prototype.multiply = function (otherVector) {
  1181. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1182. };
  1183. /**
  1184. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1185. * Returns the current Vector3.
  1186. */
  1187. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1188. result.x = this.x * otherVector.x;
  1189. result.y = this.y * otherVector.y;
  1190. result.z = this.z * otherVector.z;
  1191. return this;
  1192. };
  1193. /**
  1194. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1195. */
  1196. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1197. return new Vector3(this.x * x, this.y * y, this.z * z);
  1198. };
  1199. /**
  1200. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1201. */
  1202. Vector3.prototype.divide = function (otherVector) {
  1203. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1204. };
  1205. /**
  1206. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1207. * Returns the current Vector3.
  1208. */
  1209. Vector3.prototype.divideToRef = function (otherVector, result) {
  1210. result.x = this.x / otherVector.x;
  1211. result.y = this.y / otherVector.y;
  1212. result.z = this.z / otherVector.z;
  1213. return this;
  1214. };
  1215. /**
  1216. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1217. * Returns the updated Vector3.
  1218. */
  1219. Vector3.prototype.MinimizeInPlace = function (other) {
  1220. if (other.x < this.x)
  1221. this.x = other.x;
  1222. if (other.y < this.y)
  1223. this.y = other.y;
  1224. if (other.z < this.z)
  1225. this.z = other.z;
  1226. return this;
  1227. };
  1228. /**
  1229. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1230. * Returns the updated Vector3.
  1231. */
  1232. Vector3.prototype.MaximizeInPlace = function (other) {
  1233. if (other.x > this.x)
  1234. this.x = other.x;
  1235. if (other.y > this.y)
  1236. this.y = other.y;
  1237. if (other.z > this.z)
  1238. this.z = other.z;
  1239. return this;
  1240. };
  1241. // Properties
  1242. /**
  1243. * Returns the length of the Vector3 (float).
  1244. */
  1245. Vector3.prototype.length = function () {
  1246. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1247. };
  1248. /**
  1249. * Returns the squared length of the Vector3 (float).
  1250. */
  1251. Vector3.prototype.lengthSquared = function () {
  1252. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1253. };
  1254. // Methods
  1255. /**
  1256. * Normalize the current Vector3.
  1257. * Returns the updated Vector3.
  1258. */
  1259. Vector3.prototype.normalize = function () {
  1260. var len = this.length();
  1261. if (len === 0 || len === 1.0)
  1262. return this;
  1263. var num = 1.0 / len;
  1264. this.x *= num;
  1265. this.y *= num;
  1266. this.z *= num;
  1267. return this;
  1268. };
  1269. /**
  1270. * Returns a new Vector3 copied from the current Vector3.
  1271. */
  1272. Vector3.prototype.clone = function () {
  1273. return new Vector3(this.x, this.y, this.z);
  1274. };
  1275. /**
  1276. * Copies the passed vector coordinates to the current Vector3 ones.
  1277. * Returns the updated Vector3.
  1278. */
  1279. Vector3.prototype.copyFrom = function (source) {
  1280. this.x = source.x;
  1281. this.y = source.y;
  1282. this.z = source.z;
  1283. return this;
  1284. };
  1285. /**
  1286. * Copies the passed floats to the current Vector3 coordinates.
  1287. * Returns the updated Vector3.
  1288. */
  1289. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1290. this.x = x;
  1291. this.y = y;
  1292. this.z = z;
  1293. return this;
  1294. };
  1295. /**
  1296. * Copies the passed floats to the current Vector3 coordinates.
  1297. * Returns the updated Vector3.
  1298. */
  1299. Vector3.prototype.set = function (x, y, z) {
  1300. return this.copyFromFloats(x, y, z);
  1301. };
  1302. // Statics
  1303. /**
  1304. *
  1305. */
  1306. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1307. var d0 = Vector3.Dot(vector0, axis) - size;
  1308. var d1 = Vector3.Dot(vector1, axis) - size;
  1309. var s = d0 / (d0 - d1);
  1310. return s;
  1311. };
  1312. /**
  1313. * Returns a new Vector3 set from the index "offset" of the passed array or Float32Array.
  1314. */
  1315. Vector3.FromArray = function (array, offset) {
  1316. if (!offset) {
  1317. offset = 0;
  1318. }
  1319. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1320. };
  1321. /**
  1322. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1323. */
  1324. Vector3.FromFloatArray = function (array, offset) {
  1325. if (!offset) {
  1326. offset = 0;
  1327. }
  1328. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1329. };
  1330. /**
  1331. * Sets the passed vector "result" with the element values from the index "offset" of the passed array or Float32Array.
  1332. */
  1333. Vector3.FromArrayToRef = function (array, offset, result) {
  1334. result.x = array[offset];
  1335. result.y = array[offset + 1];
  1336. result.z = array[offset + 2];
  1337. };
  1338. /**
  1339. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1340. */
  1341. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1342. result.x = array[offset];
  1343. result.y = array[offset + 1];
  1344. result.z = array[offset + 2];
  1345. };
  1346. /**
  1347. * Sets the passed vector "result" with the passed floats.
  1348. */
  1349. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1350. result.x = x;
  1351. result.y = y;
  1352. result.z = z;
  1353. };
  1354. /**
  1355. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1356. */
  1357. Vector3.Zero = function () {
  1358. return new Vector3(0.0, 0.0, 0.0);
  1359. };
  1360. /**
  1361. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1362. */
  1363. Vector3.Up = function () {
  1364. return new Vector3(0.0, 1.0, 0.0);
  1365. };
  1366. /**
  1367. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1368. */
  1369. Vector3.Forward = function () {
  1370. return new Vector3(0.0, 0.0, 1.0);
  1371. };
  1372. /**
  1373. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1374. */
  1375. Vector3.Right = function () {
  1376. return new Vector3(1.0, 0.0, 0.0);
  1377. };
  1378. /**
  1379. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1380. */
  1381. Vector3.Left = function () {
  1382. return new Vector3(-1.0, 0.0, 0.0);
  1383. };
  1384. /**
  1385. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1386. * This method computes tranformed coordinates only, not transformed direction vectors.
  1387. */
  1388. Vector3.TransformCoordinates = function (vector, transformation) {
  1389. var result = Vector3.Zero();
  1390. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1391. return result;
  1392. };
  1393. /**
  1394. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1395. * This method computes tranformed coordinates only, not transformed direction vectors.
  1396. */
  1397. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1398. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1399. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1400. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1401. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1402. result.x = x / w;
  1403. result.y = y / w;
  1404. result.z = z / w;
  1405. };
  1406. /**
  1407. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1408. * This method computes tranformed coordinates only, not transformed direction vectors.
  1409. */
  1410. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1411. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1412. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1413. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1414. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1415. result.x = rx / rw;
  1416. result.y = ry / rw;
  1417. result.z = rz / rw;
  1418. };
  1419. /**
  1420. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1421. * This methods computes transformed normalized direction vectors only.
  1422. */
  1423. Vector3.TransformNormal = function (vector, transformation) {
  1424. var result = Vector3.Zero();
  1425. Vector3.TransformNormalToRef(vector, transformation, result);
  1426. return result;
  1427. };
  1428. /**
  1429. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1430. * This methods computes transformed normalized direction vectors only.
  1431. */
  1432. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1433. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1434. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1435. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1436. result.x = x;
  1437. result.y = y;
  1438. result.z = z;
  1439. };
  1440. /**
  1441. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1442. * This methods computes transformed normalized direction vectors only.
  1443. */
  1444. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1445. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1446. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1447. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1448. };
  1449. /**
  1450. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1451. */
  1452. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1453. var squared = amount * amount;
  1454. var cubed = amount * squared;
  1455. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1456. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1457. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1458. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1459. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1460. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1461. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1462. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1463. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1464. return new Vector3(x, y, z);
  1465. };
  1466. /**
  1467. * 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".
  1468. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1469. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1470. */
  1471. Vector3.Clamp = function (value, min, max) {
  1472. var x = value.x;
  1473. x = (x > max.x) ? max.x : x;
  1474. x = (x < min.x) ? min.x : x;
  1475. var y = value.y;
  1476. y = (y > max.y) ? max.y : y;
  1477. y = (y < min.y) ? min.y : y;
  1478. var z = value.z;
  1479. z = (z > max.z) ? max.z : z;
  1480. z = (z < min.z) ? min.z : z;
  1481. return new Vector3(x, y, z);
  1482. };
  1483. /**
  1484. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1485. */
  1486. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1487. var squared = amount * amount;
  1488. var cubed = amount * squared;
  1489. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1490. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1491. var part3 = (cubed - (2.0 * squared)) + amount;
  1492. var part4 = cubed - squared;
  1493. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1494. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1495. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1496. return new Vector3(x, y, z);
  1497. };
  1498. /**
  1499. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1500. */
  1501. Vector3.Lerp = function (start, end, amount) {
  1502. var result = new Vector3(0, 0, 0);
  1503. Vector3.LerpToRef(start, end, amount, result);
  1504. return result;
  1505. };
  1506. /**
  1507. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1508. */
  1509. Vector3.LerpToRef = function (start, end, amount, result) {
  1510. result.x = start.x + ((end.x - start.x) * amount);
  1511. result.y = start.y + ((end.y - start.y) * amount);
  1512. result.z = start.z + ((end.z - start.z) * amount);
  1513. };
  1514. /**
  1515. * Returns the dot product (float) between the vectors "left" and "right".
  1516. */
  1517. Vector3.Dot = function (left, right) {
  1518. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1519. };
  1520. /**
  1521. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1522. * The cross product is then orthogonal to both "left" and "right".
  1523. */
  1524. Vector3.Cross = function (left, right) {
  1525. var result = Vector3.Zero();
  1526. Vector3.CrossToRef(left, right, result);
  1527. return result;
  1528. };
  1529. /**
  1530. * Sets the passed vector "result" with the cross product of "left" and "right".
  1531. * The cross product is then orthogonal to both "left" and "right".
  1532. */
  1533. Vector3.CrossToRef = function (left, right, result) {
  1534. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1535. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1536. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1537. result.copyFrom(MathTmp.Vector3[0]);
  1538. };
  1539. /**
  1540. * Returns a new Vector3 as the normalization of the passed vector.
  1541. */
  1542. Vector3.Normalize = function (vector) {
  1543. var result = Vector3.Zero();
  1544. Vector3.NormalizeToRef(vector, result);
  1545. return result;
  1546. };
  1547. /**
  1548. * Sets the passed vector "result" with the normalization of the passed first vector.
  1549. */
  1550. Vector3.NormalizeToRef = function (vector, result) {
  1551. result.copyFrom(vector);
  1552. result.normalize();
  1553. };
  1554. Vector3.Project = function (vector, world, transform, viewport) {
  1555. var cw = viewport.width;
  1556. var ch = viewport.height;
  1557. var cx = viewport.x;
  1558. var cy = viewport.y;
  1559. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1560. 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);
  1561. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1562. world.multiplyToRef(transform, matrix);
  1563. matrix.multiplyToRef(viewportMatrix, matrix);
  1564. return Vector3.TransformCoordinates(vector, matrix);
  1565. };
  1566. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1567. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1568. world.multiplyToRef(transform, matrix);
  1569. matrix.invert();
  1570. source.x = source.x / viewportWidth * 2 - 1;
  1571. source.y = -(source.y / viewportHeight * 2 - 1);
  1572. var vector = Vector3.TransformCoordinates(source, matrix);
  1573. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1574. if (MathTools.WithinEpsilon(num, 1.0)) {
  1575. vector = vector.scale(1.0 / num);
  1576. }
  1577. return vector;
  1578. };
  1579. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1580. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1581. world.multiplyToRef(view, matrix);
  1582. matrix.multiplyToRef(projection, matrix);
  1583. matrix.invert();
  1584. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1585. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1586. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1587. if (MathTools.WithinEpsilon(num, 1.0)) {
  1588. vector = vector.scale(1.0 / num);
  1589. }
  1590. return vector;
  1591. };
  1592. Vector3.Minimize = function (left, right) {
  1593. var min = left.clone();
  1594. min.MinimizeInPlace(right);
  1595. return min;
  1596. };
  1597. Vector3.Maximize = function (left, right) {
  1598. var max = left.clone();
  1599. max.MaximizeInPlace(right);
  1600. return max;
  1601. };
  1602. /**
  1603. * Returns the distance (float) between the vectors "value1" and "value2".
  1604. */
  1605. Vector3.Distance = function (value1, value2) {
  1606. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1607. };
  1608. /**
  1609. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1610. */
  1611. Vector3.DistanceSquared = function (value1, value2) {
  1612. var x = value1.x - value2.x;
  1613. var y = value1.y - value2.y;
  1614. var z = value1.z - value2.z;
  1615. return (x * x) + (y * y) + (z * z);
  1616. };
  1617. /**
  1618. * Returns a new Vector3 located at the center between "value1" and "value2".
  1619. */
  1620. Vector3.Center = function (value1, value2) {
  1621. var center = value1.add(value2);
  1622. center.scaleInPlace(0.5);
  1623. return center;
  1624. };
  1625. /**
  1626. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1627. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1628. * to something in order to rotate it from its local system to the given target system.
  1629. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1630. * Returns a new Vector3.
  1631. */
  1632. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1633. var rotation = Vector3.Zero();
  1634. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1635. return rotation;
  1636. };
  1637. /**
  1638. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1639. */
  1640. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1641. var quat = MathTmp.Quaternion[0];
  1642. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1643. quat.toEulerAnglesToRef(ref);
  1644. };
  1645. return Vector3;
  1646. }());
  1647. BABYLON.Vector3 = Vector3;
  1648. //Vector4 class created for EulerAngle class conversion to Quaternion
  1649. var Vector4 = (function () {
  1650. /**
  1651. * Creates a Vector4 object from the passed floats.
  1652. */
  1653. function Vector4(x, y, z, w) {
  1654. this.x = x;
  1655. this.y = y;
  1656. this.z = z;
  1657. this.w = w;
  1658. }
  1659. /**
  1660. * Returns the string with the Vector4 coordinates.
  1661. */
  1662. Vector4.prototype.toString = function () {
  1663. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1664. };
  1665. /**
  1666. * Returns the string "Vector4".
  1667. */
  1668. Vector4.prototype.getClassName = function () {
  1669. return "Vector4";
  1670. };
  1671. /**
  1672. * Returns the Vector4 hash code.
  1673. */
  1674. Vector4.prototype.getHashCode = function () {
  1675. var hash = this.x || 0;
  1676. hash = (hash * 397) ^ (this.y || 0);
  1677. hash = (hash * 397) ^ (this.z || 0);
  1678. hash = (hash * 397) ^ (this.w || 0);
  1679. return hash;
  1680. };
  1681. // Operators
  1682. /**
  1683. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1684. */
  1685. Vector4.prototype.asArray = function () {
  1686. var result = [];
  1687. this.toArray(result, 0);
  1688. return result;
  1689. };
  1690. /**
  1691. * Populates the passed array from the passed index with the Vector4 coordinates.
  1692. * Returns the Vector4.
  1693. */
  1694. Vector4.prototype.toArray = function (array, index) {
  1695. if (index === undefined) {
  1696. index = 0;
  1697. }
  1698. array[index] = this.x;
  1699. array[index + 1] = this.y;
  1700. array[index + 2] = this.z;
  1701. array[index + 3] = this.w;
  1702. return this;
  1703. };
  1704. /**
  1705. * Adds the passed vector to the current Vector4.
  1706. * Returns the updated Vector4.
  1707. */
  1708. Vector4.prototype.addInPlace = function (otherVector) {
  1709. this.x += otherVector.x;
  1710. this.y += otherVector.y;
  1711. this.z += otherVector.z;
  1712. this.w += otherVector.w;
  1713. return this;
  1714. };
  1715. /**
  1716. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1717. */
  1718. Vector4.prototype.add = function (otherVector) {
  1719. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1720. };
  1721. /**
  1722. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1723. * Returns the current Vector4.
  1724. */
  1725. Vector4.prototype.addToRef = function (otherVector, result) {
  1726. result.x = this.x + otherVector.x;
  1727. result.y = this.y + otherVector.y;
  1728. result.z = this.z + otherVector.z;
  1729. result.w = this.w + otherVector.w;
  1730. return this;
  1731. };
  1732. /**
  1733. * Subtract in place the passed vector from the current Vector4.
  1734. * Returns the updated Vector4.
  1735. */
  1736. Vector4.prototype.subtractInPlace = function (otherVector) {
  1737. this.x -= otherVector.x;
  1738. this.y -= otherVector.y;
  1739. this.z -= otherVector.z;
  1740. this.w -= otherVector.w;
  1741. return this;
  1742. };
  1743. /**
  1744. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1745. */
  1746. Vector4.prototype.subtract = function (otherVector) {
  1747. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1748. };
  1749. /**
  1750. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1751. * Returns the current Vector4.
  1752. */
  1753. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1754. result.x = this.x - otherVector.x;
  1755. result.y = this.y - otherVector.y;
  1756. result.z = this.z - otherVector.z;
  1757. result.w = this.w - otherVector.w;
  1758. return this;
  1759. };
  1760. /**
  1761. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1762. */
  1763. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1764. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1765. };
  1766. /**
  1767. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1768. * Returns the current Vector4.
  1769. */
  1770. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1771. result.x = this.x - x;
  1772. result.y = this.y - y;
  1773. result.z = this.z - z;
  1774. result.w = this.w - w;
  1775. return this;
  1776. };
  1777. /**
  1778. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1779. */
  1780. Vector4.prototype.negate = function () {
  1781. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1782. };
  1783. /**
  1784. * Multiplies the current Vector4 coordinates by scale (float).
  1785. * Returns the updated Vector4.
  1786. */
  1787. Vector4.prototype.scaleInPlace = function (scale) {
  1788. this.x *= scale;
  1789. this.y *= scale;
  1790. this.z *= scale;
  1791. this.w *= scale;
  1792. return this;
  1793. };
  1794. /**
  1795. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1796. */
  1797. Vector4.prototype.scale = function (scale) {
  1798. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1799. };
  1800. /**
  1801. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1802. * Returns the current Vector4.
  1803. */
  1804. Vector4.prototype.scaleToRef = function (scale, result) {
  1805. result.x = this.x * scale;
  1806. result.y = this.y * scale;
  1807. result.z = this.z * scale;
  1808. result.w = this.w * scale;
  1809. return this;
  1810. };
  1811. /**
  1812. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1813. */
  1814. Vector4.prototype.equals = function (otherVector) {
  1815. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1816. };
  1817. /**
  1818. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1819. */
  1820. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1821. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1822. return otherVector
  1823. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1824. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1825. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1826. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1827. };
  1828. /**
  1829. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1830. */
  1831. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1832. return this.x === x && this.y === y && this.z === z && this.w === w;
  1833. };
  1834. /**
  1835. * Multiplies in place the current Vector4 by the passed one.
  1836. * Returns the updated Vector4.
  1837. */
  1838. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1839. this.x *= otherVector.x;
  1840. this.y *= otherVector.y;
  1841. this.z *= otherVector.z;
  1842. this.w *= otherVector.w;
  1843. return this;
  1844. };
  1845. /**
  1846. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1847. */
  1848. Vector4.prototype.multiply = function (otherVector) {
  1849. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1850. };
  1851. /**
  1852. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1853. * Returns the current Vector4.
  1854. */
  1855. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1856. result.x = this.x * otherVector.x;
  1857. result.y = this.y * otherVector.y;
  1858. result.z = this.z * otherVector.z;
  1859. result.w = this.w * otherVector.w;
  1860. return this;
  1861. };
  1862. /**
  1863. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1864. */
  1865. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1866. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1867. };
  1868. /**
  1869. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1870. */
  1871. Vector4.prototype.divide = function (otherVector) {
  1872. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1873. };
  1874. /**
  1875. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1876. * Returns the current Vector4.
  1877. */
  1878. Vector4.prototype.divideToRef = function (otherVector, result) {
  1879. result.x = this.x / otherVector.x;
  1880. result.y = this.y / otherVector.y;
  1881. result.z = this.z / otherVector.z;
  1882. result.w = this.w / otherVector.w;
  1883. return this;
  1884. };
  1885. /**
  1886. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1887. */
  1888. Vector4.prototype.MinimizeInPlace = function (other) {
  1889. if (other.x < this.x)
  1890. this.x = other.x;
  1891. if (other.y < this.y)
  1892. this.y = other.y;
  1893. if (other.z < this.z)
  1894. this.z = other.z;
  1895. if (other.w < this.w)
  1896. this.w = other.w;
  1897. return this;
  1898. };
  1899. /**
  1900. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1901. */
  1902. Vector4.prototype.MaximizeInPlace = function (other) {
  1903. if (other.x > this.x)
  1904. this.x = other.x;
  1905. if (other.y > this.y)
  1906. this.y = other.y;
  1907. if (other.z > this.z)
  1908. this.z = other.z;
  1909. if (other.w > this.w)
  1910. this.w = other.w;
  1911. return this;
  1912. };
  1913. // Properties
  1914. /**
  1915. * Returns the Vector4 length (float).
  1916. */
  1917. Vector4.prototype.length = function () {
  1918. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1919. };
  1920. /**
  1921. * Returns the Vector4 squared length (float).
  1922. */
  1923. Vector4.prototype.lengthSquared = function () {
  1924. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1925. };
  1926. // Methods
  1927. /**
  1928. * Normalizes in place the Vector4.
  1929. * Returns the updated Vector4.
  1930. */
  1931. Vector4.prototype.normalize = function () {
  1932. var len = this.length();
  1933. if (len === 0)
  1934. return this;
  1935. var num = 1.0 / len;
  1936. this.x *= num;
  1937. this.y *= num;
  1938. this.z *= num;
  1939. this.w *= num;
  1940. return this;
  1941. };
  1942. /**
  1943. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1944. */
  1945. Vector4.prototype.toVector3 = function () {
  1946. return new Vector3(this.x, this.y, this.z);
  1947. };
  1948. /**
  1949. * Returns a new Vector4 copied from the current one.
  1950. */
  1951. Vector4.prototype.clone = function () {
  1952. return new Vector4(this.x, this.y, this.z, this.w);
  1953. };
  1954. /**
  1955. * Updates the current Vector4 with the passed one coordinates.
  1956. * Returns the updated Vector4.
  1957. */
  1958. Vector4.prototype.copyFrom = function (source) {
  1959. this.x = source.x;
  1960. this.y = source.y;
  1961. this.z = source.z;
  1962. this.w = source.w;
  1963. return this;
  1964. };
  1965. /**
  1966. * Updates the current Vector4 coordinates with the passed floats.
  1967. * Returns the updated Vector4.
  1968. */
  1969. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1970. this.x = x;
  1971. this.y = y;
  1972. this.z = z;
  1973. this.w = w;
  1974. return this;
  1975. };
  1976. /**
  1977. * Updates the current Vector4 coordinates with the passed floats.
  1978. * Returns the updated Vector4.
  1979. */
  1980. Vector4.prototype.set = function (x, y, z, w) {
  1981. return this.copyFromFloats(x, y, z, w);
  1982. };
  1983. // Statics
  1984. /**
  1985. * Returns a new Vector4 set from the starting index of the passed array.
  1986. */
  1987. Vector4.FromArray = function (array, offset) {
  1988. if (!offset) {
  1989. offset = 0;
  1990. }
  1991. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1992. };
  1993. /**
  1994. * Updates the passed vector "result" from the starting index of the passed array.
  1995. */
  1996. Vector4.FromArrayToRef = function (array, offset, result) {
  1997. result.x = array[offset];
  1998. result.y = array[offset + 1];
  1999. result.z = array[offset + 2];
  2000. result.w = array[offset + 3];
  2001. };
  2002. /**
  2003. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2004. */
  2005. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2006. result.x = array[offset];
  2007. result.y = array[offset + 1];
  2008. result.z = array[offset + 2];
  2009. result.w = array[offset + 3];
  2010. };
  2011. /**
  2012. * Updates the passed vector "result" coordinates from the passed floats.
  2013. */
  2014. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2015. result.x = x;
  2016. result.y = y;
  2017. result.z = z;
  2018. result.w = w;
  2019. };
  2020. /**
  2021. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2022. */
  2023. Vector4.Zero = function () {
  2024. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2025. };
  2026. /**
  2027. * Returns a new normalized Vector4 from the passed one.
  2028. */
  2029. Vector4.Normalize = function (vector) {
  2030. var result = Vector4.Zero();
  2031. Vector4.NormalizeToRef(vector, result);
  2032. return result;
  2033. };
  2034. /**
  2035. * Updates the passed vector "result" from the normalization of the passed one.
  2036. */
  2037. Vector4.NormalizeToRef = function (vector, result) {
  2038. result.copyFrom(vector);
  2039. result.normalize();
  2040. };
  2041. Vector4.Minimize = function (left, right) {
  2042. var min = left.clone();
  2043. min.MinimizeInPlace(right);
  2044. return min;
  2045. };
  2046. Vector4.Maximize = function (left, right) {
  2047. var max = left.clone();
  2048. max.MaximizeInPlace(right);
  2049. return max;
  2050. };
  2051. /**
  2052. * Returns the distance (float) between the vectors "value1" and "value2".
  2053. */
  2054. Vector4.Distance = function (value1, value2) {
  2055. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2056. };
  2057. /**
  2058. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2059. */
  2060. Vector4.DistanceSquared = function (value1, value2) {
  2061. var x = value1.x - value2.x;
  2062. var y = value1.y - value2.y;
  2063. var z = value1.z - value2.z;
  2064. var w = value1.w - value2.w;
  2065. return (x * x) + (y * y) + (z * z) + (w * w);
  2066. };
  2067. /**
  2068. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2069. */
  2070. Vector4.Center = function (value1, value2) {
  2071. var center = value1.add(value2);
  2072. center.scaleInPlace(0.5);
  2073. return center;
  2074. };
  2075. /**
  2076. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2077. * This methods computes transformed normalized direction vectors only.
  2078. */
  2079. Vector4.TransformNormal = function (vector, transformation) {
  2080. var result = Vector4.Zero();
  2081. Vector4.TransformNormalToRef(vector, transformation, result);
  2082. return result;
  2083. };
  2084. /**
  2085. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2086. * This methods computes transformed normalized direction vectors only.
  2087. */
  2088. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2089. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2090. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2091. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2092. result.x = x;
  2093. result.y = y;
  2094. result.z = z;
  2095. result.w = vector.w;
  2096. };
  2097. /**
  2098. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2099. * This methods computes transformed normalized direction vectors only.
  2100. */
  2101. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2102. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2103. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2104. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2105. result.w = w;
  2106. };
  2107. return Vector4;
  2108. }());
  2109. BABYLON.Vector4 = Vector4;
  2110. var Size = (function () {
  2111. /**
  2112. * Creates a Size object from the passed width and height (floats).
  2113. */
  2114. function Size(width, height) {
  2115. this.width = width;
  2116. this.height = height;
  2117. }
  2118. // Returns a string with the Size width and height.
  2119. Size.prototype.toString = function () {
  2120. return "{W: " + this.width + ", H: " + this.height + "}";
  2121. };
  2122. /**
  2123. * Returns the string "Size"
  2124. */
  2125. Size.prototype.getClassName = function () {
  2126. return "Size";
  2127. };
  2128. /**
  2129. * Returns the Size hash code.
  2130. */
  2131. Size.prototype.getHashCode = function () {
  2132. var hash = this.width || 0;
  2133. hash = (hash * 397) ^ (this.height || 0);
  2134. return hash;
  2135. };
  2136. /**
  2137. * Updates the current size from the passed one.
  2138. * Returns the updated Size.
  2139. */
  2140. Size.prototype.copyFrom = function (src) {
  2141. this.width = src.width;
  2142. this.height = src.height;
  2143. };
  2144. /**
  2145. * Updates in place the current Size from the passed floats.
  2146. * Returns the updated Size.
  2147. */
  2148. Size.prototype.copyFromFloats = function (width, height) {
  2149. this.width = width;
  2150. this.height = height;
  2151. return this;
  2152. };
  2153. /**
  2154. * Updates in place the current Size from the passed floats.
  2155. * Returns the updated Size.
  2156. */
  2157. Size.prototype.set = function (width, height) {
  2158. return this.copyFromFloats(width, height);
  2159. };
  2160. /**
  2161. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2162. */
  2163. Size.prototype.multiplyByFloats = function (w, h) {
  2164. return new Size(this.width * w, this.height * h);
  2165. };
  2166. /**
  2167. * Returns a new Size copied from the passed one.
  2168. */
  2169. Size.prototype.clone = function () {
  2170. return new Size(this.width, this.height);
  2171. };
  2172. /**
  2173. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2174. */
  2175. Size.prototype.equals = function (other) {
  2176. if (!other) {
  2177. return false;
  2178. }
  2179. return (this.width === other.width) && (this.height === other.height);
  2180. };
  2181. Object.defineProperty(Size.prototype, "surface", {
  2182. /**
  2183. * Returns the surface of the Size : width * height (float).
  2184. */
  2185. get: function () {
  2186. return this.width * this.height;
  2187. },
  2188. enumerable: true,
  2189. configurable: true
  2190. });
  2191. /**
  2192. * Returns a new Size set to (0.0, 0.0)
  2193. */
  2194. Size.Zero = function () {
  2195. return new Size(0.0, 0.0);
  2196. };
  2197. /**
  2198. * Returns a new Size set as the addition result of the current Size and the passed one.
  2199. */
  2200. Size.prototype.add = function (otherSize) {
  2201. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2202. return r;
  2203. };
  2204. /**
  2205. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2206. */
  2207. Size.prototype.subtract = function (otherSize) {
  2208. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2209. return r;
  2210. };
  2211. /**
  2212. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2213. */
  2214. Size.Lerp = function (start, end, amount) {
  2215. var w = start.width + ((end.width - start.width) * amount);
  2216. var h = start.height + ((end.height - start.height) * amount);
  2217. return new Size(w, h);
  2218. };
  2219. return Size;
  2220. }());
  2221. BABYLON.Size = Size;
  2222. var Quaternion = (function () {
  2223. /**
  2224. * Creates a new Quaternion from the passed floats.
  2225. */
  2226. function Quaternion(x, y, z, w) {
  2227. if (x === void 0) { x = 0.0; }
  2228. if (y === void 0) { y = 0.0; }
  2229. if (z === void 0) { z = 0.0; }
  2230. if (w === void 0) { w = 1.0; }
  2231. this.x = x;
  2232. this.y = y;
  2233. this.z = z;
  2234. this.w = w;
  2235. }
  2236. /**
  2237. * Returns a string with the Quaternion coordinates.
  2238. */
  2239. Quaternion.prototype.toString = function () {
  2240. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2241. };
  2242. /**
  2243. * Returns the string "Quaternion".
  2244. */
  2245. Quaternion.prototype.getClassName = function () {
  2246. return "Quaternion";
  2247. };
  2248. /**
  2249. * Returns the Quaternion hash code.
  2250. */
  2251. Quaternion.prototype.getHashCode = function () {
  2252. var hash = this.x || 0;
  2253. hash = (hash * 397) ^ (this.y || 0);
  2254. hash = (hash * 397) ^ (this.z || 0);
  2255. hash = (hash * 397) ^ (this.w || 0);
  2256. return hash;
  2257. };
  2258. /**
  2259. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2260. */
  2261. Quaternion.prototype.asArray = function () {
  2262. return [this.x, this.y, this.z, this.w];
  2263. };
  2264. /**
  2265. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2266. */
  2267. Quaternion.prototype.equals = function (otherQuaternion) {
  2268. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2269. };
  2270. /**
  2271. * Returns a new Quaternion copied from the current one.
  2272. */
  2273. Quaternion.prototype.clone = function () {
  2274. return new Quaternion(this.x, this.y, this.z, this.w);
  2275. };
  2276. /**
  2277. * Updates the current Quaternion from the passed one coordinates.
  2278. * Returns the updated Quaterion.
  2279. */
  2280. Quaternion.prototype.copyFrom = function (other) {
  2281. this.x = other.x;
  2282. this.y = other.y;
  2283. this.z = other.z;
  2284. this.w = other.w;
  2285. return this;
  2286. };
  2287. /**
  2288. * Updates the current Quaternion from the passed float coordinates.
  2289. * Returns the updated Quaterion.
  2290. */
  2291. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2292. this.x = x;
  2293. this.y = y;
  2294. this.z = z;
  2295. this.w = w;
  2296. return this;
  2297. };
  2298. /**
  2299. * Updates the current Quaternion from the passed float coordinates.
  2300. * Returns the updated Quaterion.
  2301. */
  2302. Quaternion.prototype.set = function (x, y, z, w) {
  2303. return this.copyFromFloats(x, y, z, w);
  2304. };
  2305. /**
  2306. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2307. */
  2308. Quaternion.prototype.add = function (other) {
  2309. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2310. };
  2311. /**
  2312. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2313. */
  2314. Quaternion.prototype.subtract = function (other) {
  2315. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2316. };
  2317. /**
  2318. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2319. */
  2320. Quaternion.prototype.scale = function (value) {
  2321. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2322. };
  2323. /**
  2324. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2325. */
  2326. Quaternion.prototype.multiply = function (q1) {
  2327. var result = new Quaternion(0, 0, 0, 1.0);
  2328. this.multiplyToRef(q1, result);
  2329. return result;
  2330. };
  2331. /**
  2332. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2333. * Returns the current Quaternion.
  2334. */
  2335. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2336. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2337. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2338. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2339. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2340. result.copyFromFloats(x, y, z, w);
  2341. return this;
  2342. };
  2343. /**
  2344. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2345. * Returns the updated Quaternion.
  2346. */
  2347. Quaternion.prototype.multiplyInPlace = function (q1) {
  2348. this.multiplyToRef(q1, this);
  2349. return this;
  2350. };
  2351. /**
  2352. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2353. * Returns the current Quaternion.
  2354. */
  2355. Quaternion.prototype.conjugateToRef = function (ref) {
  2356. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2357. return this;
  2358. };
  2359. /**
  2360. * Conjugates in place the current Quaternion.
  2361. * Returns the updated Quaternion.
  2362. */
  2363. Quaternion.prototype.conjugateInPlace = function () {
  2364. this.x *= -1;
  2365. this.y *= -1;
  2366. this.z *= -1;
  2367. return this;
  2368. };
  2369. /**
  2370. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2371. */
  2372. Quaternion.prototype.conjugate = function () {
  2373. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2374. return result;
  2375. };
  2376. /**
  2377. * Returns the Quaternion length (float).
  2378. */
  2379. Quaternion.prototype.length = function () {
  2380. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2381. };
  2382. /**
  2383. * Normalize in place the current Quaternion.
  2384. * Returns the updated Quaternion.
  2385. */
  2386. Quaternion.prototype.normalize = function () {
  2387. var length = 1.0 / this.length();
  2388. this.x *= length;
  2389. this.y *= length;
  2390. this.z *= length;
  2391. this.w *= length;
  2392. return this;
  2393. };
  2394. /**
  2395. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2396. */
  2397. Quaternion.prototype.toEulerAngles = function (order) {
  2398. if (order === void 0) { order = "YZX"; }
  2399. var result = Vector3.Zero();
  2400. this.toEulerAnglesToRef(result, order);
  2401. return result;
  2402. };
  2403. /**
  2404. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2405. * Returns the current Quaternion.
  2406. */
  2407. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2408. if (order === void 0) { order = "YZX"; }
  2409. var qz = this.z;
  2410. var qx = this.x;
  2411. var qy = this.y;
  2412. var qw = this.w;
  2413. var sqw = qw * qw;
  2414. var sqz = qz * qz;
  2415. var sqx = qx * qx;
  2416. var sqy = qy * qy;
  2417. var zAxisY = qy * qz - qx * qw;
  2418. var limit = .4999999;
  2419. if (zAxisY < -limit) {
  2420. result.y = 2 * Math.atan2(qy, qw);
  2421. result.x = Math.PI / 2;
  2422. result.z = 0;
  2423. }
  2424. else if (zAxisY > limit) {
  2425. result.y = 2 * Math.atan2(qy, qw);
  2426. result.x = -Math.PI / 2;
  2427. result.z = 0;
  2428. }
  2429. else {
  2430. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2431. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2432. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2433. }
  2434. return this;
  2435. };
  2436. /**
  2437. * Updates the passed rotation matrix with the current Quaternion values.
  2438. * Returns the current Quaternion.
  2439. */
  2440. Quaternion.prototype.toRotationMatrix = function (result) {
  2441. var xx = this.x * this.x;
  2442. var yy = this.y * this.y;
  2443. var zz = this.z * this.z;
  2444. var xy = this.x * this.y;
  2445. var zw = this.z * this.w;
  2446. var zx = this.z * this.x;
  2447. var yw = this.y * this.w;
  2448. var yz = this.y * this.z;
  2449. var xw = this.x * this.w;
  2450. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2451. result.m[1] = 2.0 * (xy + zw);
  2452. result.m[2] = 2.0 * (zx - yw);
  2453. result.m[3] = 0;
  2454. result.m[4] = 2.0 * (xy - zw);
  2455. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2456. result.m[6] = 2.0 * (yz + xw);
  2457. result.m[7] = 0;
  2458. result.m[8] = 2.0 * (zx + yw);
  2459. result.m[9] = 2.0 * (yz - xw);
  2460. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2461. result.m[11] = 0;
  2462. result.m[12] = 0;
  2463. result.m[13] = 0;
  2464. result.m[14] = 0;
  2465. result.m[15] = 1.0;
  2466. result._markAsUpdated();
  2467. return this;
  2468. };
  2469. /**
  2470. * Updates the current Quaternion from the passed rotation matrix values.
  2471. * Returns the updated Quaternion.
  2472. */
  2473. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2474. Quaternion.FromRotationMatrixToRef(matrix, this);
  2475. return this;
  2476. };
  2477. // Statics
  2478. /**
  2479. * Returns a new Quaternion set from the passed rotation matrix values.
  2480. */
  2481. Quaternion.FromRotationMatrix = function (matrix) {
  2482. var result = new Quaternion();
  2483. Quaternion.FromRotationMatrixToRef(matrix, result);
  2484. return result;
  2485. };
  2486. /**
  2487. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2488. */
  2489. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2490. var data = matrix.m;
  2491. var m11 = data[0], m12 = data[4], m13 = data[8];
  2492. var m21 = data[1], m22 = data[5], m23 = data[9];
  2493. var m31 = data[2], m32 = data[6], m33 = data[10];
  2494. var trace = m11 + m22 + m33;
  2495. var s;
  2496. if (trace > 0) {
  2497. s = 0.5 / Math.sqrt(trace + 1.0);
  2498. result.w = 0.25 / s;
  2499. result.x = (m32 - m23) * s;
  2500. result.y = (m13 - m31) * s;
  2501. result.z = (m21 - m12) * s;
  2502. }
  2503. else if (m11 > m22 && m11 > m33) {
  2504. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2505. result.w = (m32 - m23) / s;
  2506. result.x = 0.25 * s;
  2507. result.y = (m12 + m21) / s;
  2508. result.z = (m13 + m31) / s;
  2509. }
  2510. else if (m22 > m33) {
  2511. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2512. result.w = (m13 - m31) / s;
  2513. result.x = (m12 + m21) / s;
  2514. result.y = 0.25 * s;
  2515. result.z = (m23 + m32) / s;
  2516. }
  2517. else {
  2518. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2519. result.w = (m21 - m12) / s;
  2520. result.x = (m13 + m31) / s;
  2521. result.y = (m23 + m32) / s;
  2522. result.z = 0.25 * s;
  2523. }
  2524. };
  2525. /**
  2526. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2527. */
  2528. Quaternion.Zero = function () {
  2529. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2530. };
  2531. /**
  2532. * Returns a new Quaternion as the inverted current Quaternion.
  2533. */
  2534. Quaternion.Inverse = function (q) {
  2535. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2536. };
  2537. /**
  2538. * Returns the identity Quaternion.
  2539. */
  2540. Quaternion.Identity = function () {
  2541. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2542. };
  2543. Quaternion.IsIdentity = function (quaternion) {
  2544. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2545. };
  2546. /**
  2547. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2548. */
  2549. Quaternion.RotationAxis = function (axis, angle) {
  2550. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2551. };
  2552. /**
  2553. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2554. */
  2555. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2556. var sin = Math.sin(angle / 2);
  2557. axis.normalize();
  2558. result.w = Math.cos(angle / 2);
  2559. result.x = axis.x * sin;
  2560. result.y = axis.y * sin;
  2561. result.z = axis.z * sin;
  2562. return result;
  2563. };
  2564. /**
  2565. * Retuns a new Quaternion set from the starting index of the passed array.
  2566. */
  2567. Quaternion.FromArray = function (array, offset) {
  2568. if (!offset) {
  2569. offset = 0;
  2570. }
  2571. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2572. };
  2573. /**
  2574. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2575. */
  2576. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2577. var q = new Quaternion();
  2578. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2579. return q;
  2580. };
  2581. /**
  2582. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2583. */
  2584. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2585. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2586. var halfRoll = roll * 0.5;
  2587. var halfPitch = pitch * 0.5;
  2588. var halfYaw = yaw * 0.5;
  2589. var sinRoll = Math.sin(halfRoll);
  2590. var cosRoll = Math.cos(halfRoll);
  2591. var sinPitch = Math.sin(halfPitch);
  2592. var cosPitch = Math.cos(halfPitch);
  2593. var sinYaw = Math.sin(halfYaw);
  2594. var cosYaw = Math.cos(halfYaw);
  2595. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2596. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2597. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2598. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2599. };
  2600. /**
  2601. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2602. */
  2603. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2604. var result = new Quaternion();
  2605. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2606. return result;
  2607. };
  2608. /**
  2609. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2610. */
  2611. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2612. // Produces a quaternion from Euler angles in the z-x-z orientation
  2613. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2614. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2615. var halfBeta = beta * 0.5;
  2616. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2617. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2618. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2619. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2620. };
  2621. /**
  2622. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2623. * cf to Vector3.RotationFromAxis() documentation.
  2624. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2625. */
  2626. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2627. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2628. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2629. return quat;
  2630. };
  2631. /**
  2632. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2633. * cf to Vector3.RotationFromAxis() documentation.
  2634. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2635. */
  2636. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2637. var rotMat = MathTmp.Matrix[0];
  2638. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2639. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2640. };
  2641. Quaternion.Slerp = function (left, right, amount) {
  2642. var result = Quaternion.Identity();
  2643. Quaternion.SlerpToRef(left, right, amount, result);
  2644. return result;
  2645. };
  2646. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2647. var num2;
  2648. var num3;
  2649. var num = amount;
  2650. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2651. var flag = false;
  2652. if (num4 < 0) {
  2653. flag = true;
  2654. num4 = -num4;
  2655. }
  2656. if (num4 > 0.999999) {
  2657. num3 = 1 - num;
  2658. num2 = flag ? -num : num;
  2659. }
  2660. else {
  2661. var num5 = Math.acos(num4);
  2662. var num6 = (1.0 / Math.sin(num5));
  2663. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2664. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2665. }
  2666. result.x = (num3 * left.x) + (num2 * right.x);
  2667. result.y = (num3 * left.y) + (num2 * right.y);
  2668. result.z = (num3 * left.z) + (num2 * right.z);
  2669. result.w = (num3 * left.w) + (num2 * right.w);
  2670. };
  2671. return Quaternion;
  2672. }());
  2673. BABYLON.Quaternion = Quaternion;
  2674. var Matrix = (function () {
  2675. function Matrix() {
  2676. this.m = new Float32Array(16);
  2677. this._markAsUpdated();
  2678. }
  2679. Matrix.prototype._markAsUpdated = function () {
  2680. this.updateFlag = Matrix._updateFlagSeed++;
  2681. };
  2682. // Properties
  2683. /**
  2684. * Boolean : True is the matrix is the identity matrix
  2685. */
  2686. Matrix.prototype.isIdentity = function () {
  2687. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2688. return false;
  2689. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2690. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2691. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2692. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2693. return false;
  2694. return true;
  2695. };
  2696. /**
  2697. * Returns the matrix determinant (float).
  2698. */
  2699. Matrix.prototype.determinant = function () {
  2700. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2701. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2702. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2703. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2704. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2705. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2706. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2707. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2708. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2709. };
  2710. // Methods
  2711. /**
  2712. * Returns the matrix underlying array.
  2713. */
  2714. Matrix.prototype.toArray = function () {
  2715. return this.m;
  2716. };
  2717. /**
  2718. * Returns the matrix underlying array.
  2719. */
  2720. Matrix.prototype.asArray = function () {
  2721. return this.toArray();
  2722. };
  2723. /**
  2724. * Inverts in place the Matrix.
  2725. * Returns the Matrix inverted.
  2726. */
  2727. Matrix.prototype.invert = function () {
  2728. this.invertToRef(this);
  2729. return this;
  2730. };
  2731. /**
  2732. * Sets all the matrix elements to zero.
  2733. * Returns the Matrix.
  2734. */
  2735. Matrix.prototype.reset = function () {
  2736. for (var index = 0; index < 16; index++) {
  2737. this.m[index] = 0.0;
  2738. }
  2739. this._markAsUpdated();
  2740. return this;
  2741. };
  2742. /**
  2743. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2744. */
  2745. Matrix.prototype.add = function (other) {
  2746. var result = new Matrix();
  2747. this.addToRef(other, result);
  2748. return result;
  2749. };
  2750. /**
  2751. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2752. * Returns the Matrix.
  2753. */
  2754. Matrix.prototype.addToRef = function (other, result) {
  2755. for (var index = 0; index < 16; index++) {
  2756. result.m[index] = this.m[index] + other.m[index];
  2757. }
  2758. result._markAsUpdated();
  2759. return this;
  2760. };
  2761. /**
  2762. * Adds in place the passed matrix to the current Matrix.
  2763. * Returns the updated Matrix.
  2764. */
  2765. Matrix.prototype.addToSelf = function (other) {
  2766. for (var index = 0; index < 16; index++) {
  2767. this.m[index] += other.m[index];
  2768. }
  2769. this._markAsUpdated();
  2770. return this;
  2771. };
  2772. /**
  2773. * Sets the passed matrix with the current inverted Matrix.
  2774. * Returns the unmodified current Matrix.
  2775. */
  2776. Matrix.prototype.invertToRef = function (other) {
  2777. var l1 = this.m[0];
  2778. var l2 = this.m[1];
  2779. var l3 = this.m[2];
  2780. var l4 = this.m[3];
  2781. var l5 = this.m[4];
  2782. var l6 = this.m[5];
  2783. var l7 = this.m[6];
  2784. var l8 = this.m[7];
  2785. var l9 = this.m[8];
  2786. var l10 = this.m[9];
  2787. var l11 = this.m[10];
  2788. var l12 = this.m[11];
  2789. var l13 = this.m[12];
  2790. var l14 = this.m[13];
  2791. var l15 = this.m[14];
  2792. var l16 = this.m[15];
  2793. var l17 = (l11 * l16) - (l12 * l15);
  2794. var l18 = (l10 * l16) - (l12 * l14);
  2795. var l19 = (l10 * l15) - (l11 * l14);
  2796. var l20 = (l9 * l16) - (l12 * l13);
  2797. var l21 = (l9 * l15) - (l11 * l13);
  2798. var l22 = (l9 * l14) - (l10 * l13);
  2799. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2800. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2801. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2802. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2803. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2804. var l28 = (l7 * l16) - (l8 * l15);
  2805. var l29 = (l6 * l16) - (l8 * l14);
  2806. var l30 = (l6 * l15) - (l7 * l14);
  2807. var l31 = (l5 * l16) - (l8 * l13);
  2808. var l32 = (l5 * l15) - (l7 * l13);
  2809. var l33 = (l5 * l14) - (l6 * l13);
  2810. var l34 = (l7 * l12) - (l8 * l11);
  2811. var l35 = (l6 * l12) - (l8 * l10);
  2812. var l36 = (l6 * l11) - (l7 * l10);
  2813. var l37 = (l5 * l12) - (l8 * l9);
  2814. var l38 = (l5 * l11) - (l7 * l9);
  2815. var l39 = (l5 * l10) - (l6 * l9);
  2816. other.m[0] = l23 * l27;
  2817. other.m[4] = l24 * l27;
  2818. other.m[8] = l25 * l27;
  2819. other.m[12] = l26 * l27;
  2820. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2821. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2822. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2823. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2824. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2825. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2826. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2827. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2828. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2829. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2830. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2831. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2832. other._markAsUpdated();
  2833. return this;
  2834. };
  2835. /**
  2836. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2837. * Returns the updated Matrix.
  2838. */
  2839. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2840. this.m[12] = x;
  2841. this.m[13] = y;
  2842. this.m[14] = z;
  2843. this._markAsUpdated();
  2844. return this;
  2845. };
  2846. /**
  2847. * Inserts the translation vector in the current Matrix.
  2848. * Returns the updated Matrix.
  2849. */
  2850. Matrix.prototype.setTranslation = function (vector3) {
  2851. this.m[12] = vector3.x;
  2852. this.m[13] = vector3.y;
  2853. this.m[14] = vector3.z;
  2854. this._markAsUpdated();
  2855. return this;
  2856. };
  2857. /**
  2858. * Returns a new Vector3 as the extracted translation from the Matrix.
  2859. */
  2860. Matrix.prototype.getTranslation = function () {
  2861. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2862. };
  2863. /**
  2864. * Fill a Vector3 with the extracted translation from the Matrix.
  2865. */
  2866. Matrix.prototype.getTranslationToRef = function (result) {
  2867. result.x = this.m[12];
  2868. result.y = this.m[13];
  2869. result.z = this.m[14];
  2870. return this;
  2871. };
  2872. /**
  2873. * Remove rotation and scaling part from the Matrix.
  2874. * Returns the updated Matrix.
  2875. */
  2876. Matrix.prototype.removeRotationAndScaling = function () {
  2877. this.setRowFromFloats(0, 1, 0, 0, 0);
  2878. this.setRowFromFloats(1, 0, 1, 0, 0);
  2879. this.setRowFromFloats(2, 0, 0, 1, 0);
  2880. return this;
  2881. };
  2882. /**
  2883. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2884. */
  2885. Matrix.prototype.multiply = function (other) {
  2886. var result = new Matrix();
  2887. this.multiplyToRef(other, result);
  2888. return result;
  2889. };
  2890. /**
  2891. * Updates the current Matrix from the passed one values.
  2892. * Returns the updated Matrix.
  2893. */
  2894. Matrix.prototype.copyFrom = function (other) {
  2895. for (var index = 0; index < 16; index++) {
  2896. this.m[index] = other.m[index];
  2897. }
  2898. this._markAsUpdated();
  2899. return this;
  2900. };
  2901. /**
  2902. * Populates the passed array from the starting index with the Matrix values.
  2903. * Returns the Matrix.
  2904. */
  2905. Matrix.prototype.copyToArray = function (array, offset) {
  2906. if (offset === void 0) { offset = 0; }
  2907. for (var index = 0; index < 16; index++) {
  2908. array[offset + index] = this.m[index];
  2909. }
  2910. return this;
  2911. };
  2912. /**
  2913. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2914. */
  2915. Matrix.prototype.multiplyToRef = function (other, result) {
  2916. this.multiplyToArray(other, result.m, 0);
  2917. result._markAsUpdated();
  2918. return this;
  2919. };
  2920. /**
  2921. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2922. */
  2923. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2924. var tm0 = this.m[0];
  2925. var tm1 = this.m[1];
  2926. var tm2 = this.m[2];
  2927. var tm3 = this.m[3];
  2928. var tm4 = this.m[4];
  2929. var tm5 = this.m[5];
  2930. var tm6 = this.m[6];
  2931. var tm7 = this.m[7];
  2932. var tm8 = this.m[8];
  2933. var tm9 = this.m[9];
  2934. var tm10 = this.m[10];
  2935. var tm11 = this.m[11];
  2936. var tm12 = this.m[12];
  2937. var tm13 = this.m[13];
  2938. var tm14 = this.m[14];
  2939. var tm15 = this.m[15];
  2940. var om0 = other.m[0];
  2941. var om1 = other.m[1];
  2942. var om2 = other.m[2];
  2943. var om3 = other.m[3];
  2944. var om4 = other.m[4];
  2945. var om5 = other.m[5];
  2946. var om6 = other.m[6];
  2947. var om7 = other.m[7];
  2948. var om8 = other.m[8];
  2949. var om9 = other.m[9];
  2950. var om10 = other.m[10];
  2951. var om11 = other.m[11];
  2952. var om12 = other.m[12];
  2953. var om13 = other.m[13];
  2954. var om14 = other.m[14];
  2955. var om15 = other.m[15];
  2956. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2957. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2958. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2959. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2960. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2961. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2962. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2963. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2964. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2965. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2966. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  2967. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  2968. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  2969. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  2970. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  2971. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  2972. return this;
  2973. };
  2974. /**
  2975. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  2976. */
  2977. Matrix.prototype.equals = function (value) {
  2978. return value &&
  2979. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  2980. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  2981. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  2982. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  2983. };
  2984. /**
  2985. * Returns a new Matrix from the current Matrix.
  2986. */
  2987. Matrix.prototype.clone = function () {
  2988. 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]);
  2989. };
  2990. /**
  2991. * Returns the string "Matrix"
  2992. */
  2993. Matrix.prototype.getClassName = function () {
  2994. return "Matrix";
  2995. };
  2996. /**
  2997. * Returns the Matrix hash code.
  2998. */
  2999. Matrix.prototype.getHashCode = function () {
  3000. var hash = this.m[0] || 0;
  3001. for (var i = 1; i < 16; i++) {
  3002. hash = (hash * 397) ^ (this.m[i] || 0);
  3003. }
  3004. return hash;
  3005. };
  3006. /**
  3007. * Decomposes the current Matrix into :
  3008. * - a scale vector3 passed as a reference to update,
  3009. * - a rotation quaternion passed as a reference to update,
  3010. * - a translation vector3 passed as a reference to update.
  3011. * Returns the boolean `true`.
  3012. */
  3013. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3014. translation.x = this.m[12];
  3015. translation.y = this.m[13];
  3016. translation.z = this.m[14];
  3017. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3018. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3019. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3020. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3021. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3022. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3023. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3024. rotation.x = 0;
  3025. rotation.y = 0;
  3026. rotation.z = 0;
  3027. rotation.w = 1;
  3028. return false;
  3029. }
  3030. 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]);
  3031. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3032. return true;
  3033. };
  3034. /**
  3035. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3036. */
  3037. Matrix.prototype.getRotationMatrix = function () {
  3038. var result = Matrix.Identity();
  3039. this.getRotationMatrixToRef(result);
  3040. return result;
  3041. };
  3042. /**
  3043. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3044. * Returns the current Matrix.
  3045. */
  3046. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3047. var m = this.m;
  3048. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3049. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3050. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3051. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3052. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3053. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3054. 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);
  3055. return this;
  3056. };
  3057. // Statics
  3058. /**
  3059. * Returns a new Matrix set from the starting index of the passed array.
  3060. */
  3061. Matrix.FromArray = function (array, offset) {
  3062. var result = new Matrix();
  3063. if (!offset) {
  3064. offset = 0;
  3065. }
  3066. Matrix.FromArrayToRef(array, offset, result);
  3067. return result;
  3068. };
  3069. /**
  3070. * Sets the passed "result" matrix from the starting index of the passed array.
  3071. */
  3072. Matrix.FromArrayToRef = function (array, offset, result) {
  3073. for (var index = 0; index < 16; index++) {
  3074. result.m[index] = array[index + offset];
  3075. }
  3076. result._markAsUpdated();
  3077. };
  3078. /**
  3079. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3080. */
  3081. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3082. for (var index = 0; index < 16; index++) {
  3083. result.m[index] = array[index + offset] * scale;
  3084. }
  3085. result._markAsUpdated();
  3086. };
  3087. /**
  3088. * Sets the passed matrix "result" with the 16 passed floats.
  3089. */
  3090. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3091. result.m[0] = initialM11;
  3092. result.m[1] = initialM12;
  3093. result.m[2] = initialM13;
  3094. result.m[3] = initialM14;
  3095. result.m[4] = initialM21;
  3096. result.m[5] = initialM22;
  3097. result.m[6] = initialM23;
  3098. result.m[7] = initialM24;
  3099. result.m[8] = initialM31;
  3100. result.m[9] = initialM32;
  3101. result.m[10] = initialM33;
  3102. result.m[11] = initialM34;
  3103. result.m[12] = initialM41;
  3104. result.m[13] = initialM42;
  3105. result.m[14] = initialM43;
  3106. result.m[15] = initialM44;
  3107. result._markAsUpdated();
  3108. };
  3109. /**
  3110. * Returns the index-th row of the current matrix as a new Vector4.
  3111. */
  3112. Matrix.prototype.getRow = function (index) {
  3113. if (index < 0 || index > 3) {
  3114. return null;
  3115. }
  3116. var i = index * 4;
  3117. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3118. };
  3119. /**
  3120. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3121. * Returns the updated Matrix.
  3122. */
  3123. Matrix.prototype.setRow = function (index, row) {
  3124. if (index < 0 || index > 3) {
  3125. return this;
  3126. }
  3127. var i = index * 4;
  3128. this.m[i + 0] = row.x;
  3129. this.m[i + 1] = row.y;
  3130. this.m[i + 2] = row.z;
  3131. this.m[i + 3] = row.w;
  3132. this._markAsUpdated();
  3133. return this;
  3134. };
  3135. /**
  3136. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3137. * Returns the updated Matrix.
  3138. */
  3139. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3140. if (index < 0 || index > 3) {
  3141. return this;
  3142. }
  3143. var i = index * 4;
  3144. this.m[i + 0] = x;
  3145. this.m[i + 1] = y;
  3146. this.m[i + 2] = z;
  3147. this.m[i + 3] = w;
  3148. this._markAsUpdated();
  3149. return this;
  3150. };
  3151. /**
  3152. * Returns a new Matrix set from the 16 passed floats.
  3153. */
  3154. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3155. var result = new Matrix();
  3156. result.m[0] = initialM11;
  3157. result.m[1] = initialM12;
  3158. result.m[2] = initialM13;
  3159. result.m[3] = initialM14;
  3160. result.m[4] = initialM21;
  3161. result.m[5] = initialM22;
  3162. result.m[6] = initialM23;
  3163. result.m[7] = initialM24;
  3164. result.m[8] = initialM31;
  3165. result.m[9] = initialM32;
  3166. result.m[10] = initialM33;
  3167. result.m[11] = initialM34;
  3168. result.m[12] = initialM41;
  3169. result.m[13] = initialM42;
  3170. result.m[14] = initialM43;
  3171. result.m[15] = initialM44;
  3172. return result;
  3173. };
  3174. /**
  3175. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3176. */
  3177. Matrix.Compose = function (scale, rotation, translation) {
  3178. var result = Matrix.Identity();
  3179. Matrix.ComposeToRef(scale, rotation, translation, result);
  3180. return result;
  3181. };
  3182. /**
  3183. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3184. */
  3185. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3186. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3187. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3188. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3189. result.setTranslation(translation);
  3190. };
  3191. /**
  3192. * Returns a new indentity Matrix.
  3193. */
  3194. Matrix.Identity = function () {
  3195. 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);
  3196. };
  3197. /**
  3198. * Sets the passed "result" as an identity matrix.
  3199. */
  3200. Matrix.IdentityToRef = function (result) {
  3201. 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);
  3202. };
  3203. /**
  3204. * Returns a new zero Matrix.
  3205. */
  3206. Matrix.Zero = function () {
  3207. 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);
  3208. };
  3209. /**
  3210. * Returns a new rotation matrix for "angle" radians around the X axis.
  3211. */
  3212. Matrix.RotationX = function (angle) {
  3213. var result = new Matrix();
  3214. Matrix.RotationXToRef(angle, result);
  3215. return result;
  3216. };
  3217. /**
  3218. * Returns a new Matrix as the passed inverted one.
  3219. */
  3220. Matrix.Invert = function (source) {
  3221. var result = new Matrix();
  3222. source.invertToRef(result);
  3223. return result;
  3224. };
  3225. /**
  3226. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3227. */
  3228. Matrix.RotationXToRef = function (angle, result) {
  3229. var s = Math.sin(angle);
  3230. var c = Math.cos(angle);
  3231. result.m[0] = 1.0;
  3232. result.m[15] = 1.0;
  3233. result.m[5] = c;
  3234. result.m[10] = c;
  3235. result.m[9] = -s;
  3236. result.m[6] = s;
  3237. result.m[1] = 0.0;
  3238. result.m[2] = 0.0;
  3239. result.m[3] = 0.0;
  3240. result.m[4] = 0.0;
  3241. result.m[7] = 0.0;
  3242. result.m[8] = 0.0;
  3243. result.m[11] = 0.0;
  3244. result.m[12] = 0.0;
  3245. result.m[13] = 0.0;
  3246. result.m[14] = 0.0;
  3247. result._markAsUpdated();
  3248. };
  3249. /**
  3250. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3251. */
  3252. Matrix.RotationY = function (angle) {
  3253. var result = new Matrix();
  3254. Matrix.RotationYToRef(angle, result);
  3255. return result;
  3256. };
  3257. /**
  3258. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3259. */
  3260. Matrix.RotationYToRef = function (angle, result) {
  3261. var s = Math.sin(angle);
  3262. var c = Math.cos(angle);
  3263. result.m[5] = 1.0;
  3264. result.m[15] = 1.0;
  3265. result.m[0] = c;
  3266. result.m[2] = -s;
  3267. result.m[8] = s;
  3268. result.m[10] = c;
  3269. result.m[1] = 0.0;
  3270. result.m[3] = 0.0;
  3271. result.m[4] = 0.0;
  3272. result.m[6] = 0.0;
  3273. result.m[7] = 0.0;
  3274. result.m[9] = 0.0;
  3275. result.m[11] = 0.0;
  3276. result.m[12] = 0.0;
  3277. result.m[13] = 0.0;
  3278. result.m[14] = 0.0;
  3279. result._markAsUpdated();
  3280. };
  3281. /**
  3282. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3283. */
  3284. Matrix.RotationZ = function (angle) {
  3285. var result = new Matrix();
  3286. Matrix.RotationZToRef(angle, result);
  3287. return result;
  3288. };
  3289. /**
  3290. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3291. */
  3292. Matrix.RotationZToRef = function (angle, result) {
  3293. var s = Math.sin(angle);
  3294. var c = Math.cos(angle);
  3295. result.m[10] = 1.0;
  3296. result.m[15] = 1.0;
  3297. result.m[0] = c;
  3298. result.m[1] = s;
  3299. result.m[4] = -s;
  3300. result.m[5] = c;
  3301. result.m[2] = 0.0;
  3302. result.m[3] = 0.0;
  3303. result.m[6] = 0.0;
  3304. result.m[7] = 0.0;
  3305. result.m[8] = 0.0;
  3306. result.m[9] = 0.0;
  3307. result.m[11] = 0.0;
  3308. result.m[12] = 0.0;
  3309. result.m[13] = 0.0;
  3310. result.m[14] = 0.0;
  3311. result._markAsUpdated();
  3312. };
  3313. /**
  3314. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3315. */
  3316. Matrix.RotationAxis = function (axis, angle) {
  3317. var result = Matrix.Zero();
  3318. Matrix.RotationAxisToRef(axis, angle, result);
  3319. return result;
  3320. };
  3321. /**
  3322. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3323. */
  3324. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3325. var s = Math.sin(-angle);
  3326. var c = Math.cos(-angle);
  3327. var c1 = 1 - c;
  3328. axis.normalize();
  3329. result.m[0] = (axis.x * axis.x) * c1 + c;
  3330. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3331. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3332. result.m[3] = 0.0;
  3333. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3334. result.m[5] = (axis.y * axis.y) * c1 + c;
  3335. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3336. result.m[7] = 0.0;
  3337. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3338. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3339. result.m[10] = (axis.z * axis.z) * c1 + c;
  3340. result.m[11] = 0.0;
  3341. result.m[15] = 1.0;
  3342. result._markAsUpdated();
  3343. };
  3344. /**
  3345. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3346. */
  3347. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3348. var result = new Matrix();
  3349. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3350. return result;
  3351. };
  3352. /**
  3353. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3354. */
  3355. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3356. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3357. this._tempQuaternion.toRotationMatrix(result);
  3358. };
  3359. /**
  3360. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3361. */
  3362. Matrix.Scaling = function (x, y, z) {
  3363. var result = Matrix.Zero();
  3364. Matrix.ScalingToRef(x, y, z, result);
  3365. return result;
  3366. };
  3367. /**
  3368. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3369. */
  3370. Matrix.ScalingToRef = function (x, y, z, result) {
  3371. result.m[0] = x;
  3372. result.m[1] = 0.0;
  3373. result.m[2] = 0.0;
  3374. result.m[3] = 0.0;
  3375. result.m[4] = 0.0;
  3376. result.m[5] = y;
  3377. result.m[6] = 0.0;
  3378. result.m[7] = 0.0;
  3379. result.m[8] = 0.0;
  3380. result.m[9] = 0.0;
  3381. result.m[10] = z;
  3382. result.m[11] = 0.0;
  3383. result.m[12] = 0.0;
  3384. result.m[13] = 0.0;
  3385. result.m[14] = 0.0;
  3386. result.m[15] = 1.0;
  3387. result._markAsUpdated();
  3388. };
  3389. /**
  3390. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3391. */
  3392. Matrix.Translation = function (x, y, z) {
  3393. var result = Matrix.Identity();
  3394. Matrix.TranslationToRef(x, y, z, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3399. */
  3400. Matrix.TranslationToRef = function (x, y, z, result) {
  3401. 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);
  3402. };
  3403. /**
  3404. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3405. */
  3406. Matrix.Lerp = function (startValue, endValue, gradient) {
  3407. var result = Matrix.Zero();
  3408. for (var index = 0; index < 16; index++) {
  3409. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3410. }
  3411. result._markAsUpdated();
  3412. return result;
  3413. };
  3414. /**
  3415. * Returns a new Matrix whose values are computed by :
  3416. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3417. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3418. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3419. */
  3420. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3421. var startScale = new Vector3(0, 0, 0);
  3422. var startRotation = new Quaternion();
  3423. var startTranslation = new Vector3(0, 0, 0);
  3424. startValue.decompose(startScale, startRotation, startTranslation);
  3425. var endScale = new Vector3(0, 0, 0);
  3426. var endRotation = new Quaternion();
  3427. var endTranslation = new Vector3(0, 0, 0);
  3428. endValue.decompose(endScale, endRotation, endTranslation);
  3429. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3430. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3431. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3432. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3433. };
  3434. /**
  3435. * 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".
  3436. * This methods works for a Left-Handed system.
  3437. */
  3438. Matrix.LookAtLH = function (eye, target, up) {
  3439. var result = Matrix.Zero();
  3440. Matrix.LookAtLHToRef(eye, target, up, result);
  3441. return result;
  3442. };
  3443. /**
  3444. * 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".
  3445. * This methods works for a Left-Handed system.
  3446. */
  3447. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3448. // Z axis
  3449. target.subtractToRef(eye, this._zAxis);
  3450. this._zAxis.normalize();
  3451. // X axis
  3452. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3453. if (this._xAxis.lengthSquared() === 0) {
  3454. this._xAxis.x = 1.0;
  3455. }
  3456. else {
  3457. this._xAxis.normalize();
  3458. }
  3459. // Y axis
  3460. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3461. this._yAxis.normalize();
  3462. // Eye angles
  3463. var ex = -Vector3.Dot(this._xAxis, eye);
  3464. var ey = -Vector3.Dot(this._yAxis, eye);
  3465. var ez = -Vector3.Dot(this._zAxis, eye);
  3466. 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);
  3467. };
  3468. /**
  3469. * 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".
  3470. * This methods works for a Right-Handed system.
  3471. */
  3472. Matrix.LookAtRH = function (eye, target, up) {
  3473. var result = Matrix.Zero();
  3474. Matrix.LookAtRHToRef(eye, target, up, result);
  3475. return result;
  3476. };
  3477. /**
  3478. * 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".
  3479. * This methods works for a Left-Handed system.
  3480. */
  3481. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3482. // Z axis
  3483. eye.subtractToRef(target, this._zAxis);
  3484. this._zAxis.normalize();
  3485. // X axis
  3486. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3487. if (this._xAxis.lengthSquared() === 0) {
  3488. this._xAxis.x = 1.0;
  3489. }
  3490. else {
  3491. this._xAxis.normalize();
  3492. }
  3493. // Y axis
  3494. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3495. this._yAxis.normalize();
  3496. // Eye angles
  3497. var ex = -Vector3.Dot(this._xAxis, eye);
  3498. var ey = -Vector3.Dot(this._yAxis, eye);
  3499. var ez = -Vector3.Dot(this._zAxis, eye);
  3500. 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);
  3501. };
  3502. /**
  3503. * 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.
  3504. */
  3505. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3506. var matrix = Matrix.Zero();
  3507. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3508. return matrix;
  3509. };
  3510. /**
  3511. * 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.
  3512. */
  3513. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3514. var n = znear;
  3515. var f = zfar;
  3516. var a = 2.0 / width;
  3517. var b = 2.0 / height;
  3518. var c = 2.0 / (f - n);
  3519. var d = -(f + n) / (f - n);
  3520. 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);
  3521. };
  3522. /**
  3523. * 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.
  3524. */
  3525. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3526. var matrix = Matrix.Zero();
  3527. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3528. return matrix;
  3529. };
  3530. /**
  3531. * 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.
  3532. */
  3533. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3534. var n = znear;
  3535. var f = zfar;
  3536. var a = 2.0 / (right - left);
  3537. var b = 2.0 / (top - bottom);
  3538. var c = 2.0 / (f - n);
  3539. var d = -(f + n) / (f - n);
  3540. var i0 = (left + right) / (left - right);
  3541. var i1 = (top + bottom) / (bottom - top);
  3542. 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);
  3543. };
  3544. /**
  3545. * 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.
  3546. */
  3547. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3548. var matrix = Matrix.Zero();
  3549. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3550. return matrix;
  3551. };
  3552. /**
  3553. * 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.
  3554. */
  3555. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3556. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3557. result.m[10] *= -1.0;
  3558. };
  3559. /**
  3560. * 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.
  3561. */
  3562. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3563. var matrix = Matrix.Zero();
  3564. var n = znear;
  3565. var f = zfar;
  3566. var a = 2.0 * n / width;
  3567. var b = 2.0 * n / height;
  3568. var c = (f + n) / (f - n);
  3569. var d = -2.0 * f * n / (f - n);
  3570. 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);
  3571. return matrix;
  3572. };
  3573. /**
  3574. * 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.
  3575. */
  3576. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3577. var matrix = Matrix.Zero();
  3578. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3579. return matrix;
  3580. };
  3581. /**
  3582. * 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.
  3583. */
  3584. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3585. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3586. var n = znear;
  3587. var f = zfar;
  3588. var t = 1.0 / (Math.tan(fov * 0.5));
  3589. var a = isVerticalFovFixed ? (t / aspect) : t;
  3590. var b = isVerticalFovFixed ? t : (t * aspect);
  3591. var c = (f + n) / (f - n);
  3592. var d = -2.0 * f * n / (f - n);
  3593. 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);
  3594. };
  3595. /**
  3596. * 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.
  3597. */
  3598. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3599. var matrix = Matrix.Zero();
  3600. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3601. return matrix;
  3602. };
  3603. /**
  3604. * 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.
  3605. */
  3606. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3607. //alternatively this could be expressed as:
  3608. // m = PerspectiveFovLHToRef
  3609. // m[10] *= -1.0;
  3610. // m[11] *= -1.0;
  3611. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3612. var n = znear;
  3613. var f = zfar;
  3614. var t = 1.0 / (Math.tan(fov * 0.5));
  3615. var a = isVerticalFovFixed ? (t / aspect) : t;
  3616. var b = isVerticalFovFixed ? t : (t * aspect);
  3617. var c = -(f + n) / (f - n);
  3618. var d = -2 * f * n / (f - n);
  3619. 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);
  3620. };
  3621. /**
  3622. * 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.
  3623. */
  3624. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3625. if (rightHanded === void 0) { rightHanded = false; }
  3626. var rightHandedFactor = rightHanded ? -1 : 1;
  3627. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3628. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3629. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3630. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3631. var xScale = 2.0 / (leftTan + rightTan);
  3632. var yScale = 2.0 / (upTan + downTan);
  3633. result.m[0] = xScale;
  3634. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3635. result.m[5] = yScale;
  3636. result.m[6] = result.m[7] = 0.0;
  3637. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3638. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3639. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3640. result.m[10] = -zfar / (znear - zfar);
  3641. result.m[11] = 1.0 * rightHandedFactor;
  3642. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3643. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3644. // result.m[14] = (znear * zfar) / (znear - zfar);
  3645. result._markAsUpdated();
  3646. };
  3647. /**
  3648. * Returns the final transformation matrix : world * view * projection * viewport
  3649. */
  3650. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3651. var cw = viewport.width;
  3652. var ch = viewport.height;
  3653. var cx = viewport.x;
  3654. var cy = viewport.y;
  3655. 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);
  3656. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3657. };
  3658. /**
  3659. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3660. */
  3661. Matrix.GetAsMatrix2x2 = function (matrix) {
  3662. return new Float32Array([
  3663. matrix.m[0], matrix.m[1],
  3664. matrix.m[4], matrix.m[5]
  3665. ]);
  3666. };
  3667. /**
  3668. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3669. */
  3670. Matrix.GetAsMatrix3x3 = function (matrix) {
  3671. return new Float32Array([
  3672. matrix.m[0], matrix.m[1], matrix.m[2],
  3673. matrix.m[4], matrix.m[5], matrix.m[6],
  3674. matrix.m[8], matrix.m[9], matrix.m[10]
  3675. ]);
  3676. };
  3677. /**
  3678. * Compute the transpose of the passed Matrix.
  3679. * Returns a new Matrix.
  3680. */
  3681. Matrix.Transpose = function (matrix) {
  3682. var result = new Matrix();
  3683. result.m[0] = matrix.m[0];
  3684. result.m[1] = matrix.m[4];
  3685. result.m[2] = matrix.m[8];
  3686. result.m[3] = matrix.m[12];
  3687. result.m[4] = matrix.m[1];
  3688. result.m[5] = matrix.m[5];
  3689. result.m[6] = matrix.m[9];
  3690. result.m[7] = matrix.m[13];
  3691. result.m[8] = matrix.m[2];
  3692. result.m[9] = matrix.m[6];
  3693. result.m[10] = matrix.m[10];
  3694. result.m[11] = matrix.m[14];
  3695. result.m[12] = matrix.m[3];
  3696. result.m[13] = matrix.m[7];
  3697. result.m[14] = matrix.m[11];
  3698. result.m[15] = matrix.m[15];
  3699. return result;
  3700. };
  3701. /**
  3702. * Returns a new Matrix as the reflection matrix across the passed plane.
  3703. */
  3704. Matrix.Reflection = function (plane) {
  3705. var matrix = new Matrix();
  3706. Matrix.ReflectionToRef(plane, matrix);
  3707. return matrix;
  3708. };
  3709. /**
  3710. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3711. */
  3712. Matrix.ReflectionToRef = function (plane, result) {
  3713. plane.normalize();
  3714. var x = plane.normal.x;
  3715. var y = plane.normal.y;
  3716. var z = plane.normal.z;
  3717. var temp = -2 * x;
  3718. var temp2 = -2 * y;
  3719. var temp3 = -2 * z;
  3720. result.m[0] = (temp * x) + 1;
  3721. result.m[1] = temp2 * x;
  3722. result.m[2] = temp3 * x;
  3723. result.m[3] = 0.0;
  3724. result.m[4] = temp * y;
  3725. result.m[5] = (temp2 * y) + 1;
  3726. result.m[6] = temp3 * y;
  3727. result.m[7] = 0.0;
  3728. result.m[8] = temp * z;
  3729. result.m[9] = temp2 * z;
  3730. result.m[10] = (temp3 * z) + 1;
  3731. result.m[11] = 0.0;
  3732. result.m[12] = temp * plane.d;
  3733. result.m[13] = temp2 * plane.d;
  3734. result.m[14] = temp3 * plane.d;
  3735. result.m[15] = 1.0;
  3736. result._markAsUpdated();
  3737. };
  3738. /**
  3739. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3740. */
  3741. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3742. result.m[0] = xaxis.x;
  3743. result.m[1] = xaxis.y;
  3744. result.m[2] = xaxis.z;
  3745. result.m[3] = 0.0;
  3746. result.m[4] = yaxis.x;
  3747. result.m[5] = yaxis.y;
  3748. result.m[6] = yaxis.z;
  3749. result.m[7] = 0.0;
  3750. result.m[8] = zaxis.x;
  3751. result.m[9] = zaxis.y;
  3752. result.m[10] = zaxis.z;
  3753. result.m[11] = 0.0;
  3754. result.m[12] = 0.0;
  3755. result.m[13] = 0.0;
  3756. result.m[14] = 0.0;
  3757. result.m[15] = 1.0;
  3758. result._markAsUpdated();
  3759. };
  3760. /**
  3761. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3762. */
  3763. Matrix.FromQuaternionToRef = function (quat, result) {
  3764. var xx = quat.x * quat.x;
  3765. var yy = quat.y * quat.y;
  3766. var zz = quat.z * quat.z;
  3767. var xy = quat.x * quat.y;
  3768. var zw = quat.z * quat.w;
  3769. var zx = quat.z * quat.x;
  3770. var yw = quat.y * quat.w;
  3771. var yz = quat.y * quat.z;
  3772. var xw = quat.x * quat.w;
  3773. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3774. result.m[1] = 2.0 * (xy + zw);
  3775. result.m[2] = 2.0 * (zx - yw);
  3776. result.m[3] = 0.0;
  3777. result.m[4] = 2.0 * (xy - zw);
  3778. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3779. result.m[6] = 2.0 * (yz + xw);
  3780. result.m[7] = 0.0;
  3781. result.m[8] = 2.0 * (zx + yw);
  3782. result.m[9] = 2.0 * (yz - xw);
  3783. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3784. result.m[11] = 0.0;
  3785. result.m[12] = 0.0;
  3786. result.m[13] = 0.0;
  3787. result.m[14] = 0.0;
  3788. result.m[15] = 1.0;
  3789. result._markAsUpdated();
  3790. };
  3791. return Matrix;
  3792. }());
  3793. Matrix._tempQuaternion = new Quaternion();
  3794. Matrix._xAxis = Vector3.Zero();
  3795. Matrix._yAxis = Vector3.Zero();
  3796. Matrix._zAxis = Vector3.Zero();
  3797. Matrix._updateFlagSeed = 0;
  3798. BABYLON.Matrix = Matrix;
  3799. var Plane = (function () {
  3800. /**
  3801. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3802. */
  3803. function Plane(a, b, c, d) {
  3804. this.normal = new Vector3(a, b, c);
  3805. this.d = d;
  3806. }
  3807. /**
  3808. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3809. */
  3810. Plane.prototype.asArray = function () {
  3811. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3812. };
  3813. // Methods
  3814. /**
  3815. * Returns a new plane copied from the current Plane.
  3816. */
  3817. Plane.prototype.clone = function () {
  3818. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3819. };
  3820. /**
  3821. * Returns the string "Plane".
  3822. */
  3823. Plane.prototype.getClassName = function () {
  3824. return "Plane";
  3825. };
  3826. /**
  3827. * Returns the Plane hash code.
  3828. */
  3829. Plane.prototype.getHashCode = function () {
  3830. var hash = this.normal.getHashCode();
  3831. hash = (hash * 397) ^ (this.d || 0);
  3832. return hash;
  3833. };
  3834. /**
  3835. * Normalize the current Plane in place.
  3836. * Returns the updated Plane.
  3837. */
  3838. Plane.prototype.normalize = function () {
  3839. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3840. var magnitude = 0.0;
  3841. if (norm !== 0) {
  3842. magnitude = 1.0 / norm;
  3843. }
  3844. this.normal.x *= magnitude;
  3845. this.normal.y *= magnitude;
  3846. this.normal.z *= magnitude;
  3847. this.d *= magnitude;
  3848. return this;
  3849. };
  3850. /**
  3851. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3852. */
  3853. Plane.prototype.transform = function (transformation) {
  3854. var transposedMatrix = Matrix.Transpose(transformation);
  3855. var x = this.normal.x;
  3856. var y = this.normal.y;
  3857. var z = this.normal.z;
  3858. var d = this.d;
  3859. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3860. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3861. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3862. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3863. return new Plane(normalX, normalY, normalZ, finalD);
  3864. };
  3865. /**
  3866. * Returns the dot product (float) of the point coordinates and the plane normal.
  3867. */
  3868. Plane.prototype.dotCoordinate = function (point) {
  3869. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3870. };
  3871. /**
  3872. * Updates the current Plane from the plane defined by the three passed points.
  3873. * Returns the updated Plane.
  3874. */
  3875. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3876. var x1 = point2.x - point1.x;
  3877. var y1 = point2.y - point1.y;
  3878. var z1 = point2.z - point1.z;
  3879. var x2 = point3.x - point1.x;
  3880. var y2 = point3.y - point1.y;
  3881. var z2 = point3.z - point1.z;
  3882. var yz = (y1 * z2) - (z1 * y2);
  3883. var xz = (z1 * x2) - (x1 * z2);
  3884. var xy = (x1 * y2) - (y1 * x2);
  3885. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3886. var invPyth;
  3887. if (pyth !== 0) {
  3888. invPyth = 1.0 / pyth;
  3889. }
  3890. else {
  3891. invPyth = 0.0;
  3892. }
  3893. this.normal.x = yz * invPyth;
  3894. this.normal.y = xz * invPyth;
  3895. this.normal.z = xy * invPyth;
  3896. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3897. return this;
  3898. };
  3899. /**
  3900. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3901. */
  3902. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3903. var dot = Vector3.Dot(this.normal, direction);
  3904. return (dot <= epsilon);
  3905. };
  3906. /**
  3907. * Returns the signed distance (float) from the passed point to the Plane.
  3908. */
  3909. Plane.prototype.signedDistanceTo = function (point) {
  3910. return Vector3.Dot(point, this.normal) + this.d;
  3911. };
  3912. // Statics
  3913. /**
  3914. * Returns a new Plane from the passed array.
  3915. */
  3916. Plane.FromArray = function (array) {
  3917. return new Plane(array[0], array[1], array[2], array[3]);
  3918. };
  3919. /**
  3920. * Returns a new Plane defined by the three passed points.
  3921. */
  3922. Plane.FromPoints = function (point1, point2, point3) {
  3923. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3924. result.copyFromPoints(point1, point2, point3);
  3925. return result;
  3926. };
  3927. /**
  3928. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3929. * Note : the vector "normal" is updated because normalized.
  3930. */
  3931. Plane.FromPositionAndNormal = function (origin, normal) {
  3932. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3933. normal.normalize();
  3934. result.normal = normal;
  3935. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3936. return result;
  3937. };
  3938. /**
  3939. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3940. */
  3941. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3942. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3943. return Vector3.Dot(point, normal) + d;
  3944. };
  3945. return Plane;
  3946. }());
  3947. BABYLON.Plane = Plane;
  3948. var Viewport = (function () {
  3949. /**
  3950. * Creates a Viewport object located at (x, y) and sized (width, height).
  3951. */
  3952. function Viewport(x, y, width, height) {
  3953. this.x = x;
  3954. this.y = y;
  3955. this.width = width;
  3956. this.height = height;
  3957. }
  3958. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3959. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3960. };
  3961. /**
  3962. * Returns a new Viewport copied from the current one.
  3963. */
  3964. Viewport.prototype.clone = function () {
  3965. return new Viewport(this.x, this.y, this.width, this.height);
  3966. };
  3967. return Viewport;
  3968. }());
  3969. BABYLON.Viewport = Viewport;
  3970. var Frustum = (function () {
  3971. function Frustum() {
  3972. }
  3973. /**
  3974. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  3975. */
  3976. Frustum.GetPlanes = function (transform) {
  3977. var frustumPlanes = [];
  3978. for (var index = 0; index < 6; index++) {
  3979. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  3980. }
  3981. Frustum.GetPlanesToRef(transform, frustumPlanes);
  3982. return frustumPlanes;
  3983. };
  3984. /**
  3985. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  3986. */
  3987. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  3988. // Near
  3989. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  3990. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  3991. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  3992. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  3993. frustumPlanes[0].normalize();
  3994. // Far
  3995. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  3996. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  3997. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  3998. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  3999. frustumPlanes[1].normalize();
  4000. // Left
  4001. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4002. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4003. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4004. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4005. frustumPlanes[2].normalize();
  4006. // Right
  4007. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4008. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4009. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4010. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4011. frustumPlanes[3].normalize();
  4012. // Top
  4013. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4014. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4015. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4016. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4017. frustumPlanes[4].normalize();
  4018. // Bottom
  4019. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4020. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4021. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4022. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4023. frustumPlanes[5].normalize();
  4024. };
  4025. return Frustum;
  4026. }());
  4027. BABYLON.Frustum = Frustum;
  4028. var Space;
  4029. (function (Space) {
  4030. Space[Space["LOCAL"] = 0] = "LOCAL";
  4031. Space[Space["WORLD"] = 1] = "WORLD";
  4032. Space[Space["BONE"] = 2] = "BONE";
  4033. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4034. var Axis = (function () {
  4035. function Axis() {
  4036. }
  4037. return Axis;
  4038. }());
  4039. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4040. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4041. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4042. BABYLON.Axis = Axis;
  4043. ;
  4044. var BezierCurve = (function () {
  4045. function BezierCurve() {
  4046. }
  4047. /**
  4048. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4049. */
  4050. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4051. // Extract X (which is equal to time here)
  4052. var f0 = 1 - 3 * x2 + 3 * x1;
  4053. var f1 = 3 * x2 - 6 * x1;
  4054. var f2 = 3 * x1;
  4055. var refinedT = t;
  4056. for (var i = 0; i < 5; i++) {
  4057. var refinedT2 = refinedT * refinedT;
  4058. var refinedT3 = refinedT2 * refinedT;
  4059. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4060. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4061. refinedT -= (x - t) * slope;
  4062. refinedT = Math.min(1, Math.max(0, refinedT));
  4063. }
  4064. // Resolve cubic bezier for the given x
  4065. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4066. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4067. Math.pow(refinedT, 3);
  4068. };
  4069. return BezierCurve;
  4070. }());
  4071. BABYLON.BezierCurve = BezierCurve;
  4072. var Orientation;
  4073. (function (Orientation) {
  4074. Orientation[Orientation["CW"] = 0] = "CW";
  4075. Orientation[Orientation["CCW"] = 1] = "CCW";
  4076. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4077. var Angle = (function () {
  4078. /**
  4079. * Creates an Angle object of "radians" radians (float).
  4080. */
  4081. function Angle(radians) {
  4082. var _this = this;
  4083. /**
  4084. * Returns the Angle value in degrees (float).
  4085. */
  4086. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4087. /**
  4088. * Returns the Angle value in radians (float).
  4089. */
  4090. this.radians = function () { return _this._radians; };
  4091. this._radians = radians;
  4092. if (this._radians < 0.0)
  4093. this._radians += (2.0 * Math.PI);
  4094. }
  4095. /**
  4096. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4097. */
  4098. Angle.BetweenTwoPoints = function (a, b) {
  4099. var delta = b.subtract(a);
  4100. var theta = Math.atan2(delta.y, delta.x);
  4101. return new Angle(theta);
  4102. };
  4103. /**
  4104. * Returns a new Angle object from the passed float in radians.
  4105. */
  4106. Angle.FromRadians = function (radians) {
  4107. return new Angle(radians);
  4108. };
  4109. /**
  4110. * Returns a new Angle object from the passed float in degrees.
  4111. */
  4112. Angle.FromDegrees = function (degrees) {
  4113. return new Angle(degrees * Math.PI / 180.0);
  4114. };
  4115. return Angle;
  4116. }());
  4117. BABYLON.Angle = Angle;
  4118. var Arc2 = (function () {
  4119. /**
  4120. * Creates an Arc object from the three passed points : start, middle and end.
  4121. */
  4122. function Arc2(startPoint, midPoint, endPoint) {
  4123. this.startPoint = startPoint;
  4124. this.midPoint = midPoint;
  4125. this.endPoint = endPoint;
  4126. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4127. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4128. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4129. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4130. 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);
  4131. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4132. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4133. var a1 = this.startAngle.degrees();
  4134. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4135. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4136. // angles correction
  4137. if (a2 - a1 > +180.0)
  4138. a2 -= 360.0;
  4139. if (a2 - a1 < -180.0)
  4140. a2 += 360.0;
  4141. if (a3 - a2 > +180.0)
  4142. a3 -= 360.0;
  4143. if (a3 - a2 < -180.0)
  4144. a3 += 360.0;
  4145. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4146. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4147. }
  4148. return Arc2;
  4149. }());
  4150. BABYLON.Arc2 = Arc2;
  4151. var Path2 = (function () {
  4152. /**
  4153. * Creates a Path2 object from the starting 2D coordinates x and y.
  4154. */
  4155. function Path2(x, y) {
  4156. this._points = new Array();
  4157. this._length = 0.0;
  4158. this.closed = false;
  4159. this._points.push(new Vector2(x, y));
  4160. }
  4161. /**
  4162. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4163. * Returns the updated Path2.
  4164. */
  4165. Path2.prototype.addLineTo = function (x, y) {
  4166. if (closed) {
  4167. //Tools.Error("cannot add lines to closed paths");
  4168. return this;
  4169. }
  4170. var newPoint = new Vector2(x, y);
  4171. var previousPoint = this._points[this._points.length - 1];
  4172. this._points.push(newPoint);
  4173. this._length += newPoint.subtract(previousPoint).length();
  4174. return this;
  4175. };
  4176. /**
  4177. * 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.
  4178. * Returns the updated Path2.
  4179. */
  4180. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4181. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4182. if (closed) {
  4183. //Tools.Error("cannot add arcs to closed paths");
  4184. return this;
  4185. }
  4186. var startPoint = this._points[this._points.length - 1];
  4187. var midPoint = new Vector2(midX, midY);
  4188. var endPoint = new Vector2(endX, endY);
  4189. var arc = new Arc2(startPoint, midPoint, endPoint);
  4190. var increment = arc.angle.radians() / numberOfSegments;
  4191. if (arc.orientation === Orientation.CW)
  4192. increment *= -1;
  4193. var currentAngle = arc.startAngle.radians() + increment;
  4194. for (var i = 0; i < numberOfSegments; i++) {
  4195. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4196. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4197. this.addLineTo(x, y);
  4198. currentAngle += increment;
  4199. }
  4200. return this;
  4201. };
  4202. /**
  4203. * Closes the Path2.
  4204. * Returns the Path2.
  4205. */
  4206. Path2.prototype.close = function () {
  4207. this.closed = true;
  4208. return this;
  4209. };
  4210. /**
  4211. * Returns the Path2 total length (float).
  4212. */
  4213. Path2.prototype.length = function () {
  4214. var result = this._length;
  4215. if (!this.closed) {
  4216. var lastPoint = this._points[this._points.length - 1];
  4217. var firstPoint = this._points[0];
  4218. result += (firstPoint.subtract(lastPoint).length());
  4219. }
  4220. return result;
  4221. };
  4222. /**
  4223. * Returns the Path2 internal array of points.
  4224. */
  4225. Path2.prototype.getPoints = function () {
  4226. return this._points;
  4227. };
  4228. /**
  4229. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4230. */
  4231. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4232. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4233. //Tools.Error("normalized length position should be between 0 and 1.");
  4234. return Vector2.Zero();
  4235. }
  4236. var lengthPosition = normalizedLengthPosition * this.length();
  4237. var previousOffset = 0;
  4238. for (var i = 0; i < this._points.length; i++) {
  4239. var j = (i + 1) % this._points.length;
  4240. var a = this._points[i];
  4241. var b = this._points[j];
  4242. var bToA = b.subtract(a);
  4243. var nextOffset = (bToA.length() + previousOffset);
  4244. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4245. var dir = bToA.normalize();
  4246. var localOffset = lengthPosition - previousOffset;
  4247. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4248. }
  4249. previousOffset = nextOffset;
  4250. }
  4251. //Tools.Error("internal error");
  4252. return Vector2.Zero();
  4253. };
  4254. /**
  4255. * Returns a new Path2 starting at the coordinates (x, y).
  4256. */
  4257. Path2.StartingAt = function (x, y) {
  4258. return new Path2(x, y);
  4259. };
  4260. return Path2;
  4261. }());
  4262. BABYLON.Path2 = Path2;
  4263. var Path3D = (function () {
  4264. /**
  4265. * new Path3D(path, normal, raw)
  4266. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4267. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4268. * path : an array of Vector3, the curve axis of the Path3D
  4269. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4270. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4271. */
  4272. function Path3D(path, firstNormal, raw) {
  4273. this.path = path;
  4274. this._curve = new Array();
  4275. this._distances = new Array();
  4276. this._tangents = new Array();
  4277. this._normals = new Array();
  4278. this._binormals = new Array();
  4279. for (var p = 0; p < path.length; p++) {
  4280. this._curve[p] = path[p].clone(); // hard copy
  4281. }
  4282. this._raw = raw || false;
  4283. this._compute(firstNormal);
  4284. }
  4285. /**
  4286. * Returns the Path3D array of successive Vector3 designing its curve.
  4287. */
  4288. Path3D.prototype.getCurve = function () {
  4289. return this._curve;
  4290. };
  4291. /**
  4292. * Returns an array populated with tangent vectors on each Path3D curve point.
  4293. */
  4294. Path3D.prototype.getTangents = function () {
  4295. return this._tangents;
  4296. };
  4297. /**
  4298. * Returns an array populated with normal vectors on each Path3D curve point.
  4299. */
  4300. Path3D.prototype.getNormals = function () {
  4301. return this._normals;
  4302. };
  4303. /**
  4304. * Returns an array populated with binormal vectors on each Path3D curve point.
  4305. */
  4306. Path3D.prototype.getBinormals = function () {
  4307. return this._binormals;
  4308. };
  4309. /**
  4310. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4311. */
  4312. Path3D.prototype.getDistances = function () {
  4313. return this._distances;
  4314. };
  4315. /**
  4316. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4317. * Returns the same object updated.
  4318. */
  4319. Path3D.prototype.update = function (path, firstNormal) {
  4320. for (var p = 0; p < path.length; p++) {
  4321. this._curve[p].x = path[p].x;
  4322. this._curve[p].y = path[p].y;
  4323. this._curve[p].z = path[p].z;
  4324. }
  4325. this._compute(firstNormal);
  4326. return this;
  4327. };
  4328. // private function compute() : computes tangents, normals and binormals
  4329. Path3D.prototype._compute = function (firstNormal) {
  4330. var l = this._curve.length;
  4331. // first and last tangents
  4332. this._tangents[0] = this._getFirstNonNullVector(0);
  4333. if (!this._raw) {
  4334. this._tangents[0].normalize();
  4335. }
  4336. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4337. if (!this._raw) {
  4338. this._tangents[l - 1].normalize();
  4339. }
  4340. // normals and binormals at first point : arbitrary vector with _normalVector()
  4341. var tg0 = this._tangents[0];
  4342. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4343. this._normals[0] = pp0;
  4344. if (!this._raw) {
  4345. this._normals[0].normalize();
  4346. }
  4347. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4348. if (!this._raw) {
  4349. this._binormals[0].normalize();
  4350. }
  4351. this._distances[0] = 0.0;
  4352. // normals and binormals : next points
  4353. var prev; // previous vector (segment)
  4354. var cur; // current vector (segment)
  4355. var curTang; // current tangent
  4356. // previous normal
  4357. var prevBinor; // previous binormal
  4358. for (var i = 1; i < l; i++) {
  4359. // tangents
  4360. prev = this._getLastNonNullVector(i);
  4361. if (i < l - 1) {
  4362. cur = this._getFirstNonNullVector(i);
  4363. this._tangents[i] = prev.add(cur);
  4364. this._tangents[i].normalize();
  4365. }
  4366. this._distances[i] = this._distances[i - 1] + prev.length();
  4367. // normals and binormals
  4368. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4369. curTang = this._tangents[i];
  4370. prevBinor = this._binormals[i - 1];
  4371. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4372. if (!this._raw) {
  4373. this._normals[i].normalize();
  4374. }
  4375. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4376. if (!this._raw) {
  4377. this._binormals[i].normalize();
  4378. }
  4379. }
  4380. };
  4381. // private function getFirstNonNullVector(index)
  4382. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4383. Path3D.prototype._getFirstNonNullVector = function (index) {
  4384. var i = 1;
  4385. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4386. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4387. i++;
  4388. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4389. }
  4390. return nNVector;
  4391. };
  4392. // private function getLastNonNullVector(index)
  4393. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4394. Path3D.prototype._getLastNonNullVector = function (index) {
  4395. var i = 1;
  4396. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4397. while (nLVector.length() === 0 && index > i + 1) {
  4398. i++;
  4399. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4400. }
  4401. return nLVector;
  4402. };
  4403. // private function normalVector(v0, vt, va) :
  4404. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4405. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4406. Path3D.prototype._normalVector = function (v0, vt, va) {
  4407. var normal0;
  4408. var tgl = vt.length();
  4409. if (tgl === 0.0) {
  4410. tgl = 1.0;
  4411. }
  4412. if (va === undefined || va === null) {
  4413. var point;
  4414. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4415. point = new Vector3(0.0, -1.0, 0.0);
  4416. }
  4417. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4418. point = new Vector3(1.0, 0.0, 0.0);
  4419. }
  4420. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4421. point = new Vector3(0.0, 0.0, 1.0);
  4422. }
  4423. normal0 = Vector3.Cross(vt, point);
  4424. }
  4425. else {
  4426. normal0 = Vector3.Cross(vt, va);
  4427. Vector3.CrossToRef(normal0, vt, normal0);
  4428. }
  4429. normal0.normalize();
  4430. return normal0;
  4431. };
  4432. return Path3D;
  4433. }());
  4434. BABYLON.Path3D = Path3D;
  4435. var Curve3 = (function () {
  4436. /**
  4437. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4438. * A Curve3 is designed from a series of successive Vector3.
  4439. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4440. */
  4441. function Curve3(points) {
  4442. this._length = 0.0;
  4443. this._points = points;
  4444. this._length = this._computeLength(points);
  4445. }
  4446. /**
  4447. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4448. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4449. * @param v1 (Vector3) the control point
  4450. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4451. * @param nbPoints (integer) the wanted number of points in the curve
  4452. */
  4453. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4454. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4455. var bez = new Array();
  4456. var equation = function (t, val0, val1, val2) {
  4457. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4458. return res;
  4459. };
  4460. for (var i = 0; i <= nbPoints; i++) {
  4461. 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)));
  4462. }
  4463. return new Curve3(bez);
  4464. };
  4465. /**
  4466. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4467. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4468. * @param v1 (Vector3) the first control point
  4469. * @param v2 (Vector3) the second control point
  4470. * @param v3 (Vector3) the end point of the Cubic Bezier
  4471. * @param nbPoints (integer) the wanted number of points in the curve
  4472. */
  4473. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4474. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4475. var bez = new Array();
  4476. var equation = function (t, val0, val1, val2, val3) {
  4477. 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;
  4478. return res;
  4479. };
  4480. for (var i = 0; i <= nbPoints; i++) {
  4481. 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)));
  4482. }
  4483. return new Curve3(bez);
  4484. };
  4485. /**
  4486. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4487. * @param p1 (Vector3) the origin point of the Hermite Spline
  4488. * @param t1 (Vector3) the tangent vector at the origin point
  4489. * @param p2 (Vector3) the end point of the Hermite Spline
  4490. * @param t2 (Vector3) the tangent vector at the end point
  4491. * @param nbPoints (integer) the wanted number of points in the curve
  4492. */
  4493. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4494. var hermite = new Array();
  4495. var step = 1.0 / nbPoints;
  4496. for (var i = 0; i <= nbPoints; i++) {
  4497. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4498. }
  4499. return new Curve3(hermite);
  4500. };
  4501. /**
  4502. * Returns a Curve3 object along a CatmullRom Spline curve :
  4503. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4504. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4505. */
  4506. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4507. var totalPoints = new Array();
  4508. totalPoints.push(points[0].clone());
  4509. Array.prototype.push.apply(totalPoints, points);
  4510. totalPoints.push(points[points.length - 1].clone());
  4511. var catmullRom = new Array();
  4512. var step = 1.0 / nbPoints;
  4513. for (var i = 0; i < totalPoints.length - 3; i++) {
  4514. var amount = 0.0;
  4515. for (var c = 0; c < nbPoints; c++) {
  4516. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4517. amount += step;
  4518. }
  4519. }
  4520. i--;
  4521. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4522. return new Curve3(catmullRom);
  4523. };
  4524. /**
  4525. * Returns the Curve3 stored array of successive Vector3
  4526. */
  4527. Curve3.prototype.getPoints = function () {
  4528. return this._points;
  4529. };
  4530. /**
  4531. * Returns the computed length (float) of the curve.
  4532. */
  4533. Curve3.prototype.length = function () {
  4534. return this._length;
  4535. };
  4536. /**
  4537. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4538. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4539. * curveA and curveB keep unchanged.
  4540. */
  4541. Curve3.prototype.continue = function (curve) {
  4542. var lastPoint = this._points[this._points.length - 1];
  4543. var continuedPoints = this._points.slice();
  4544. var curvePoints = curve.getPoints();
  4545. for (var i = 1; i < curvePoints.length; i++) {
  4546. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4547. }
  4548. var continuedCurve = new Curve3(continuedPoints);
  4549. return continuedCurve;
  4550. };
  4551. Curve3.prototype._computeLength = function (path) {
  4552. var l = 0;
  4553. for (var i = 1; i < path.length; i++) {
  4554. l += (path[i].subtract(path[i - 1])).length();
  4555. }
  4556. return l;
  4557. };
  4558. return Curve3;
  4559. }());
  4560. BABYLON.Curve3 = Curve3;
  4561. // SphericalHarmonics
  4562. var SphericalHarmonics = (function () {
  4563. function SphericalHarmonics() {
  4564. this.L00 = Vector3.Zero();
  4565. this.L1_1 = Vector3.Zero();
  4566. this.L10 = Vector3.Zero();
  4567. this.L11 = Vector3.Zero();
  4568. this.L2_2 = Vector3.Zero();
  4569. this.L2_1 = Vector3.Zero();
  4570. this.L20 = Vector3.Zero();
  4571. this.L21 = Vector3.Zero();
  4572. this.L22 = Vector3.Zero();
  4573. }
  4574. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4575. var colorVector = new Vector3(color.r, color.g, color.b);
  4576. var c = colorVector.scale(deltaSolidAngle);
  4577. this.L00 = this.L00.add(c.scale(0.282095));
  4578. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4579. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4580. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4581. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4582. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4583. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4584. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4585. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4586. };
  4587. SphericalHarmonics.prototype.scale = function (scale) {
  4588. this.L00 = this.L00.scale(scale);
  4589. this.L1_1 = this.L1_1.scale(scale);
  4590. this.L10 = this.L10.scale(scale);
  4591. this.L11 = this.L11.scale(scale);
  4592. this.L2_2 = this.L2_2.scale(scale);
  4593. this.L2_1 = this.L2_1.scale(scale);
  4594. this.L20 = this.L20.scale(scale);
  4595. this.L21 = this.L21.scale(scale);
  4596. this.L22 = this.L22.scale(scale);
  4597. };
  4598. return SphericalHarmonics;
  4599. }());
  4600. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4601. // SphericalPolynomial
  4602. var SphericalPolynomial = (function () {
  4603. function SphericalPolynomial() {
  4604. this.x = Vector3.Zero();
  4605. this.y = Vector3.Zero();
  4606. this.z = Vector3.Zero();
  4607. this.xx = Vector3.Zero();
  4608. this.yy = Vector3.Zero();
  4609. this.zz = Vector3.Zero();
  4610. this.xy = Vector3.Zero();
  4611. this.yz = Vector3.Zero();
  4612. this.zx = Vector3.Zero();
  4613. }
  4614. SphericalPolynomial.prototype.addAmbient = function (color) {
  4615. var colorVector = new Vector3(color.r, color.g, color.b);
  4616. this.xx = this.xx.add(colorVector);
  4617. this.yy = this.yy.add(colorVector);
  4618. this.zz = this.zz.add(colorVector);
  4619. };
  4620. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4621. var result = new SphericalPolynomial();
  4622. result.x = harmonics.L11.scale(1.02333);
  4623. result.y = harmonics.L1_1.scale(1.02333);
  4624. result.z = harmonics.L10.scale(1.02333);
  4625. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4626. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4627. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4628. result.yz = harmonics.L2_1.scale(0.858086);
  4629. result.zx = harmonics.L21.scale(0.858086);
  4630. result.xy = harmonics.L2_2.scale(0.858086);
  4631. return result;
  4632. };
  4633. return SphericalPolynomial;
  4634. }());
  4635. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4636. // Vertex formats
  4637. var PositionNormalVertex = (function () {
  4638. function PositionNormalVertex(position, normal) {
  4639. if (position === void 0) { position = Vector3.Zero(); }
  4640. if (normal === void 0) { normal = Vector3.Up(); }
  4641. this.position = position;
  4642. this.normal = normal;
  4643. }
  4644. PositionNormalVertex.prototype.clone = function () {
  4645. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4646. };
  4647. return PositionNormalVertex;
  4648. }());
  4649. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4650. var PositionNormalTextureVertex = (function () {
  4651. function PositionNormalTextureVertex(position, normal, uv) {
  4652. if (position === void 0) { position = Vector3.Zero(); }
  4653. if (normal === void 0) { normal = Vector3.Up(); }
  4654. if (uv === void 0) { uv = Vector2.Zero(); }
  4655. this.position = position;
  4656. this.normal = normal;
  4657. this.uv = uv;
  4658. }
  4659. PositionNormalTextureVertex.prototype.clone = function () {
  4660. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4661. };
  4662. return PositionNormalTextureVertex;
  4663. }());
  4664. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4665. // Temporary pre-allocated objects for engine internal use
  4666. // usage in any internal function :
  4667. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4668. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4669. var Tmp = (function () {
  4670. function Tmp() {
  4671. }
  4672. return Tmp;
  4673. }());
  4674. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4675. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4676. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4677. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4678. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4679. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4680. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4681. Matrix.Zero(), Matrix.Zero(),
  4682. Matrix.Zero(), Matrix.Zero(),
  4683. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4684. BABYLON.Tmp = Tmp;
  4685. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4686. var MathTmp = (function () {
  4687. function MathTmp() {
  4688. }
  4689. return MathTmp;
  4690. }());
  4691. MathTmp.Vector3 = [Vector3.Zero()];
  4692. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4693. MathTmp.Quaternion = [Quaternion.Zero()];
  4694. })(BABYLON || (BABYLON = {}));
  4695. //# sourceMappingURL=babylon.math.js.map
  4696. //# sourceMappingURL=babylon.mixins.js.map
  4697. var BABYLON;
  4698. (function (BABYLON) {
  4699. function generateSerializableMember(type, sourceName) {
  4700. return function (target, propertyKey) {
  4701. if (!target.__serializableMembers) {
  4702. target.__serializableMembers = {};
  4703. }
  4704. if (!target.__serializableMembers[propertyKey]) {
  4705. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4706. }
  4707. };
  4708. }
  4709. function generateExpandMember(setCallback) {
  4710. return function (target, propertyKey) {
  4711. if (setCallback) {
  4712. var key = "_" + propertyKey;
  4713. Object.defineProperty(target, propertyKey, {
  4714. get: function () {
  4715. return this[key];
  4716. },
  4717. set: function (value) {
  4718. if (this[key] === value) {
  4719. return;
  4720. }
  4721. this[key] = value;
  4722. target[setCallback].apply(this);
  4723. },
  4724. enumerable: true,
  4725. configurable: true
  4726. });
  4727. }
  4728. };
  4729. }
  4730. function expandToProperty(callback) {
  4731. return generateExpandMember(callback);
  4732. }
  4733. BABYLON.expandToProperty = expandToProperty;
  4734. function serialize(sourceName) {
  4735. return generateSerializableMember(0, sourceName); // value member
  4736. }
  4737. BABYLON.serialize = serialize;
  4738. function serializeAsTexture(sourceName) {
  4739. return generateSerializableMember(1, sourceName); // texture member
  4740. }
  4741. BABYLON.serializeAsTexture = serializeAsTexture;
  4742. function serializeAsColor3(sourceName) {
  4743. return generateSerializableMember(2, sourceName); // color3 member
  4744. }
  4745. BABYLON.serializeAsColor3 = serializeAsColor3;
  4746. function serializeAsFresnelParameters(sourceName) {
  4747. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4748. }
  4749. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4750. function serializeAsVector2(sourceName) {
  4751. return generateSerializableMember(4, sourceName); // vector2 member
  4752. }
  4753. BABYLON.serializeAsVector2 = serializeAsVector2;
  4754. function serializeAsVector3(sourceName) {
  4755. return generateSerializableMember(5, sourceName); // vector3 member
  4756. }
  4757. BABYLON.serializeAsVector3 = serializeAsVector3;
  4758. function serializeAsMeshReference(sourceName) {
  4759. return generateSerializableMember(6, sourceName); // mesh reference member
  4760. }
  4761. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4762. function serializeAsColorCurves(sourceName) {
  4763. return generateSerializableMember(7, sourceName); // color curves
  4764. }
  4765. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4766. var SerializationHelper = (function () {
  4767. function SerializationHelper() {
  4768. }
  4769. SerializationHelper.Serialize = function (entity, serializationObject) {
  4770. if (!serializationObject) {
  4771. serializationObject = {};
  4772. }
  4773. // Tags
  4774. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4775. // Properties
  4776. for (var property in entity.__serializableMembers) {
  4777. var propertyDescriptor = entity.__serializableMembers[property];
  4778. var targetPropertyName = propertyDescriptor.sourceName || property;
  4779. var propertyType = propertyDescriptor.type;
  4780. var sourceProperty = entity[property];
  4781. if (sourceProperty !== undefined && sourceProperty !== null) {
  4782. switch (propertyType) {
  4783. case 0:
  4784. serializationObject[targetPropertyName] = sourceProperty;
  4785. break;
  4786. case 1:
  4787. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4788. break;
  4789. case 2:
  4790. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4791. break;
  4792. case 3:
  4793. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4794. break;
  4795. case 4:
  4796. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4797. break;
  4798. case 5:
  4799. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4800. break;
  4801. case 6:
  4802. serializationObject[targetPropertyName] = sourceProperty.id;
  4803. break;
  4804. case 7:
  4805. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4806. break;
  4807. }
  4808. }
  4809. }
  4810. return serializationObject;
  4811. };
  4812. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4813. var destination = creationFunction();
  4814. // Tags
  4815. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4816. // Properties
  4817. for (var property in destination.__serializableMembers) {
  4818. var propertyDescriptor = destination.__serializableMembers[property];
  4819. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4820. var propertyType = propertyDescriptor.type;
  4821. if (sourceProperty !== undefined && sourceProperty !== null) {
  4822. switch (propertyType) {
  4823. case 0:
  4824. destination[property] = sourceProperty;
  4825. break;
  4826. case 1:
  4827. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4828. break;
  4829. case 2:
  4830. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4831. break;
  4832. case 3:
  4833. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4834. break;
  4835. case 4:
  4836. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4837. break;
  4838. case 5:
  4839. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4840. break;
  4841. case 6:
  4842. destination[property] = scene.getLastMeshByID(sourceProperty);
  4843. break;
  4844. case 7:
  4845. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4846. break;
  4847. }
  4848. }
  4849. }
  4850. return destination;
  4851. };
  4852. SerializationHelper.Clone = function (creationFunction, source) {
  4853. var destination = creationFunction();
  4854. // Tags
  4855. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4856. // Properties
  4857. for (var property in destination.__serializableMembers) {
  4858. var propertyDescriptor = destination.__serializableMembers[property];
  4859. var sourceProperty = source[property];
  4860. var propertyType = propertyDescriptor.type;
  4861. if (sourceProperty !== undefined && sourceProperty !== null) {
  4862. switch (propertyType) {
  4863. case 0: // Value
  4864. case 6:
  4865. destination[property] = sourceProperty;
  4866. break;
  4867. case 1: // Texture
  4868. case 2: // Color3
  4869. case 3: // FresnelParameters
  4870. case 4: // Vector2
  4871. case 5: // Vector3
  4872. case 7:
  4873. destination[property] = sourceProperty.clone();
  4874. break;
  4875. }
  4876. }
  4877. }
  4878. return destination;
  4879. };
  4880. return SerializationHelper;
  4881. }());
  4882. BABYLON.SerializationHelper = SerializationHelper;
  4883. })(BABYLON || (BABYLON = {}));
  4884. //# sourceMappingURL=babylon.decorators.js.map
  4885. var BABYLON;
  4886. (function (BABYLON) {
  4887. /**
  4888. * A class serves as a medium between the observable and its observers
  4889. */
  4890. var EventState = (function () {
  4891. /**
  4892. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4893. */
  4894. function EventState(mask, skipNextObservers) {
  4895. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4896. this.initalize(mask, skipNextObservers);
  4897. }
  4898. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4899. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4900. this.mask = mask;
  4901. this.skipNextObservers = skipNextObservers;
  4902. return this;
  4903. };
  4904. return EventState;
  4905. }());
  4906. BABYLON.EventState = EventState;
  4907. /**
  4908. * Represent an Observer registered to a given Observable object.
  4909. */
  4910. var Observer = (function () {
  4911. function Observer(callback, mask) {
  4912. this.callback = callback;
  4913. this.mask = mask;
  4914. }
  4915. return Observer;
  4916. }());
  4917. BABYLON.Observer = Observer;
  4918. /**
  4919. * The Observable class is a simple implementation of the Observable pattern.
  4920. * 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.
  4921. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4922. * 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).
  4923. * 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.
  4924. */
  4925. var Observable = (function () {
  4926. function Observable() {
  4927. this._observers = new Array();
  4928. this._eventState = new EventState(0);
  4929. }
  4930. /**
  4931. * Create a new Observer with the specified callback
  4932. * @param callback the callback that will be executed for that Observer
  4933. * @param mask the mask used to filter observers
  4934. * @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.
  4935. */
  4936. Observable.prototype.add = function (callback, mask, insertFirst) {
  4937. if (mask === void 0) { mask = -1; }
  4938. if (insertFirst === void 0) { insertFirst = false; }
  4939. if (!callback) {
  4940. return null;
  4941. }
  4942. var observer = new Observer(callback, mask);
  4943. if (insertFirst) {
  4944. this._observers.unshift(observer);
  4945. }
  4946. else {
  4947. this._observers.push(observer);
  4948. }
  4949. return observer;
  4950. };
  4951. /**
  4952. * Remove an Observer from the Observable object
  4953. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4954. */
  4955. Observable.prototype.remove = function (observer) {
  4956. var index = this._observers.indexOf(observer);
  4957. if (index !== -1) {
  4958. this._observers.splice(index, 1);
  4959. return true;
  4960. }
  4961. return false;
  4962. };
  4963. /**
  4964. * Remove a callback from the Observable object
  4965. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4966. */
  4967. Observable.prototype.removeCallback = function (callback) {
  4968. for (var index = 0; index < this._observers.length; index++) {
  4969. if (this._observers[index].callback === callback) {
  4970. this._observers.splice(index, 1);
  4971. return true;
  4972. }
  4973. }
  4974. return false;
  4975. };
  4976. /**
  4977. * Notify all Observers by calling their respective callback with the given data
  4978. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  4979. * @param eventData
  4980. * @param mask
  4981. */
  4982. Observable.prototype.notifyObservers = function (eventData, mask) {
  4983. if (mask === void 0) { mask = -1; }
  4984. var state = this._eventState;
  4985. state.mask = mask;
  4986. state.skipNextObservers = false;
  4987. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4988. var obs = _a[_i];
  4989. if (obs.mask & mask) {
  4990. obs.callback(eventData, state);
  4991. }
  4992. if (state.skipNextObservers) {
  4993. return false;
  4994. }
  4995. }
  4996. return true;
  4997. };
  4998. /**
  4999. * return true is the Observable has at least one Observer registered
  5000. */
  5001. Observable.prototype.hasObservers = function () {
  5002. return this._observers.length > 0;
  5003. };
  5004. /**
  5005. * Clear the list of observers
  5006. */
  5007. Observable.prototype.clear = function () {
  5008. this._observers = new Array();
  5009. };
  5010. /**
  5011. * Clone the current observable
  5012. */
  5013. Observable.prototype.clone = function () {
  5014. var result = new Observable();
  5015. result._observers = this._observers.slice(0);
  5016. return result;
  5017. };
  5018. /**
  5019. * Does this observable handles observer registered with a given mask
  5020. * @param {number} trigger - the mask to be tested
  5021. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5022. **/
  5023. Observable.prototype.hasSpecificMask = function (mask) {
  5024. if (mask === void 0) { mask = -1; }
  5025. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5026. var obs = _a[_i];
  5027. if (obs.mask & mask && obs.mask === mask) {
  5028. return true;
  5029. }
  5030. }
  5031. return false;
  5032. };
  5033. return Observable;
  5034. }());
  5035. BABYLON.Observable = Observable;
  5036. })(BABYLON || (BABYLON = {}));
  5037. //# sourceMappingURL=babylon.observable.js.map
  5038. var BABYLON;
  5039. (function (BABYLON) {
  5040. var SmartArray = (function () {
  5041. function SmartArray(capacity) {
  5042. this.length = 0;
  5043. this._duplicateId = 0;
  5044. this.data = new Array(capacity);
  5045. this._id = SmartArray._GlobalId++;
  5046. }
  5047. SmartArray.prototype.push = function (value) {
  5048. this.data[this.length++] = value;
  5049. if (this.length > this.data.length) {
  5050. this.data.length *= 2;
  5051. }
  5052. if (!value.__smartArrayFlags) {
  5053. value.__smartArrayFlags = {};
  5054. }
  5055. value.__smartArrayFlags[this._id] = this._duplicateId;
  5056. };
  5057. SmartArray.prototype.forEach = function (func) {
  5058. for (var index = 0; index < this.length; index++) {
  5059. func(this.data[index]);
  5060. }
  5061. };
  5062. SmartArray.prototype.pushNoDuplicate = function (value) {
  5063. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5064. return false;
  5065. }
  5066. this.push(value);
  5067. return true;
  5068. };
  5069. SmartArray.prototype.sort = function (compareFn) {
  5070. this.data.sort(compareFn);
  5071. };
  5072. SmartArray.prototype.reset = function () {
  5073. this.length = 0;
  5074. this._duplicateId++;
  5075. };
  5076. SmartArray.prototype.dispose = function () {
  5077. this.reset();
  5078. this.data.length = 0;
  5079. };
  5080. SmartArray.prototype.concat = function (array) {
  5081. if (array.length === 0) {
  5082. return;
  5083. }
  5084. if (this.length + array.length > this.data.length) {
  5085. this.data.length = (this.length + array.length) * 2;
  5086. }
  5087. for (var index = 0; index < array.length; index++) {
  5088. this.data[this.length++] = (array.data || array)[index];
  5089. }
  5090. };
  5091. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5092. if (array.length === 0) {
  5093. return;
  5094. }
  5095. if (this.length + array.length > this.data.length) {
  5096. this.data.length = (this.length + array.length) * 2;
  5097. }
  5098. for (var index = 0; index < array.length; index++) {
  5099. var item = (array.data || array)[index];
  5100. this.pushNoDuplicate(item);
  5101. }
  5102. };
  5103. SmartArray.prototype.indexOf = function (value) {
  5104. var position = this.data.indexOf(value);
  5105. if (position >= this.length) {
  5106. return -1;
  5107. }
  5108. return position;
  5109. };
  5110. SmartArray.prototype.contains = function (value) {
  5111. return this.data.indexOf(value) !== -1;
  5112. };
  5113. return SmartArray;
  5114. }());
  5115. // Statics
  5116. SmartArray._GlobalId = 0;
  5117. BABYLON.SmartArray = SmartArray;
  5118. })(BABYLON || (BABYLON = {}));
  5119. //# sourceMappingURL=babylon.smartArray.js.map
  5120. var BABYLON;
  5121. (function (BABYLON) {
  5122. // Screenshots
  5123. var screenshotCanvas;
  5124. var cloneValue = function (source, destinationObject) {
  5125. if (!source)
  5126. return null;
  5127. if (source instanceof BABYLON.Mesh) {
  5128. return null;
  5129. }
  5130. if (source instanceof BABYLON.SubMesh) {
  5131. return source.clone(destinationObject);
  5132. }
  5133. else if (source.clone) {
  5134. return source.clone();
  5135. }
  5136. return null;
  5137. };
  5138. var Tools = (function () {
  5139. function Tools() {
  5140. }
  5141. ;
  5142. Tools.Instantiate = function (className) {
  5143. var arr = className.split(".");
  5144. var fn = (window || this);
  5145. for (var i = 0, len = arr.length; i < len; i++) {
  5146. fn = fn[arr[i]];
  5147. }
  5148. if (typeof fn !== "function") {
  5149. return null;
  5150. }
  5151. return fn;
  5152. };
  5153. Tools.SetImmediate = function (action) {
  5154. if (window.setImmediate) {
  5155. window.setImmediate(action);
  5156. }
  5157. else {
  5158. setTimeout(action, 1);
  5159. }
  5160. };
  5161. Tools.IsExponentOfTwo = function (value) {
  5162. var count = 1;
  5163. do {
  5164. count *= 2;
  5165. } while (count < value);
  5166. return count === value;
  5167. };
  5168. Tools.GetExponentOfTwo = function (value, max) {
  5169. var count = 1;
  5170. do {
  5171. count *= 2;
  5172. } while (count < value);
  5173. if (count > max)
  5174. count = max;
  5175. return count;
  5176. };
  5177. Tools.GetFilename = function (path) {
  5178. var index = path.lastIndexOf("/");
  5179. if (index < 0)
  5180. return path;
  5181. return path.substring(index + 1);
  5182. };
  5183. Tools.GetDOMTextContent = function (element) {
  5184. var result = "";
  5185. var child = element.firstChild;
  5186. while (child) {
  5187. if (child.nodeType === 3) {
  5188. result += child.textContent;
  5189. }
  5190. child = child.nextSibling;
  5191. }
  5192. return result;
  5193. };
  5194. Tools.ToDegrees = function (angle) {
  5195. return angle * 180 / Math.PI;
  5196. };
  5197. Tools.ToRadians = function (angle) {
  5198. return angle * Math.PI / 180;
  5199. };
  5200. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5201. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5202. var output = "";
  5203. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5204. var i = 0;
  5205. var bytes = new Uint8Array(buffer);
  5206. while (i < bytes.length) {
  5207. chr1 = bytes[i++];
  5208. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5209. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5210. enc1 = chr1 >> 2;
  5211. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5212. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5213. enc4 = chr3 & 63;
  5214. if (isNaN(chr2)) {
  5215. enc3 = enc4 = 64;
  5216. }
  5217. else if (isNaN(chr3)) {
  5218. enc4 = 64;
  5219. }
  5220. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5221. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5222. }
  5223. return "data:image/png;base64," + output;
  5224. };
  5225. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5226. if (bias === void 0) { bias = null; }
  5227. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5228. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5229. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5230. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5231. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5232. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5233. }
  5234. if (bias) {
  5235. minimum.x -= minimum.x * bias.x + bias.y;
  5236. minimum.y -= minimum.y * bias.x + bias.y;
  5237. minimum.z -= minimum.z * bias.x + bias.y;
  5238. maximum.x += maximum.x * bias.x + bias.y;
  5239. maximum.y += maximum.y * bias.x + bias.y;
  5240. maximum.z += maximum.z * bias.x + bias.y;
  5241. }
  5242. return {
  5243. minimum: minimum,
  5244. maximum: maximum
  5245. };
  5246. };
  5247. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5248. if (bias === void 0) { bias = null; }
  5249. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5250. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5251. if (!stride) {
  5252. stride = 3;
  5253. }
  5254. for (var index = start; index < start + count; index++) {
  5255. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5256. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5257. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5258. }
  5259. if (bias) {
  5260. minimum.x -= minimum.x * bias.x + bias.y;
  5261. minimum.y -= minimum.y * bias.x + bias.y;
  5262. minimum.z -= minimum.z * bias.x + bias.y;
  5263. maximum.x += maximum.x * bias.x + bias.y;
  5264. maximum.y += maximum.y * bias.x + bias.y;
  5265. maximum.z += maximum.z * bias.x + bias.y;
  5266. }
  5267. return {
  5268. minimum: minimum,
  5269. maximum: maximum
  5270. };
  5271. };
  5272. Tools.Vector2ArrayFeeder = function (array) {
  5273. return function (index) {
  5274. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5275. var length = isFloatArray ? array.length / 2 : array.length;
  5276. if (index >= length) {
  5277. return null;
  5278. }
  5279. if (isFloatArray) {
  5280. var fa = array;
  5281. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5282. }
  5283. var a = array;
  5284. return a[index];
  5285. };
  5286. };
  5287. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5288. if (bias === void 0) { bias = null; }
  5289. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5290. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5291. var i = 0;
  5292. var cur = feeder(i++);
  5293. while (cur) {
  5294. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5295. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5296. cur = feeder(i++);
  5297. }
  5298. if (bias) {
  5299. minimum.x -= minimum.x * bias.x + bias.y;
  5300. minimum.y -= minimum.y * bias.x + bias.y;
  5301. maximum.x += maximum.x * bias.x + bias.y;
  5302. maximum.y += maximum.y * bias.x + bias.y;
  5303. }
  5304. return {
  5305. minimum: minimum,
  5306. maximum: maximum
  5307. };
  5308. };
  5309. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5310. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5311. return undefined;
  5312. return Array.isArray(obj) ? obj : [obj];
  5313. };
  5314. // Misc.
  5315. Tools.GetPointerPrefix = function () {
  5316. var eventPrefix = "pointer";
  5317. // Check if pointer events are supported
  5318. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5319. eventPrefix = "mouse";
  5320. }
  5321. return eventPrefix;
  5322. };
  5323. /**
  5324. * @param func - the function to be called
  5325. * @param requester - the object that will request the next frame. Falls back to window.
  5326. */
  5327. Tools.QueueNewFrame = function (func, requester) {
  5328. if (requester === void 0) { requester = window; }
  5329. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5330. /*if(requester.isPresenting) {
  5331. return;
  5332. } else*/ if (requester.requestAnimationFrame)
  5333. requester.requestAnimationFrame(func);
  5334. else if (requester.msRequestAnimationFrame)
  5335. requester.msRequestAnimationFrame(func);
  5336. else if (requester.webkitRequestAnimationFrame)
  5337. requester.webkitRequestAnimationFrame(func);
  5338. else if (requester.mozRequestAnimationFrame)
  5339. requester.mozRequestAnimationFrame(func);
  5340. else if (requester.oRequestAnimationFrame)
  5341. requester.oRequestAnimationFrame(func);
  5342. else {
  5343. window.setTimeout(func, 16);
  5344. }
  5345. };
  5346. Tools.RequestFullscreen = function (element) {
  5347. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5348. if (!requestFunction)
  5349. return;
  5350. requestFunction.call(element);
  5351. };
  5352. Tools.ExitFullscreen = function () {
  5353. if (document.exitFullscreen) {
  5354. document.exitFullscreen();
  5355. }
  5356. else if (document.mozCancelFullScreen) {
  5357. document.mozCancelFullScreen();
  5358. }
  5359. else if (document.webkitCancelFullScreen) {
  5360. document.webkitCancelFullScreen();
  5361. }
  5362. else if (document.msCancelFullScreen) {
  5363. document.msCancelFullScreen();
  5364. }
  5365. };
  5366. Tools.SetCorsBehavior = function (url, img) {
  5367. if (Tools.CorsBehavior) {
  5368. switch (typeof (Tools.CorsBehavior)) {
  5369. case "function":
  5370. var result = Tools.CorsBehavior(url);
  5371. if (result) {
  5372. img.crossOrigin = result;
  5373. }
  5374. break;
  5375. case "string":
  5376. default:
  5377. img.crossOrigin = Tools.CorsBehavior;
  5378. break;
  5379. }
  5380. }
  5381. };
  5382. // External files
  5383. Tools.CleanUrl = function (url) {
  5384. url = url.replace(/#/mg, "%23");
  5385. return url;
  5386. };
  5387. Tools.LoadImage = function (url, onload, onerror, database) {
  5388. if (url instanceof ArrayBuffer) {
  5389. url = Tools.EncodeArrayBufferTobase64(url);
  5390. }
  5391. url = Tools.CleanUrl(url);
  5392. var img = new Image();
  5393. if (url.substr(0, 5) !== "data:") {
  5394. Tools.SetCorsBehavior(url, img);
  5395. }
  5396. img.onload = function () {
  5397. onload(img);
  5398. };
  5399. img.onerror = function (err) {
  5400. Tools.Error("Error while trying to load image: " + url);
  5401. if (Tools.UseFallbackTexture) {
  5402. img.src = Tools.fallbackTexture;
  5403. onload(img);
  5404. }
  5405. else {
  5406. onerror();
  5407. }
  5408. };
  5409. var noIndexedDB = function () {
  5410. img.src = url;
  5411. };
  5412. var loadFromIndexedDB = function () {
  5413. database.loadImageFromDB(url, img);
  5414. };
  5415. //ANY database to do!
  5416. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5417. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5418. }
  5419. else {
  5420. if (url.indexOf("file:") === -1) {
  5421. noIndexedDB();
  5422. }
  5423. else {
  5424. var textureName = url.substring(5).toLowerCase();
  5425. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5426. try {
  5427. var blobURL;
  5428. try {
  5429. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5430. }
  5431. catch (ex) {
  5432. // Chrome doesn't support oneTimeOnly parameter
  5433. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5434. }
  5435. img.src = blobURL;
  5436. }
  5437. catch (e) {
  5438. img.src = null;
  5439. }
  5440. }
  5441. else {
  5442. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5443. img.src = Tools.fallbackTexture;
  5444. }
  5445. }
  5446. }
  5447. return img;
  5448. };
  5449. //ANY
  5450. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5451. url = Tools.CleanUrl(url);
  5452. var noIndexedDB = function () {
  5453. var request = new XMLHttpRequest();
  5454. var loadUrl = Tools.BaseUrl + url;
  5455. request.open('GET', loadUrl, true);
  5456. if (useArrayBuffer) {
  5457. request.responseType = "arraybuffer";
  5458. }
  5459. request.onprogress = progressCallBack;
  5460. request.onreadystatechange = function () {
  5461. if (request.readyState === 4) {
  5462. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5463. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5464. callback(!useArrayBuffer ? request.responseText : request.response);
  5465. }
  5466. else {
  5467. if (onError) {
  5468. onError();
  5469. }
  5470. else {
  5471. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5472. }
  5473. }
  5474. }
  5475. };
  5476. request.send(null);
  5477. };
  5478. var loadFromIndexedDB = function () {
  5479. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5480. };
  5481. if (url.indexOf("file:") !== -1) {
  5482. var fileName = url.substring(5).toLowerCase();
  5483. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5484. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5485. }
  5486. else {
  5487. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5488. }
  5489. }
  5490. else {
  5491. // Caching all files
  5492. if (database && database.enableSceneOffline) {
  5493. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5494. }
  5495. else {
  5496. noIndexedDB();
  5497. }
  5498. }
  5499. };
  5500. /**
  5501. * Load a script (identified by an url). When the url returns, the
  5502. * content of this file is added into a new script element, attached to the DOM (body element)
  5503. */
  5504. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5505. var head = document.getElementsByTagName('head')[0];
  5506. var script = document.createElement('script');
  5507. script.type = 'text/javascript';
  5508. script.src = scriptUrl;
  5509. var self = this;
  5510. script.onload = function () {
  5511. if (onSuccess) {
  5512. onSuccess();
  5513. }
  5514. };
  5515. script.onerror = function () {
  5516. if (onError) {
  5517. onError();
  5518. }
  5519. };
  5520. head.appendChild(script);
  5521. };
  5522. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5523. var reader = new FileReader();
  5524. reader.onload = function (e) {
  5525. //target doesn't have result from ts 1.3
  5526. callback(e.target['result']);
  5527. };
  5528. reader.onprogress = progressCallback;
  5529. reader.readAsDataURL(fileToLoad);
  5530. };
  5531. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5532. var reader = new FileReader();
  5533. reader.onerror = function (e) {
  5534. Tools.Log("Error while reading file: " + fileToLoad.name);
  5535. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5536. };
  5537. reader.onload = function (e) {
  5538. //target doesn't have result from ts 1.3
  5539. callback(e.target['result']);
  5540. };
  5541. reader.onprogress = progressCallBack;
  5542. if (!useArrayBuffer) {
  5543. // Asynchronous read
  5544. reader.readAsText(fileToLoad);
  5545. }
  5546. else {
  5547. reader.readAsArrayBuffer(fileToLoad);
  5548. }
  5549. };
  5550. //returns a downloadable url to a file content.
  5551. Tools.FileAsURL = function (content) {
  5552. var fileBlob = new Blob([content]);
  5553. var url = window.URL || window.webkitURL;
  5554. var link = url.createObjectURL(fileBlob);
  5555. return link;
  5556. };
  5557. // Misc.
  5558. Tools.Format = function (value, decimals) {
  5559. if (decimals === void 0) { decimals = 2; }
  5560. return value.toFixed(decimals);
  5561. };
  5562. Tools.CheckExtends = function (v, min, max) {
  5563. if (v.x < min.x)
  5564. min.x = v.x;
  5565. if (v.y < min.y)
  5566. min.y = v.y;
  5567. if (v.z < min.z)
  5568. min.z = v.z;
  5569. if (v.x > max.x)
  5570. max.x = v.x;
  5571. if (v.y > max.y)
  5572. max.y = v.y;
  5573. if (v.z > max.z)
  5574. max.z = v.z;
  5575. };
  5576. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5577. for (var prop in source) {
  5578. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5579. continue;
  5580. }
  5581. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5582. continue;
  5583. }
  5584. var sourceValue = source[prop];
  5585. var typeOfSourceValue = typeof sourceValue;
  5586. if (typeOfSourceValue === "function") {
  5587. continue;
  5588. }
  5589. if (typeOfSourceValue === "object") {
  5590. if (sourceValue instanceof Array) {
  5591. destination[prop] = [];
  5592. if (sourceValue.length > 0) {
  5593. if (typeof sourceValue[0] == "object") {
  5594. for (var index = 0; index < sourceValue.length; index++) {
  5595. var clonedValue = cloneValue(sourceValue[index], destination);
  5596. if (destination[prop].indexOf(clonedValue) === -1) {
  5597. destination[prop].push(clonedValue);
  5598. }
  5599. }
  5600. }
  5601. else {
  5602. destination[prop] = sourceValue.slice(0);
  5603. }
  5604. }
  5605. }
  5606. else {
  5607. destination[prop] = cloneValue(sourceValue, destination);
  5608. }
  5609. }
  5610. else {
  5611. destination[prop] = sourceValue;
  5612. }
  5613. }
  5614. };
  5615. Tools.IsEmpty = function (obj) {
  5616. for (var i in obj) {
  5617. return false;
  5618. }
  5619. return true;
  5620. };
  5621. Tools.RegisterTopRootEvents = function (events) {
  5622. for (var index = 0; index < events.length; index++) {
  5623. var event = events[index];
  5624. window.addEventListener(event.name, event.handler, false);
  5625. try {
  5626. if (window.parent) {
  5627. window.parent.addEventListener(event.name, event.handler, false);
  5628. }
  5629. }
  5630. catch (e) {
  5631. // Silently fails...
  5632. }
  5633. }
  5634. };
  5635. Tools.UnregisterTopRootEvents = function (events) {
  5636. for (var index = 0; index < events.length; index++) {
  5637. var event = events[index];
  5638. window.removeEventListener(event.name, event.handler);
  5639. try {
  5640. if (window.parent) {
  5641. window.parent.removeEventListener(event.name, event.handler);
  5642. }
  5643. }
  5644. catch (e) {
  5645. // Silently fails...
  5646. }
  5647. }
  5648. };
  5649. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5650. if (mimeType === void 0) { mimeType = "image/png"; }
  5651. // Read the contents of the framebuffer
  5652. var numberOfChannelsByLine = width * 4;
  5653. var halfHeight = height / 2;
  5654. //Reading datas from WebGL
  5655. var data = engine.readPixels(0, 0, width, height);
  5656. //To flip image on Y axis.
  5657. for (var i = 0; i < halfHeight; i++) {
  5658. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5659. var currentCell = j + i * numberOfChannelsByLine;
  5660. var targetLine = height - i - 1;
  5661. var targetCell = j + targetLine * numberOfChannelsByLine;
  5662. var temp = data[currentCell];
  5663. data[currentCell] = data[targetCell];
  5664. data[targetCell] = temp;
  5665. }
  5666. }
  5667. // Create a 2D canvas to store the result
  5668. if (!screenshotCanvas) {
  5669. screenshotCanvas = document.createElement('canvas');
  5670. }
  5671. screenshotCanvas.width = width;
  5672. screenshotCanvas.height = height;
  5673. var context = screenshotCanvas.getContext('2d');
  5674. // Copy the pixels to a 2D canvas
  5675. var imageData = context.createImageData(width, height);
  5676. var castData = (imageData.data);
  5677. castData.set(data);
  5678. context.putImageData(imageData, 0, 0);
  5679. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5680. };
  5681. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5682. if (mimeType === void 0) { mimeType = "image/png"; }
  5683. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5684. if (successCallback) {
  5685. successCallback(base64Image);
  5686. }
  5687. else {
  5688. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5689. if (("download" in document.createElement("a"))) {
  5690. var a = window.document.createElement("a");
  5691. a.href = base64Image;
  5692. var date = new Date();
  5693. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5694. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5695. window.document.body.appendChild(a);
  5696. a.addEventListener("click", function () {
  5697. a.parentElement.removeChild(a);
  5698. });
  5699. a.click();
  5700. //Or opening a new tab with the image if it is not possible to automatically start download.
  5701. }
  5702. else {
  5703. var newWindow = window.open("");
  5704. var img = newWindow.document.createElement("img");
  5705. img.src = base64Image;
  5706. newWindow.document.body.appendChild(img);
  5707. }
  5708. }
  5709. };
  5710. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5711. if (mimeType === void 0) { mimeType = "image/png"; }
  5712. var width;
  5713. var height;
  5714. // If a precision value is specified
  5715. if (size.precision) {
  5716. width = Math.round(engine.getRenderWidth() * size.precision);
  5717. height = Math.round(width / engine.getAspectRatio(camera));
  5718. }
  5719. else if (size.width && size.height) {
  5720. width = size.width;
  5721. height = size.height;
  5722. }
  5723. else if (size.width && !size.height) {
  5724. width = size.width;
  5725. height = Math.round(width / engine.getAspectRatio(camera));
  5726. }
  5727. else if (size.height && !size.width) {
  5728. height = size.height;
  5729. width = Math.round(height * engine.getAspectRatio(camera));
  5730. }
  5731. else if (!isNaN(size)) {
  5732. height = size;
  5733. width = size;
  5734. }
  5735. else {
  5736. Tools.Error("Invalid 'size' parameter !");
  5737. return;
  5738. }
  5739. if (!screenshotCanvas) {
  5740. screenshotCanvas = document.createElement('canvas');
  5741. }
  5742. screenshotCanvas.width = width;
  5743. screenshotCanvas.height = height;
  5744. var renderContext = screenshotCanvas.getContext("2d");
  5745. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5746. var newWidth = width;
  5747. var newHeight = newWidth / ratio;
  5748. if (newHeight > height) {
  5749. newHeight = height;
  5750. newWidth = newHeight * ratio;
  5751. }
  5752. var offsetX = Math.max(0, width - newWidth) / 2;
  5753. var offsetY = Math.max(0, height - newHeight) / 2;
  5754. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5755. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5756. };
  5757. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5758. if (mimeType === void 0) { mimeType = "image/png"; }
  5759. if (samples === void 0) { samples = 1; }
  5760. var width;
  5761. var height;
  5762. //If a precision value is specified
  5763. if (size.precision) {
  5764. width = Math.round(engine.getRenderWidth() * size.precision);
  5765. height = Math.round(width / engine.getAspectRatio(camera));
  5766. size = { width: width, height: height };
  5767. }
  5768. else if (size.width && size.height) {
  5769. width = size.width;
  5770. height = size.height;
  5771. }
  5772. else if (size.width && !size.height) {
  5773. width = size.width;
  5774. height = Math.round(width / engine.getAspectRatio(camera));
  5775. size = { width: width, height: height };
  5776. }
  5777. else if (size.height && !size.width) {
  5778. height = size.height;
  5779. width = Math.round(height * engine.getAspectRatio(camera));
  5780. size = { width: width, height: height };
  5781. }
  5782. else if (!isNaN(size)) {
  5783. height = size;
  5784. width = size;
  5785. }
  5786. else {
  5787. Tools.Error("Invalid 'size' parameter !");
  5788. return;
  5789. }
  5790. var scene = camera.getScene();
  5791. var previousCamera = null;
  5792. if (scene.activeCamera !== camera) {
  5793. previousCamera = scene.activeCamera;
  5794. scene.activeCamera = camera;
  5795. }
  5796. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5797. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5798. texture.renderList = scene.meshes;
  5799. texture.samples = samples;
  5800. texture.onAfterRenderObservable.add(function () {
  5801. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5802. });
  5803. scene.incrementRenderId();
  5804. scene.resetCachedMaterial();
  5805. texture.render(true);
  5806. texture.dispose();
  5807. if (previousCamera) {
  5808. scene.activeCamera = previousCamera;
  5809. }
  5810. camera.getProjectionMatrix(true); // Force cache refresh;
  5811. };
  5812. // XHR response validator for local file scenario
  5813. Tools.ValidateXHRData = function (xhr, dataType) {
  5814. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5815. if (dataType === void 0) { dataType = 7; }
  5816. try {
  5817. if (dataType & 1) {
  5818. if (xhr.responseText && xhr.responseText.length > 0) {
  5819. return true;
  5820. }
  5821. else if (dataType === 1) {
  5822. return false;
  5823. }
  5824. }
  5825. if (dataType & 2) {
  5826. // Check header width and height since there is no "TGA" magic number
  5827. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5828. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5829. return true;
  5830. }
  5831. else if (dataType === 2) {
  5832. return false;
  5833. }
  5834. }
  5835. if (dataType & 4) {
  5836. // Check for the "DDS" magic number
  5837. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5838. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5839. return true;
  5840. }
  5841. else {
  5842. return false;
  5843. }
  5844. }
  5845. }
  5846. catch (e) {
  5847. // Global protection
  5848. }
  5849. return false;
  5850. };
  5851. /**
  5852. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5853. * Be aware Math.random() could cause collisions, but:
  5854. * "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"
  5855. */
  5856. Tools.RandomId = function () {
  5857. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5858. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5859. return v.toString(16);
  5860. });
  5861. };
  5862. Object.defineProperty(Tools, "NoneLogLevel", {
  5863. get: function () {
  5864. return Tools._NoneLogLevel;
  5865. },
  5866. enumerable: true,
  5867. configurable: true
  5868. });
  5869. Object.defineProperty(Tools, "MessageLogLevel", {
  5870. get: function () {
  5871. return Tools._MessageLogLevel;
  5872. },
  5873. enumerable: true,
  5874. configurable: true
  5875. });
  5876. Object.defineProperty(Tools, "WarningLogLevel", {
  5877. get: function () {
  5878. return Tools._WarningLogLevel;
  5879. },
  5880. enumerable: true,
  5881. configurable: true
  5882. });
  5883. Object.defineProperty(Tools, "ErrorLogLevel", {
  5884. get: function () {
  5885. return Tools._ErrorLogLevel;
  5886. },
  5887. enumerable: true,
  5888. configurable: true
  5889. });
  5890. Object.defineProperty(Tools, "AllLogLevel", {
  5891. get: function () {
  5892. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5893. },
  5894. enumerable: true,
  5895. configurable: true
  5896. });
  5897. Tools._AddLogEntry = function (entry) {
  5898. Tools._LogCache = entry + Tools._LogCache;
  5899. if (Tools.OnNewCacheEntry) {
  5900. Tools.OnNewCacheEntry(entry);
  5901. }
  5902. };
  5903. Tools._FormatMessage = function (message) {
  5904. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5905. var date = new Date();
  5906. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5907. };
  5908. Tools._LogDisabled = function (message) {
  5909. // nothing to do
  5910. };
  5911. Tools._LogEnabled = function (message) {
  5912. var formattedMessage = Tools._FormatMessage(message);
  5913. console.log("BJS - " + formattedMessage);
  5914. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5915. Tools._AddLogEntry(entry);
  5916. };
  5917. Tools._WarnDisabled = function (message) {
  5918. // nothing to do
  5919. };
  5920. Tools._WarnEnabled = function (message) {
  5921. var formattedMessage = Tools._FormatMessage(message);
  5922. console.warn("BJS - " + formattedMessage);
  5923. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5924. Tools._AddLogEntry(entry);
  5925. };
  5926. Tools._ErrorDisabled = function (message) {
  5927. // nothing to do
  5928. };
  5929. Tools._ErrorEnabled = function (message) {
  5930. Tools.errorsCount++;
  5931. var formattedMessage = Tools._FormatMessage(message);
  5932. console.error("BJS - " + formattedMessage);
  5933. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5934. Tools._AddLogEntry(entry);
  5935. };
  5936. Object.defineProperty(Tools, "LogCache", {
  5937. get: function () {
  5938. return Tools._LogCache;
  5939. },
  5940. enumerable: true,
  5941. configurable: true
  5942. });
  5943. Tools.ClearLogCache = function () {
  5944. Tools._LogCache = "";
  5945. Tools.errorsCount = 0;
  5946. };
  5947. Object.defineProperty(Tools, "LogLevels", {
  5948. set: function (level) {
  5949. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5950. Tools.Log = Tools._LogEnabled;
  5951. }
  5952. else {
  5953. Tools.Log = Tools._LogDisabled;
  5954. }
  5955. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5956. Tools.Warn = Tools._WarnEnabled;
  5957. }
  5958. else {
  5959. Tools.Warn = Tools._WarnDisabled;
  5960. }
  5961. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5962. Tools.Error = Tools._ErrorEnabled;
  5963. }
  5964. else {
  5965. Tools.Error = Tools._ErrorDisabled;
  5966. }
  5967. },
  5968. enumerable: true,
  5969. configurable: true
  5970. });
  5971. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5972. get: function () {
  5973. return Tools._PerformanceNoneLogLevel;
  5974. },
  5975. enumerable: true,
  5976. configurable: true
  5977. });
  5978. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5979. get: function () {
  5980. return Tools._PerformanceUserMarkLogLevel;
  5981. },
  5982. enumerable: true,
  5983. configurable: true
  5984. });
  5985. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5986. get: function () {
  5987. return Tools._PerformanceConsoleLogLevel;
  5988. },
  5989. enumerable: true,
  5990. configurable: true
  5991. });
  5992. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5993. set: function (level) {
  5994. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5995. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5996. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5997. return;
  5998. }
  5999. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6000. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6001. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6002. return;
  6003. }
  6004. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6005. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6006. },
  6007. enumerable: true,
  6008. configurable: true
  6009. });
  6010. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6011. };
  6012. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6013. };
  6014. Tools._StartUserMark = function (counterName, condition) {
  6015. if (condition === void 0) { condition = true; }
  6016. if (!condition || !Tools._performance.mark) {
  6017. return;
  6018. }
  6019. Tools._performance.mark(counterName + "-Begin");
  6020. };
  6021. Tools._EndUserMark = function (counterName, condition) {
  6022. if (condition === void 0) { condition = true; }
  6023. if (!condition || !Tools._performance.mark) {
  6024. return;
  6025. }
  6026. Tools._performance.mark(counterName + "-End");
  6027. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6028. };
  6029. Tools._StartPerformanceConsole = function (counterName, condition) {
  6030. if (condition === void 0) { condition = true; }
  6031. if (!condition) {
  6032. return;
  6033. }
  6034. Tools._StartUserMark(counterName, condition);
  6035. if (console.time) {
  6036. console.time(counterName);
  6037. }
  6038. };
  6039. Tools._EndPerformanceConsole = function (counterName, condition) {
  6040. if (condition === void 0) { condition = true; }
  6041. if (!condition) {
  6042. return;
  6043. }
  6044. Tools._EndUserMark(counterName, condition);
  6045. if (console.time) {
  6046. console.timeEnd(counterName);
  6047. }
  6048. };
  6049. Object.defineProperty(Tools, "Now", {
  6050. get: function () {
  6051. if (window.performance && window.performance.now) {
  6052. return window.performance.now();
  6053. }
  6054. return new Date().getTime();
  6055. },
  6056. enumerable: true,
  6057. configurable: true
  6058. });
  6059. /**
  6060. * This method will return the name of the class used to create the instance of the given object.
  6061. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6062. * @param object the object to get the class name from
  6063. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6064. */
  6065. Tools.getClassName = function (object, isType) {
  6066. if (isType === void 0) { isType = false; }
  6067. var name = null;
  6068. if (!isType && object.getClassName) {
  6069. name = object.getClassName();
  6070. }
  6071. else {
  6072. if (object instanceof Object) {
  6073. var classObj = isType ? object : Object.getPrototypeOf(object);
  6074. name = classObj.constructor["__bjsclassName__"];
  6075. }
  6076. if (!name) {
  6077. name = typeof object;
  6078. }
  6079. }
  6080. return name;
  6081. };
  6082. Tools.first = function (array, predicate) {
  6083. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6084. var el = array_1[_i];
  6085. if (predicate(el)) {
  6086. return el;
  6087. }
  6088. }
  6089. };
  6090. /**
  6091. * This method will return the name of the full name of the class, including its owning module (if any).
  6092. * 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).
  6093. * @param object the object to get the class name from
  6094. * @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.
  6095. */
  6096. Tools.getFullClassName = function (object, isType) {
  6097. if (isType === void 0) { isType = false; }
  6098. var className = null;
  6099. var moduleName = null;
  6100. if (!isType && object.getClassName) {
  6101. className = object.getClassName();
  6102. }
  6103. else {
  6104. if (object instanceof Object) {
  6105. var classObj = isType ? object : Object.getPrototypeOf(object);
  6106. className = classObj.constructor["__bjsclassName__"];
  6107. moduleName = classObj.constructor["__bjsmoduleName__"];
  6108. }
  6109. if (!className) {
  6110. className = typeof object;
  6111. }
  6112. }
  6113. if (!className) {
  6114. return null;
  6115. }
  6116. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6117. };
  6118. /**
  6119. * 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.
  6120. * @param array
  6121. */
  6122. Tools.arrayOrStringFeeder = function (array) {
  6123. return function (index) {
  6124. if (index >= array.length) {
  6125. return null;
  6126. }
  6127. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6128. if (val && val.getHashCode) {
  6129. val = val.getHashCode();
  6130. }
  6131. if (typeof val === "string") {
  6132. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6133. }
  6134. return val;
  6135. };
  6136. };
  6137. /**
  6138. * Compute the hashCode of a stream of number
  6139. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6140. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6141. * @return the hash code computed
  6142. */
  6143. Tools.hashCodeFromStream = function (feeder) {
  6144. // Based from here: http://stackoverflow.com/a/7616484/802124
  6145. var hash = 0;
  6146. var index = 0;
  6147. var chr = feeder(index++);
  6148. while (chr != null) {
  6149. hash = ((hash << 5) - hash) + chr;
  6150. hash |= 0; // Convert to 32bit integer
  6151. chr = feeder(index++);
  6152. }
  6153. return hash;
  6154. };
  6155. return Tools;
  6156. }());
  6157. Tools.BaseUrl = "";
  6158. Tools.CorsBehavior = "anonymous";
  6159. Tools.UseFallbackTexture = true;
  6160. // Used in case of a texture loading problem
  6161. 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";
  6162. // Logs
  6163. Tools._NoneLogLevel = 0;
  6164. Tools._MessageLogLevel = 1;
  6165. Tools._WarningLogLevel = 2;
  6166. Tools._ErrorLogLevel = 4;
  6167. Tools._LogCache = "";
  6168. Tools.errorsCount = 0;
  6169. Tools.Log = Tools._LogEnabled;
  6170. Tools.Warn = Tools._WarnEnabled;
  6171. Tools.Error = Tools._ErrorEnabled;
  6172. // Performances
  6173. Tools._PerformanceNoneLogLevel = 0;
  6174. Tools._PerformanceUserMarkLogLevel = 1;
  6175. Tools._PerformanceConsoleLogLevel = 2;
  6176. Tools._performance = window.performance;
  6177. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6178. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6179. BABYLON.Tools = Tools;
  6180. /**
  6181. * This class is used to track a performance counter which is number based.
  6182. * The user has access to many properties which give statistics of different nature
  6183. *
  6184. * The implementer can track two kinds of Performance Counter: time and count
  6185. * 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.
  6186. * 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.
  6187. */
  6188. var PerfCounter = (function () {
  6189. function PerfCounter() {
  6190. this._startMonitoringTime = 0;
  6191. this._min = 0;
  6192. this._max = 0;
  6193. this._average = 0;
  6194. this._lastSecAverage = 0;
  6195. this._current = 0;
  6196. this._totalValueCount = 0;
  6197. this._totalAccumulated = 0;
  6198. this._lastSecAccumulated = 0;
  6199. this._lastSecTime = 0;
  6200. this._lastSecValueCount = 0;
  6201. }
  6202. Object.defineProperty(PerfCounter.prototype, "min", {
  6203. /**
  6204. * Returns the smallest value ever
  6205. */
  6206. get: function () {
  6207. return this._min;
  6208. },
  6209. enumerable: true,
  6210. configurable: true
  6211. });
  6212. Object.defineProperty(PerfCounter.prototype, "max", {
  6213. /**
  6214. * Returns the biggest value ever
  6215. */
  6216. get: function () {
  6217. return this._max;
  6218. },
  6219. enumerable: true,
  6220. configurable: true
  6221. });
  6222. Object.defineProperty(PerfCounter.prototype, "average", {
  6223. /**
  6224. * Returns the average value since the performance counter is running
  6225. */
  6226. get: function () {
  6227. return this._average;
  6228. },
  6229. enumerable: true,
  6230. configurable: true
  6231. });
  6232. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6233. /**
  6234. * Returns the average value of the last second the counter was monitored
  6235. */
  6236. get: function () {
  6237. return this._lastSecAverage;
  6238. },
  6239. enumerable: true,
  6240. configurable: true
  6241. });
  6242. Object.defineProperty(PerfCounter.prototype, "current", {
  6243. /**
  6244. * Returns the current value
  6245. */
  6246. get: function () {
  6247. return this._current;
  6248. },
  6249. enumerable: true,
  6250. configurable: true
  6251. });
  6252. Object.defineProperty(PerfCounter.prototype, "total", {
  6253. get: function () {
  6254. return this._totalAccumulated;
  6255. },
  6256. enumerable: true,
  6257. configurable: true
  6258. });
  6259. /**
  6260. * Call this method to start monitoring a new frame.
  6261. * 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.
  6262. */
  6263. PerfCounter.prototype.fetchNewFrame = function () {
  6264. this._totalValueCount++;
  6265. this._current = 0;
  6266. this._lastSecValueCount++;
  6267. };
  6268. /**
  6269. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6270. * @param newCount the count value to add to the monitored count
  6271. * @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.
  6272. */
  6273. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6274. if (!PerfCounter.Enabled) {
  6275. return;
  6276. }
  6277. this._current += newCount;
  6278. if (fetchResult) {
  6279. this._fetchResult();
  6280. }
  6281. };
  6282. /**
  6283. * Start monitoring this performance counter
  6284. */
  6285. PerfCounter.prototype.beginMonitoring = function () {
  6286. if (!PerfCounter.Enabled) {
  6287. return;
  6288. }
  6289. this._startMonitoringTime = Tools.Now;
  6290. };
  6291. /**
  6292. * Compute the time lapsed since the previous beginMonitoring() call.
  6293. * @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
  6294. */
  6295. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6296. if (newFrame === void 0) { newFrame = true; }
  6297. if (!PerfCounter.Enabled) {
  6298. return;
  6299. }
  6300. if (newFrame) {
  6301. this.fetchNewFrame();
  6302. }
  6303. var currentTime = Tools.Now;
  6304. this._current = currentTime - this._startMonitoringTime;
  6305. if (newFrame) {
  6306. this._fetchResult();
  6307. }
  6308. };
  6309. PerfCounter.prototype._fetchResult = function () {
  6310. this._totalAccumulated += this._current;
  6311. this._lastSecAccumulated += this._current;
  6312. // Min/Max update
  6313. this._min = Math.min(this._min, this._current);
  6314. this._max = Math.max(this._max, this._current);
  6315. this._average = this._totalAccumulated / this._totalValueCount;
  6316. // Reset last sec?
  6317. var now = Tools.Now;
  6318. if ((now - this._lastSecTime) > 1000) {
  6319. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6320. this._lastSecTime = now;
  6321. this._lastSecAccumulated = 0;
  6322. this._lastSecValueCount = 0;
  6323. }
  6324. };
  6325. return PerfCounter;
  6326. }());
  6327. PerfCounter.Enabled = true;
  6328. BABYLON.PerfCounter = PerfCounter;
  6329. /**
  6330. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6331. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6332. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6333. * @param name The name of the class, case should be preserved
  6334. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6335. */
  6336. function className(name, module) {
  6337. return function (target) {
  6338. target["__bjsclassName__"] = name;
  6339. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6340. };
  6341. }
  6342. BABYLON.className = className;
  6343. /**
  6344. * An implementation of a loop for asynchronous functions.
  6345. */
  6346. var AsyncLoop = (function () {
  6347. /**
  6348. * Constroctor.
  6349. * @param iterations the number of iterations.
  6350. * @param _fn the function to run each iteration
  6351. * @param _successCallback the callback that will be called upon succesful execution
  6352. * @param offset starting offset.
  6353. */
  6354. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6355. if (offset === void 0) { offset = 0; }
  6356. this.iterations = iterations;
  6357. this._fn = _fn;
  6358. this._successCallback = _successCallback;
  6359. this.index = offset - 1;
  6360. this._done = false;
  6361. }
  6362. /**
  6363. * Execute the next iteration. Must be called after the last iteration was finished.
  6364. */
  6365. AsyncLoop.prototype.executeNext = function () {
  6366. if (!this._done) {
  6367. if (this.index + 1 < this.iterations) {
  6368. ++this.index;
  6369. this._fn(this);
  6370. }
  6371. else {
  6372. this.breakLoop();
  6373. }
  6374. }
  6375. };
  6376. /**
  6377. * Break the loop and run the success callback.
  6378. */
  6379. AsyncLoop.prototype.breakLoop = function () {
  6380. this._done = true;
  6381. this._successCallback();
  6382. };
  6383. /**
  6384. * Helper function
  6385. */
  6386. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6387. if (offset === void 0) { offset = 0; }
  6388. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6389. loop.executeNext();
  6390. return loop;
  6391. };
  6392. /**
  6393. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6394. * @param iterations total number of iterations
  6395. * @param syncedIterations number of synchronous iterations in each async iteration.
  6396. * @param fn the function to call each iteration.
  6397. * @param callback a success call back that will be called when iterating stops.
  6398. * @param breakFunction a break condition (optional)
  6399. * @param timeout timeout settings for the setTimeout function. default - 0.
  6400. * @constructor
  6401. */
  6402. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6403. if (timeout === void 0) { timeout = 0; }
  6404. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6405. if (breakFunction && breakFunction())
  6406. loop.breakLoop();
  6407. else {
  6408. setTimeout(function () {
  6409. for (var i = 0; i < syncedIterations; ++i) {
  6410. var iteration = (loop.index * syncedIterations) + i;
  6411. if (iteration >= iterations)
  6412. break;
  6413. fn(iteration);
  6414. if (breakFunction && breakFunction()) {
  6415. loop.breakLoop();
  6416. break;
  6417. }
  6418. }
  6419. loop.executeNext();
  6420. }, timeout);
  6421. }
  6422. }, callback);
  6423. };
  6424. return AsyncLoop;
  6425. }());
  6426. BABYLON.AsyncLoop = AsyncLoop;
  6427. })(BABYLON || (BABYLON = {}));
  6428. //# sourceMappingURL=babylon.tools.js.map
  6429. var BABYLON;
  6430. (function (BABYLON) {
  6431. var Internals;
  6432. (function (Internals) {
  6433. var _AlphaState = (function () {
  6434. /**
  6435. * Initializes the state.
  6436. */
  6437. function _AlphaState() {
  6438. this._isAlphaBlendDirty = false;
  6439. this._isBlendFunctionParametersDirty = false;
  6440. this._alphaBlend = false;
  6441. this._blendFunctionParameters = new Array(4);
  6442. this.reset();
  6443. }
  6444. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6445. get: function () {
  6446. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6447. },
  6448. enumerable: true,
  6449. configurable: true
  6450. });
  6451. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6452. get: function () {
  6453. return this._alphaBlend;
  6454. },
  6455. set: function (value) {
  6456. if (this._alphaBlend === value) {
  6457. return;
  6458. }
  6459. this._alphaBlend = value;
  6460. this._isAlphaBlendDirty = true;
  6461. },
  6462. enumerable: true,
  6463. configurable: true
  6464. });
  6465. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6466. if (this._blendFunctionParameters[0] === value0 &&
  6467. this._blendFunctionParameters[1] === value1 &&
  6468. this._blendFunctionParameters[2] === value2 &&
  6469. this._blendFunctionParameters[3] === value3) {
  6470. return;
  6471. }
  6472. this._blendFunctionParameters[0] = value0;
  6473. this._blendFunctionParameters[1] = value1;
  6474. this._blendFunctionParameters[2] = value2;
  6475. this._blendFunctionParameters[3] = value3;
  6476. this._isBlendFunctionParametersDirty = true;
  6477. };
  6478. _AlphaState.prototype.reset = function () {
  6479. this._alphaBlend = false;
  6480. this._blendFunctionParameters[0] = null;
  6481. this._blendFunctionParameters[1] = null;
  6482. this._blendFunctionParameters[2] = null;
  6483. this._blendFunctionParameters[3] = null;
  6484. this._isAlphaBlendDirty = true;
  6485. this._isBlendFunctionParametersDirty = false;
  6486. };
  6487. _AlphaState.prototype.apply = function (gl) {
  6488. if (!this.isDirty) {
  6489. return;
  6490. }
  6491. // Alpha blend
  6492. if (this._isAlphaBlendDirty) {
  6493. if (this._alphaBlend) {
  6494. gl.enable(gl.BLEND);
  6495. }
  6496. else {
  6497. gl.disable(gl.BLEND);
  6498. }
  6499. this._isAlphaBlendDirty = false;
  6500. }
  6501. // Alpha function
  6502. if (this._isBlendFunctionParametersDirty) {
  6503. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6504. this._isBlendFunctionParametersDirty = false;
  6505. }
  6506. };
  6507. return _AlphaState;
  6508. }());
  6509. Internals._AlphaState = _AlphaState;
  6510. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6511. })(BABYLON || (BABYLON = {}));
  6512. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6513. var BABYLON;
  6514. (function (BABYLON) {
  6515. var Internals;
  6516. (function (Internals) {
  6517. var _DepthCullingState = (function () {
  6518. /**
  6519. * Initializes the state.
  6520. */
  6521. function _DepthCullingState() {
  6522. this._isDepthTestDirty = false;
  6523. this._isDepthMaskDirty = false;
  6524. this._isDepthFuncDirty = false;
  6525. this._isCullFaceDirty = false;
  6526. this._isCullDirty = false;
  6527. this._isZOffsetDirty = false;
  6528. this.reset();
  6529. }
  6530. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6531. get: function () {
  6532. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6533. },
  6534. enumerable: true,
  6535. configurable: true
  6536. });
  6537. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6538. get: function () {
  6539. return this._zOffset;
  6540. },
  6541. set: function (value) {
  6542. if (this._zOffset === value) {
  6543. return;
  6544. }
  6545. this._zOffset = value;
  6546. this._isZOffsetDirty = true;
  6547. },
  6548. enumerable: true,
  6549. configurable: true
  6550. });
  6551. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6552. get: function () {
  6553. return this._cullFace;
  6554. },
  6555. set: function (value) {
  6556. if (this._cullFace === value) {
  6557. return;
  6558. }
  6559. this._cullFace = value;
  6560. this._isCullFaceDirty = true;
  6561. },
  6562. enumerable: true,
  6563. configurable: true
  6564. });
  6565. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6566. get: function () {
  6567. return this._cull;
  6568. },
  6569. set: function (value) {
  6570. if (this._cull === value) {
  6571. return;
  6572. }
  6573. this._cull = value;
  6574. this._isCullDirty = true;
  6575. },
  6576. enumerable: true,
  6577. configurable: true
  6578. });
  6579. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6580. get: function () {
  6581. return this._depthFunc;
  6582. },
  6583. set: function (value) {
  6584. if (this._depthFunc === value) {
  6585. return;
  6586. }
  6587. this._depthFunc = value;
  6588. this._isDepthFuncDirty = true;
  6589. },
  6590. enumerable: true,
  6591. configurable: true
  6592. });
  6593. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6594. get: function () {
  6595. return this._depthMask;
  6596. },
  6597. set: function (value) {
  6598. if (this._depthMask === value) {
  6599. return;
  6600. }
  6601. this._depthMask = value;
  6602. this._isDepthMaskDirty = true;
  6603. },
  6604. enumerable: true,
  6605. configurable: true
  6606. });
  6607. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6608. get: function () {
  6609. return this._depthTest;
  6610. },
  6611. set: function (value) {
  6612. if (this._depthTest === value) {
  6613. return;
  6614. }
  6615. this._depthTest = value;
  6616. this._isDepthTestDirty = true;
  6617. },
  6618. enumerable: true,
  6619. configurable: true
  6620. });
  6621. _DepthCullingState.prototype.reset = function () {
  6622. this._depthMask = true;
  6623. this._depthTest = true;
  6624. this._depthFunc = null;
  6625. this._cullFace = null;
  6626. this._cull = null;
  6627. this._zOffset = 0;
  6628. this._isDepthTestDirty = true;
  6629. this._isDepthMaskDirty = true;
  6630. this._isDepthFuncDirty = false;
  6631. this._isCullFaceDirty = false;
  6632. this._isCullDirty = false;
  6633. this._isZOffsetDirty = false;
  6634. };
  6635. _DepthCullingState.prototype.apply = function (gl) {
  6636. if (!this.isDirty) {
  6637. return;
  6638. }
  6639. // Cull
  6640. if (this._isCullDirty) {
  6641. if (this.cull) {
  6642. gl.enable(gl.CULL_FACE);
  6643. }
  6644. else {
  6645. gl.disable(gl.CULL_FACE);
  6646. }
  6647. this._isCullDirty = false;
  6648. }
  6649. // Cull face
  6650. if (this._isCullFaceDirty) {
  6651. gl.cullFace(this.cullFace);
  6652. this._isCullFaceDirty = false;
  6653. }
  6654. // Depth mask
  6655. if (this._isDepthMaskDirty) {
  6656. gl.depthMask(this.depthMask);
  6657. this._isDepthMaskDirty = false;
  6658. }
  6659. // Depth test
  6660. if (this._isDepthTestDirty) {
  6661. if (this.depthTest) {
  6662. gl.enable(gl.DEPTH_TEST);
  6663. }
  6664. else {
  6665. gl.disable(gl.DEPTH_TEST);
  6666. }
  6667. this._isDepthTestDirty = false;
  6668. }
  6669. // Depth func
  6670. if (this._isDepthFuncDirty) {
  6671. gl.depthFunc(this.depthFunc);
  6672. this._isDepthFuncDirty = false;
  6673. }
  6674. // zOffset
  6675. if (this._isZOffsetDirty) {
  6676. if (this.zOffset) {
  6677. gl.enable(gl.POLYGON_OFFSET_FILL);
  6678. gl.polygonOffset(this.zOffset, 0);
  6679. }
  6680. else {
  6681. gl.disable(gl.POLYGON_OFFSET_FILL);
  6682. }
  6683. this._isZOffsetDirty = false;
  6684. }
  6685. };
  6686. return _DepthCullingState;
  6687. }());
  6688. Internals._DepthCullingState = _DepthCullingState;
  6689. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6690. })(BABYLON || (BABYLON = {}));
  6691. //# sourceMappingURL=babylon.depthCullingState.js.map
  6692. var BABYLON;
  6693. (function (BABYLON) {
  6694. var Internals;
  6695. (function (Internals) {
  6696. var _StencilState = (function () {
  6697. function _StencilState() {
  6698. this._isStencilTestDirty = false;
  6699. this._isStencilMaskDirty = false;
  6700. this._isStencilFuncDirty = false;
  6701. this._isStencilOpDirty = false;
  6702. this.reset();
  6703. }
  6704. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6705. get: function () {
  6706. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6707. },
  6708. enumerable: true,
  6709. configurable: true
  6710. });
  6711. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6712. get: function () {
  6713. return this._stencilFunc;
  6714. },
  6715. set: function (value) {
  6716. if (this._stencilFunc === value) {
  6717. return;
  6718. }
  6719. this._stencilFunc = value;
  6720. this._isStencilFuncDirty = true;
  6721. },
  6722. enumerable: true,
  6723. configurable: true
  6724. });
  6725. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6726. get: function () {
  6727. return this._stencilFuncRef;
  6728. },
  6729. set: function (value) {
  6730. if (this._stencilFuncRef === value) {
  6731. return;
  6732. }
  6733. this._stencilFuncRef = value;
  6734. this._isStencilFuncDirty = true;
  6735. },
  6736. enumerable: true,
  6737. configurable: true
  6738. });
  6739. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6740. get: function () {
  6741. return this._stencilFuncMask;
  6742. },
  6743. set: function (value) {
  6744. if (this._stencilFuncMask === value) {
  6745. return;
  6746. }
  6747. this._stencilFuncMask = value;
  6748. this._isStencilFuncDirty = true;
  6749. },
  6750. enumerable: true,
  6751. configurable: true
  6752. });
  6753. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6754. get: function () {
  6755. return this._stencilOpStencilFail;
  6756. },
  6757. set: function (value) {
  6758. if (this._stencilOpStencilFail === value) {
  6759. return;
  6760. }
  6761. this._stencilOpStencilFail = value;
  6762. this._isStencilOpDirty = true;
  6763. },
  6764. enumerable: true,
  6765. configurable: true
  6766. });
  6767. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6768. get: function () {
  6769. return this._stencilOpDepthFail;
  6770. },
  6771. set: function (value) {
  6772. if (this._stencilOpDepthFail === value) {
  6773. return;
  6774. }
  6775. this._stencilOpDepthFail = value;
  6776. this._isStencilOpDirty = true;
  6777. },
  6778. enumerable: true,
  6779. configurable: true
  6780. });
  6781. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6782. get: function () {
  6783. return this._stencilOpStencilDepthPass;
  6784. },
  6785. set: function (value) {
  6786. if (this._stencilOpStencilDepthPass === value) {
  6787. return;
  6788. }
  6789. this._stencilOpStencilDepthPass = value;
  6790. this._isStencilOpDirty = true;
  6791. },
  6792. enumerable: true,
  6793. configurable: true
  6794. });
  6795. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6796. get: function () {
  6797. return this._stencilMask;
  6798. },
  6799. set: function (value) {
  6800. if (this._stencilMask === value) {
  6801. return;
  6802. }
  6803. this._stencilMask = value;
  6804. this._isStencilMaskDirty = true;
  6805. },
  6806. enumerable: true,
  6807. configurable: true
  6808. });
  6809. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6810. get: function () {
  6811. return this._stencilTest;
  6812. },
  6813. set: function (value) {
  6814. if (this._stencilTest === value) {
  6815. return;
  6816. }
  6817. this._stencilTest = value;
  6818. this._isStencilTestDirty = true;
  6819. },
  6820. enumerable: true,
  6821. configurable: true
  6822. });
  6823. _StencilState.prototype.reset = function () {
  6824. this._stencilTest = false;
  6825. this._stencilMask = 0xFF;
  6826. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6827. this._stencilFuncRef = 1;
  6828. this._stencilFuncMask = 0xFF;
  6829. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6830. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6831. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6832. this._isStencilTestDirty = true;
  6833. this._isStencilMaskDirty = true;
  6834. this._isStencilFuncDirty = true;
  6835. this._isStencilOpDirty = true;
  6836. };
  6837. _StencilState.prototype.apply = function (gl) {
  6838. if (!this.isDirty) {
  6839. return;
  6840. }
  6841. // Stencil test
  6842. if (this._isStencilTestDirty) {
  6843. if (this.stencilTest) {
  6844. gl.enable(gl.STENCIL_TEST);
  6845. }
  6846. else {
  6847. gl.disable(gl.STENCIL_TEST);
  6848. }
  6849. this._isStencilTestDirty = false;
  6850. }
  6851. // Stencil mask
  6852. if (this._isStencilMaskDirty) {
  6853. gl.stencilMask(this.stencilMask);
  6854. this._isStencilMaskDirty = false;
  6855. }
  6856. // Stencil func
  6857. if (this._isStencilFuncDirty) {
  6858. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6859. this._isStencilFuncDirty = false;
  6860. }
  6861. // Stencil op
  6862. if (this._isStencilOpDirty) {
  6863. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6864. this._isStencilOpDirty = false;
  6865. }
  6866. };
  6867. return _StencilState;
  6868. }());
  6869. Internals._StencilState = _StencilState;
  6870. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6871. })(BABYLON || (BABYLON = {}));
  6872. //# sourceMappingURL=babylon.stencilState.js.map
  6873. var BABYLON;
  6874. (function (BABYLON) {
  6875. var compileShader = function (gl, source, type, defines, shaderVersion) {
  6876. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6877. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  6878. gl.compileShader(shader);
  6879. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6880. throw new Error(gl.getShaderInfoLog(shader));
  6881. }
  6882. return shader;
  6883. };
  6884. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6885. var magFilter = gl.NEAREST;
  6886. var minFilter = gl.NEAREST;
  6887. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6888. magFilter = gl.LINEAR;
  6889. if (generateMipMaps) {
  6890. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6891. }
  6892. else {
  6893. minFilter = gl.LINEAR;
  6894. }
  6895. }
  6896. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6897. magFilter = gl.LINEAR;
  6898. if (generateMipMaps) {
  6899. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6900. }
  6901. else {
  6902. minFilter = gl.LINEAR;
  6903. }
  6904. }
  6905. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6906. magFilter = gl.NEAREST;
  6907. if (generateMipMaps) {
  6908. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6909. }
  6910. else {
  6911. minFilter = gl.NEAREST;
  6912. }
  6913. }
  6914. return {
  6915. min: minFilter,
  6916. mag: magFilter
  6917. };
  6918. };
  6919. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6920. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6921. var engine = scene.getEngine();
  6922. if (!engine) {
  6923. return;
  6924. }
  6925. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6926. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6927. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6928. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6929. texture._baseWidth = width;
  6930. texture._baseHeight = height;
  6931. texture._width = potWidth;
  6932. texture._height = potHeight;
  6933. texture.isReady = true;
  6934. processFunction(potWidth, potHeight);
  6935. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6936. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6937. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6938. if (!noMipmap && !isCompressed) {
  6939. gl.generateMipmap(gl.TEXTURE_2D);
  6940. }
  6941. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6942. engine.resetTextureCache();
  6943. scene._removePendingData(texture);
  6944. texture.onLoadedCallbacks.forEach(function (callback) {
  6945. callback();
  6946. });
  6947. texture.onLoadedCallbacks = [];
  6948. };
  6949. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6950. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6951. var img;
  6952. var onload = function () {
  6953. loadedImages[index] = img;
  6954. loadedImages._internalCount++;
  6955. scene._removePendingData(img);
  6956. if (loadedImages._internalCount === 6) {
  6957. onfinish(loadedImages);
  6958. }
  6959. };
  6960. var onerror = function () {
  6961. scene._removePendingData(img);
  6962. if (onErrorCallBack) {
  6963. onErrorCallBack();
  6964. }
  6965. };
  6966. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6967. scene._addPendingData(img);
  6968. };
  6969. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6970. if (onError === void 0) { onError = null; }
  6971. var loadedImages = [];
  6972. loadedImages._internalCount = 0;
  6973. for (var index = 0; index < 6; index++) {
  6974. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6975. }
  6976. };
  6977. var InstancingAttributeInfo = (function () {
  6978. function InstancingAttributeInfo() {
  6979. }
  6980. return InstancingAttributeInfo;
  6981. }());
  6982. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6983. var EngineCapabilities = (function () {
  6984. function EngineCapabilities() {
  6985. }
  6986. return EngineCapabilities;
  6987. }());
  6988. BABYLON.EngineCapabilities = EngineCapabilities;
  6989. /**
  6990. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6991. */
  6992. var Engine = (function () {
  6993. /**
  6994. * @constructor
  6995. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6996. * @param {boolean} [antialias] - enable antialias
  6997. * @param options - further options to be sent to the getContext function
  6998. */
  6999. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7000. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7001. var _this = this;
  7002. // Public members
  7003. this.isFullscreen = false;
  7004. this.isPointerLock = false;
  7005. this.cullBackFaces = true;
  7006. this.renderEvenInBackground = true;
  7007. this.preventCacheWipeBetweenFrames = false;
  7008. // To enable/disable IDB support and avoid XHR on .manifest
  7009. this.enableOfflineSupport = BABYLON.Database;
  7010. this.scenes = new Array();
  7011. this._windowIsBackground = false;
  7012. this._webGLVersion = 1.0;
  7013. this._badOS = false;
  7014. this._drawCalls = new BABYLON.PerfCounter();
  7015. this._renderingQueueLaunched = false;
  7016. this._activeRenderLoops = [];
  7017. // FPS
  7018. this.fpsRange = 60;
  7019. this.previousFramesDuration = [];
  7020. this.fps = 60;
  7021. this.deltaTime = 0;
  7022. // States
  7023. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7024. this._stencilState = new BABYLON.Internals._StencilState();
  7025. this._alphaState = new BABYLON.Internals._AlphaState();
  7026. this._alphaMode = Engine.ALPHA_DISABLE;
  7027. // Cache
  7028. this._loadedTexturesCache = new Array();
  7029. this._maxTextureChannels = 16;
  7030. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7031. this._compiledEffects = {};
  7032. this._vertexAttribArraysEnabled = [];
  7033. this._uintIndicesCurrentlySet = false;
  7034. this._currentBoundBuffer = new Array();
  7035. this._currentBufferPointers = [];
  7036. this._currentInstanceLocations = new Array();
  7037. this._currentInstanceBuffers = new Array();
  7038. this._vaoRecordInProgress = false;
  7039. this._mustWipeVertexAttributes = false;
  7040. // Hardware supported Compressed Textures
  7041. this._texturesSupported = new Array();
  7042. this._onVRFullScreenTriggered = function () {
  7043. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7044. //get the old size before we change
  7045. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7046. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7047. //get the width and height, change the render size
  7048. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7049. var width, height;
  7050. _this.setHardwareScalingLevel(1);
  7051. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7052. }
  7053. else {
  7054. //When the specs are implemented, need to uncomment this.
  7055. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7056. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7057. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7058. _this._vrDisplayEnabled = undefined;
  7059. }
  7060. };
  7061. this._renderingCanvas = canvas;
  7062. Engine.Instances.push(this);
  7063. options = options || {};
  7064. if (antialias != null) {
  7065. options.antialias = antialias;
  7066. }
  7067. if (options.preserveDrawingBuffer === undefined) {
  7068. options.preserveDrawingBuffer = false;
  7069. }
  7070. if (options.audioEngine === undefined) {
  7071. options.audioEngine = true;
  7072. }
  7073. if (options.stencil === undefined) {
  7074. options.stencil = true;
  7075. }
  7076. // GL
  7077. if (!options.disableWebGL2Support) {
  7078. try {
  7079. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7080. if (this._gl) {
  7081. this._webGLVersion = 2.0;
  7082. }
  7083. }
  7084. catch (e) {
  7085. // Do nothing
  7086. }
  7087. }
  7088. if (!this._gl) {
  7089. if (!canvas) {
  7090. throw new Error("The provided canvas is null or undefined.");
  7091. }
  7092. try {
  7093. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7094. }
  7095. catch (e) {
  7096. throw new Error("WebGL not supported");
  7097. }
  7098. }
  7099. if (!this._gl) {
  7100. throw new Error("WebGL not supported");
  7101. }
  7102. this._onBlur = function () {
  7103. _this._windowIsBackground = true;
  7104. };
  7105. this._onFocus = function () {
  7106. _this._windowIsBackground = false;
  7107. };
  7108. window.addEventListener("blur", this._onBlur);
  7109. window.addEventListener("focus", this._onFocus);
  7110. // Viewport
  7111. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7112. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7113. this.resize();
  7114. // Caps
  7115. this._isStencilEnable = options.stencil;
  7116. this._caps = new EngineCapabilities();
  7117. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7118. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7119. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7120. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7121. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7122. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7123. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7124. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7125. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7126. // Infos
  7127. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7128. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7129. if (rendererInfo != null) {
  7130. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7131. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7132. }
  7133. if (!this._glVendor) {
  7134. this._glVendor = "Unknown vendor";
  7135. }
  7136. if (!this._glRenderer) {
  7137. this._glRenderer = "Unknown renderer";
  7138. }
  7139. // Extensions
  7140. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7141. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7142. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7143. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7144. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7145. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7146. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7147. 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');
  7148. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7149. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7150. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7151. this._caps.highPrecisionShaderSupported = true;
  7152. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7153. // Checks if some of the format renders first to allow the use of webgl inspector.
  7154. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7155. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7156. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7157. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7158. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7159. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7160. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7161. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7162. // Vertex array object
  7163. if (this._webGLVersion > 1) {
  7164. this._caps.vertexArrayObject = true;
  7165. }
  7166. else {
  7167. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7168. if (vertexArrayObjectExtension != null) {
  7169. this._caps.vertexArrayObject = true;
  7170. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7171. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7172. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7173. }
  7174. else {
  7175. this._caps.vertexArrayObject = false;
  7176. }
  7177. }
  7178. // Instances count
  7179. if (this._webGLVersion > 1) {
  7180. this._caps.instancedArrays = true;
  7181. }
  7182. else {
  7183. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7184. if (instanceExtension != null) {
  7185. this._caps.instancedArrays = true;
  7186. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7187. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7188. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7189. }
  7190. else {
  7191. this._caps.instancedArrays = false;
  7192. }
  7193. }
  7194. // Intelligently add supported compressed formats in order to check for.
  7195. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7196. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7197. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7198. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7199. if (this._caps.astc)
  7200. this.texturesSupported.push('-astc.ktx');
  7201. if (this._caps.s3tc)
  7202. this.texturesSupported.push('-dxt.ktx');
  7203. if (this._caps.pvrtc)
  7204. this.texturesSupported.push('-pvrtc.ktx');
  7205. if (this._caps.etc2)
  7206. this.texturesSupported.push('-etc2.ktx');
  7207. if (this._caps.etc1)
  7208. this.texturesSupported.push('-etc1.ktx');
  7209. if (this._gl.getShaderPrecisionFormat) {
  7210. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7211. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7212. }
  7213. // Depth buffer
  7214. this.setDepthBuffer(true);
  7215. this.setDepthFunctionToLessOrEqual();
  7216. this.setDepthWrite(true);
  7217. // Fullscreen
  7218. this._onFullscreenChange = function () {
  7219. if (document.fullscreen !== undefined) {
  7220. _this.isFullscreen = document.fullscreen;
  7221. }
  7222. else if (document.mozFullScreen !== undefined) {
  7223. _this.isFullscreen = document.mozFullScreen;
  7224. }
  7225. else if (document.webkitIsFullScreen !== undefined) {
  7226. _this.isFullscreen = document.webkitIsFullScreen;
  7227. }
  7228. else if (document.msIsFullScreen !== undefined) {
  7229. _this.isFullscreen = document.msIsFullScreen;
  7230. }
  7231. // Pointer lock
  7232. if (_this.isFullscreen && _this._pointerLockRequested) {
  7233. canvas.requestPointerLock = canvas.requestPointerLock ||
  7234. canvas.msRequestPointerLock ||
  7235. canvas.mozRequestPointerLock ||
  7236. canvas.webkitRequestPointerLock;
  7237. if (canvas.requestPointerLock) {
  7238. canvas.requestPointerLock();
  7239. }
  7240. }
  7241. };
  7242. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7243. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7244. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7245. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7246. // Pointer lock
  7247. this._onPointerLockChange = function () {
  7248. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7249. document.webkitPointerLockElement === canvas ||
  7250. document.msPointerLockElement === canvas ||
  7251. document.pointerLockElement === canvas);
  7252. };
  7253. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7254. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7255. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7256. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7257. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7258. Engine.audioEngine = new BABYLON.AudioEngine();
  7259. }
  7260. //Load WebVR Devices
  7261. if (options.autoEnableWebVR) {
  7262. this.initWebVR();
  7263. }
  7264. //Detect if we are running on a faulty buggy OS.
  7265. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7266. //ua sniffing is the tool of the devil.
  7267. this._badOS = regexp.test(navigator.userAgent);
  7268. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7269. }
  7270. Object.defineProperty(Engine, "LastCreatedEngine", {
  7271. get: function () {
  7272. if (Engine.Instances.length === 0) {
  7273. return null;
  7274. }
  7275. return Engine.Instances[Engine.Instances.length - 1];
  7276. },
  7277. enumerable: true,
  7278. configurable: true
  7279. });
  7280. Object.defineProperty(Engine, "LastCreatedScene", {
  7281. get: function () {
  7282. var lastCreatedEngine = Engine.LastCreatedEngine;
  7283. if (!lastCreatedEngine) {
  7284. return null;
  7285. }
  7286. if (lastCreatedEngine.scenes.length === 0) {
  7287. return null;
  7288. }
  7289. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7290. },
  7291. enumerable: true,
  7292. configurable: true
  7293. });
  7294. /**
  7295. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7296. */
  7297. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7298. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7299. var engine = Engine.Instances[engineIndex];
  7300. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7301. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7302. }
  7303. }
  7304. };
  7305. Object.defineProperty(Engine, "NEVER", {
  7306. get: function () {
  7307. return Engine._NEVER;
  7308. },
  7309. enumerable: true,
  7310. configurable: true
  7311. });
  7312. Object.defineProperty(Engine, "ALWAYS", {
  7313. get: function () {
  7314. return Engine._ALWAYS;
  7315. },
  7316. enumerable: true,
  7317. configurable: true
  7318. });
  7319. Object.defineProperty(Engine, "LESS", {
  7320. get: function () {
  7321. return Engine._LESS;
  7322. },
  7323. enumerable: true,
  7324. configurable: true
  7325. });
  7326. Object.defineProperty(Engine, "EQUAL", {
  7327. get: function () {
  7328. return Engine._EQUAL;
  7329. },
  7330. enumerable: true,
  7331. configurable: true
  7332. });
  7333. Object.defineProperty(Engine, "LEQUAL", {
  7334. get: function () {
  7335. return Engine._LEQUAL;
  7336. },
  7337. enumerable: true,
  7338. configurable: true
  7339. });
  7340. Object.defineProperty(Engine, "GREATER", {
  7341. get: function () {
  7342. return Engine._GREATER;
  7343. },
  7344. enumerable: true,
  7345. configurable: true
  7346. });
  7347. Object.defineProperty(Engine, "GEQUAL", {
  7348. get: function () {
  7349. return Engine._GEQUAL;
  7350. },
  7351. enumerable: true,
  7352. configurable: true
  7353. });
  7354. Object.defineProperty(Engine, "NOTEQUAL", {
  7355. get: function () {
  7356. return Engine._NOTEQUAL;
  7357. },
  7358. enumerable: true,
  7359. configurable: true
  7360. });
  7361. Object.defineProperty(Engine, "KEEP", {
  7362. get: function () {
  7363. return Engine._KEEP;
  7364. },
  7365. enumerable: true,
  7366. configurable: true
  7367. });
  7368. Object.defineProperty(Engine, "REPLACE", {
  7369. get: function () {
  7370. return Engine._REPLACE;
  7371. },
  7372. enumerable: true,
  7373. configurable: true
  7374. });
  7375. Object.defineProperty(Engine, "INCR", {
  7376. get: function () {
  7377. return Engine._INCR;
  7378. },
  7379. enumerable: true,
  7380. configurable: true
  7381. });
  7382. Object.defineProperty(Engine, "DECR", {
  7383. get: function () {
  7384. return Engine._DECR;
  7385. },
  7386. enumerable: true,
  7387. configurable: true
  7388. });
  7389. Object.defineProperty(Engine, "INVERT", {
  7390. get: function () {
  7391. return Engine._INVERT;
  7392. },
  7393. enumerable: true,
  7394. configurable: true
  7395. });
  7396. Object.defineProperty(Engine, "INCR_WRAP", {
  7397. get: function () {
  7398. return Engine._INCR_WRAP;
  7399. },
  7400. enumerable: true,
  7401. configurable: true
  7402. });
  7403. Object.defineProperty(Engine, "DECR_WRAP", {
  7404. get: function () {
  7405. return Engine._DECR_WRAP;
  7406. },
  7407. enumerable: true,
  7408. configurable: true
  7409. });
  7410. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7411. get: function () {
  7412. return Engine._ALPHA_DISABLE;
  7413. },
  7414. enumerable: true,
  7415. configurable: true
  7416. });
  7417. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7418. get: function () {
  7419. return Engine._ALPHA_ONEONE;
  7420. },
  7421. enumerable: true,
  7422. configurable: true
  7423. });
  7424. Object.defineProperty(Engine, "ALPHA_ADD", {
  7425. get: function () {
  7426. return Engine._ALPHA_ADD;
  7427. },
  7428. enumerable: true,
  7429. configurable: true
  7430. });
  7431. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7432. get: function () {
  7433. return Engine._ALPHA_COMBINE;
  7434. },
  7435. enumerable: true,
  7436. configurable: true
  7437. });
  7438. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7439. get: function () {
  7440. return Engine._ALPHA_SUBTRACT;
  7441. },
  7442. enumerable: true,
  7443. configurable: true
  7444. });
  7445. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7446. get: function () {
  7447. return Engine._ALPHA_MULTIPLY;
  7448. },
  7449. enumerable: true,
  7450. configurable: true
  7451. });
  7452. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7453. get: function () {
  7454. return Engine._ALPHA_MAXIMIZED;
  7455. },
  7456. enumerable: true,
  7457. configurable: true
  7458. });
  7459. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7460. get: function () {
  7461. return Engine._ALPHA_PREMULTIPLIED;
  7462. },
  7463. enumerable: true,
  7464. configurable: true
  7465. });
  7466. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7467. get: function () {
  7468. return Engine._DELAYLOADSTATE_NONE;
  7469. },
  7470. enumerable: true,
  7471. configurable: true
  7472. });
  7473. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7474. get: function () {
  7475. return Engine._DELAYLOADSTATE_LOADED;
  7476. },
  7477. enumerable: true,
  7478. configurable: true
  7479. });
  7480. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7481. get: function () {
  7482. return Engine._DELAYLOADSTATE_LOADING;
  7483. },
  7484. enumerable: true,
  7485. configurable: true
  7486. });
  7487. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7488. get: function () {
  7489. return Engine._DELAYLOADSTATE_NOTLOADED;
  7490. },
  7491. enumerable: true,
  7492. configurable: true
  7493. });
  7494. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7495. get: function () {
  7496. return Engine._TEXTUREFORMAT_ALPHA;
  7497. },
  7498. enumerable: true,
  7499. configurable: true
  7500. });
  7501. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7502. get: function () {
  7503. return Engine._TEXTUREFORMAT_LUMINANCE;
  7504. },
  7505. enumerable: true,
  7506. configurable: true
  7507. });
  7508. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7509. get: function () {
  7510. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7511. },
  7512. enumerable: true,
  7513. configurable: true
  7514. });
  7515. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7516. get: function () {
  7517. return Engine._TEXTUREFORMAT_RGB;
  7518. },
  7519. enumerable: true,
  7520. configurable: true
  7521. });
  7522. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7523. get: function () {
  7524. return Engine._TEXTUREFORMAT_RGBA;
  7525. },
  7526. enumerable: true,
  7527. configurable: true
  7528. });
  7529. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7530. get: function () {
  7531. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7532. },
  7533. enumerable: true,
  7534. configurable: true
  7535. });
  7536. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7537. get: function () {
  7538. return Engine._TEXTURETYPE_FLOAT;
  7539. },
  7540. enumerable: true,
  7541. configurable: true
  7542. });
  7543. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7544. get: function () {
  7545. return Engine._TEXTURETYPE_HALF_FLOAT;
  7546. },
  7547. enumerable: true,
  7548. configurable: true
  7549. });
  7550. Object.defineProperty(Engine, "Version", {
  7551. get: function () {
  7552. return "3.0-alpha";
  7553. },
  7554. enumerable: true,
  7555. configurable: true
  7556. });
  7557. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7558. get: function () {
  7559. return this._texturesSupported;
  7560. },
  7561. enumerable: true,
  7562. configurable: true
  7563. });
  7564. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7565. get: function () {
  7566. return this._textureFormatInUse;
  7567. },
  7568. enumerable: true,
  7569. configurable: true
  7570. });
  7571. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7572. get: function () {
  7573. return this._webGLVersion;
  7574. },
  7575. enumerable: true,
  7576. configurable: true
  7577. });
  7578. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7579. /**
  7580. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7581. */
  7582. get: function () {
  7583. return this._isStencilEnable;
  7584. },
  7585. enumerable: true,
  7586. configurable: true
  7587. });
  7588. Engine.prototype._prepareWorkingCanvas = function () {
  7589. if (this._workingCanvas) {
  7590. return;
  7591. }
  7592. this._workingCanvas = document.createElement("canvas");
  7593. this._workingContext = this._workingCanvas.getContext("2d");
  7594. };
  7595. Engine.prototype.resetTextureCache = function () {
  7596. for (var index = 0; index < this._maxTextureChannels; index++) {
  7597. this._activeTexturesCache[index] = null;
  7598. }
  7599. };
  7600. Engine.prototype.getGlInfo = function () {
  7601. return {
  7602. vendor: this._glVendor,
  7603. renderer: this._glRenderer,
  7604. version: this._glVersion
  7605. };
  7606. };
  7607. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7608. if (useScreen === void 0) { useScreen = false; }
  7609. var viewport = camera.viewport;
  7610. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7611. };
  7612. Engine.prototype.getRenderWidth = function (useScreen) {
  7613. if (useScreen === void 0) { useScreen = false; }
  7614. if (!useScreen && this._currentRenderTarget) {
  7615. return this._currentRenderTarget._width;
  7616. }
  7617. return this._renderingCanvas.width;
  7618. };
  7619. Engine.prototype.getRenderHeight = function (useScreen) {
  7620. if (useScreen === void 0) { useScreen = false; }
  7621. if (!useScreen && this._currentRenderTarget) {
  7622. return this._currentRenderTarget._height;
  7623. }
  7624. return this._renderingCanvas.height;
  7625. };
  7626. Engine.prototype.getRenderingCanvas = function () {
  7627. return this._renderingCanvas;
  7628. };
  7629. Engine.prototype.getRenderingCanvasClientRect = function () {
  7630. return this._renderingCanvas.getBoundingClientRect();
  7631. };
  7632. Engine.prototype.setHardwareScalingLevel = function (level) {
  7633. this._hardwareScalingLevel = level;
  7634. this.resize();
  7635. };
  7636. Engine.prototype.getHardwareScalingLevel = function () {
  7637. return this._hardwareScalingLevel;
  7638. };
  7639. Engine.prototype.getLoadedTexturesCache = function () {
  7640. return this._loadedTexturesCache;
  7641. };
  7642. Engine.prototype.getCaps = function () {
  7643. return this._caps;
  7644. };
  7645. Object.defineProperty(Engine.prototype, "drawCalls", {
  7646. get: function () {
  7647. return this._drawCalls.current;
  7648. },
  7649. enumerable: true,
  7650. configurable: true
  7651. });
  7652. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7653. get: function () {
  7654. return this._drawCalls;
  7655. },
  7656. enumerable: true,
  7657. configurable: true
  7658. });
  7659. Engine.prototype.getDepthFunction = function () {
  7660. return this._depthCullingState.depthFunc;
  7661. };
  7662. Engine.prototype.setDepthFunction = function (depthFunc) {
  7663. this._depthCullingState.depthFunc = depthFunc;
  7664. };
  7665. Engine.prototype.setDepthFunctionToGreater = function () {
  7666. this._depthCullingState.depthFunc = this._gl.GREATER;
  7667. };
  7668. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7669. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7670. };
  7671. Engine.prototype.setDepthFunctionToLess = function () {
  7672. this._depthCullingState.depthFunc = this._gl.LESS;
  7673. };
  7674. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7675. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7676. };
  7677. Engine.prototype.getStencilBuffer = function () {
  7678. return this._stencilState.stencilTest;
  7679. };
  7680. Engine.prototype.setStencilBuffer = function (enable) {
  7681. this._stencilState.stencilTest = enable;
  7682. };
  7683. Engine.prototype.getStencilMask = function () {
  7684. return this._stencilState.stencilMask;
  7685. };
  7686. Engine.prototype.setStencilMask = function (mask) {
  7687. this._stencilState.stencilMask = mask;
  7688. };
  7689. Engine.prototype.getStencilFunction = function () {
  7690. return this._stencilState.stencilFunc;
  7691. };
  7692. Engine.prototype.getStencilFunctionReference = function () {
  7693. return this._stencilState.stencilFuncRef;
  7694. };
  7695. Engine.prototype.getStencilFunctionMask = function () {
  7696. return this._stencilState.stencilFuncMask;
  7697. };
  7698. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7699. this._stencilState.stencilFunc = stencilFunc;
  7700. };
  7701. Engine.prototype.setStencilFunctionReference = function (reference) {
  7702. this._stencilState.stencilFuncRef = reference;
  7703. };
  7704. Engine.prototype.setStencilFunctionMask = function (mask) {
  7705. this._stencilState.stencilFuncMask = mask;
  7706. };
  7707. Engine.prototype.getStencilOperationFail = function () {
  7708. return this._stencilState.stencilOpStencilFail;
  7709. };
  7710. Engine.prototype.getStencilOperationDepthFail = function () {
  7711. return this._stencilState.stencilOpDepthFail;
  7712. };
  7713. Engine.prototype.getStencilOperationPass = function () {
  7714. return this._stencilState.stencilOpStencilDepthPass;
  7715. };
  7716. Engine.prototype.setStencilOperationFail = function (operation) {
  7717. this._stencilState.stencilOpStencilFail = operation;
  7718. };
  7719. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7720. this._stencilState.stencilOpDepthFail = operation;
  7721. };
  7722. Engine.prototype.setStencilOperationPass = function (operation) {
  7723. this._stencilState.stencilOpStencilDepthPass = operation;
  7724. };
  7725. /**
  7726. * stop executing a render loop function and remove it from the execution array
  7727. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7728. */
  7729. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7730. if (!renderFunction) {
  7731. this._activeRenderLoops = [];
  7732. return;
  7733. }
  7734. var index = this._activeRenderLoops.indexOf(renderFunction);
  7735. if (index >= 0) {
  7736. this._activeRenderLoops.splice(index, 1);
  7737. }
  7738. };
  7739. Engine.prototype._renderLoop = function () {
  7740. var shouldRender = true;
  7741. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7742. shouldRender = false;
  7743. }
  7744. if (shouldRender) {
  7745. // Start new frame
  7746. this.beginFrame();
  7747. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7748. var renderFunction = this._activeRenderLoops[index];
  7749. renderFunction();
  7750. }
  7751. // Present
  7752. this.endFrame();
  7753. }
  7754. if (this._activeRenderLoops.length > 0) {
  7755. // Register new frame
  7756. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7757. }
  7758. else {
  7759. this._renderingQueueLaunched = false;
  7760. }
  7761. };
  7762. /**
  7763. * Register and execute a render loop. The engine can have more than one render function.
  7764. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7765. * @example
  7766. * engine.runRenderLoop(function () {
  7767. * scene.render()
  7768. * })
  7769. */
  7770. Engine.prototype.runRenderLoop = function (renderFunction) {
  7771. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7772. return;
  7773. }
  7774. this._activeRenderLoops.push(renderFunction);
  7775. if (!this._renderingQueueLaunched) {
  7776. this._renderingQueueLaunched = true;
  7777. this._bindedRenderFunction = this._renderLoop.bind(this);
  7778. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7779. }
  7780. };
  7781. /**
  7782. * Toggle full screen mode.
  7783. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7784. * @param {any} options - an options object to be sent to the requestFullscreen function
  7785. */
  7786. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7787. if (this.isFullscreen) {
  7788. BABYLON.Tools.ExitFullscreen();
  7789. }
  7790. else {
  7791. this._pointerLockRequested = requestPointerLock;
  7792. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7793. }
  7794. };
  7795. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7796. if (stencil === void 0) { stencil = false; }
  7797. this.applyStates();
  7798. var mode = 0;
  7799. if (backBuffer && color) {
  7800. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7801. mode |= this._gl.COLOR_BUFFER_BIT;
  7802. }
  7803. if (depth) {
  7804. this._gl.clearDepth(1.0);
  7805. mode |= this._gl.DEPTH_BUFFER_BIT;
  7806. }
  7807. if (stencil) {
  7808. this._gl.clearStencil(0);
  7809. mode |= this._gl.STENCIL_BUFFER_BIT;
  7810. }
  7811. this._gl.clear(mode);
  7812. };
  7813. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7814. var gl = this._gl;
  7815. // Save state
  7816. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7817. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7818. // Change state
  7819. gl.enable(gl.SCISSOR_TEST);
  7820. gl.scissor(x, y, width, height);
  7821. // Clear
  7822. this.clear(clearColor, true, true, true);
  7823. // Restore state
  7824. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7825. if (curScissor === true) {
  7826. gl.enable(gl.SCISSOR_TEST);
  7827. }
  7828. else {
  7829. gl.disable(gl.SCISSOR_TEST);
  7830. }
  7831. };
  7832. /**
  7833. * Set the WebGL's viewport
  7834. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7835. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7836. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7837. */
  7838. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7839. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7840. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7841. var x = viewport.x || 0;
  7842. var y = viewport.y || 0;
  7843. this._cachedViewport = viewport;
  7844. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7845. };
  7846. /**
  7847. * Directly set the WebGL Viewport
  7848. * The x, y, width & height are directly passed to the WebGL call
  7849. * @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.
  7850. */
  7851. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7852. var currentViewport = this._cachedViewport;
  7853. this._cachedViewport = null;
  7854. this._gl.viewport(x, y, width, height);
  7855. return currentViewport;
  7856. };
  7857. Engine.prototype.beginFrame = function () {
  7858. this._measureFps();
  7859. };
  7860. Engine.prototype.endFrame = function () {
  7861. //force a flush in case we are using a bad OS.
  7862. if (this._badOS) {
  7863. this.flushFramebuffer();
  7864. }
  7865. //submit frame to the vr device, if enabled
  7866. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7867. this._vrDisplayEnabled.submitFrame();
  7868. }
  7869. };
  7870. /**
  7871. * resize the view according to the canvas' size.
  7872. * @example
  7873. * window.addEventListener("resize", function () {
  7874. * engine.resize();
  7875. * });
  7876. */
  7877. Engine.prototype.resize = function () {
  7878. // We're not resizing the size of the canvas while in VR mode & presenting
  7879. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  7880. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7881. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7882. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7883. }
  7884. };
  7885. /**
  7886. * force a specific size of the canvas
  7887. * @param {number} width - the new canvas' width
  7888. * @param {number} height - the new canvas' height
  7889. */
  7890. Engine.prototype.setSize = function (width, height) {
  7891. this._renderingCanvas.width = width;
  7892. this._renderingCanvas.height = height;
  7893. for (var index = 0; index < this.scenes.length; index++) {
  7894. var scene = this.scenes[index];
  7895. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7896. var cam = scene.cameras[camIndex];
  7897. cam._currentRenderId = 0;
  7898. }
  7899. }
  7900. };
  7901. //WebVR functions
  7902. Engine.prototype.initWebVR = function () {
  7903. if (!this.vrDisplaysPromise) {
  7904. this._getVRDisplays();
  7905. }
  7906. };
  7907. Engine.prototype.enableVR = function (vrDevice) {
  7908. this._vrDisplayEnabled = vrDevice;
  7909. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7910. };
  7911. Engine.prototype.disableVR = function () {
  7912. if (this._vrDisplayEnabled) {
  7913. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7914. }
  7915. };
  7916. Engine.prototype._getVRDisplays = function () {
  7917. var _this = this;
  7918. var getWebVRDevices = function (devices) {
  7919. var size = devices.length;
  7920. var i = 0;
  7921. _this._vrDisplays = devices.filter(function (device) {
  7922. return devices[i] instanceof VRDisplay;
  7923. });
  7924. return _this._vrDisplays;
  7925. };
  7926. //using a key due to typescript
  7927. if (navigator.getVRDisplays) {
  7928. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7929. }
  7930. };
  7931. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7932. this._currentRenderTarget = texture;
  7933. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  7934. var gl = this._gl;
  7935. if (texture.isCube) {
  7936. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7937. }
  7938. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7939. this.wipeCaches();
  7940. };
  7941. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7942. if (this._currentFramebuffer !== framebuffer) {
  7943. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7944. this._currentFramebuffer = framebuffer;
  7945. }
  7946. };
  7947. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  7948. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7949. this._currentRenderTarget = null;
  7950. // If MSAA, we need to bitblt back to main texture
  7951. var gl = this._gl;
  7952. if (texture._MSAAFramebuffer) {
  7953. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  7954. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  7955. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  7956. }
  7957. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7958. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7959. gl.generateMipmap(gl.TEXTURE_2D);
  7960. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7961. }
  7962. if (onBeforeUnbind) {
  7963. if (texture._MSAAFramebuffer) {
  7964. // Bind the correct framebuffer
  7965. this.bindUnboundFramebuffer(texture._framebuffer);
  7966. }
  7967. onBeforeUnbind();
  7968. }
  7969. this.bindUnboundFramebuffer(null);
  7970. };
  7971. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7972. if (texture.generateMipMaps) {
  7973. var gl = this._gl;
  7974. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7975. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7976. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7977. }
  7978. };
  7979. Engine.prototype.flushFramebuffer = function () {
  7980. this._gl.flush();
  7981. };
  7982. Engine.prototype.restoreDefaultFramebuffer = function () {
  7983. this._currentRenderTarget = null;
  7984. this.bindUnboundFramebuffer(null);
  7985. this.setViewport(this._cachedViewport);
  7986. this.wipeCaches();
  7987. };
  7988. // VBOs
  7989. Engine.prototype._resetVertexBufferBinding = function () {
  7990. this.bindArrayBuffer(null);
  7991. this._cachedVertexBuffers = null;
  7992. };
  7993. Engine.prototype.createVertexBuffer = function (vertices) {
  7994. var vbo = this._gl.createBuffer();
  7995. this.bindArrayBuffer(vbo);
  7996. if (vertices instanceof Float32Array) {
  7997. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7998. }
  7999. else {
  8000. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8001. }
  8002. this._resetVertexBufferBinding();
  8003. vbo.references = 1;
  8004. return vbo;
  8005. };
  8006. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8007. var vbo = this._gl.createBuffer();
  8008. this.bindArrayBuffer(vbo);
  8009. if (vertices instanceof Float32Array) {
  8010. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8011. }
  8012. else {
  8013. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8014. }
  8015. this._resetVertexBufferBinding();
  8016. vbo.references = 1;
  8017. return vbo;
  8018. };
  8019. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8020. this.bindArrayBuffer(vertexBuffer);
  8021. if (offset === undefined) {
  8022. offset = 0;
  8023. }
  8024. if (count === undefined) {
  8025. if (vertices instanceof Float32Array) {
  8026. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8027. }
  8028. else {
  8029. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8030. }
  8031. }
  8032. else {
  8033. if (vertices instanceof Float32Array) {
  8034. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8035. }
  8036. else {
  8037. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8038. }
  8039. }
  8040. this._resetVertexBufferBinding();
  8041. };
  8042. Engine.prototype._resetIndexBufferBinding = function () {
  8043. this.bindIndexBuffer(null);
  8044. this._cachedIndexBuffer = null;
  8045. };
  8046. Engine.prototype.createIndexBuffer = function (indices) {
  8047. var vbo = this._gl.createBuffer();
  8048. this.bindIndexBuffer(vbo);
  8049. // Check for 32 bits indices
  8050. var arrayBuffer;
  8051. var need32Bits = false;
  8052. if (indices instanceof Uint16Array) {
  8053. arrayBuffer = indices;
  8054. }
  8055. else {
  8056. //check 32 bit support
  8057. if (this._caps.uintIndices) {
  8058. if (indices instanceof Uint32Array) {
  8059. arrayBuffer = indices;
  8060. need32Bits = true;
  8061. }
  8062. else {
  8063. //number[] or Int32Array, check if 32 bit is necessary
  8064. for (var index = 0; index < indices.length; index++) {
  8065. if (indices[index] > 65535) {
  8066. need32Bits = true;
  8067. break;
  8068. }
  8069. }
  8070. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8071. }
  8072. }
  8073. else {
  8074. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8075. arrayBuffer = new Uint16Array(indices);
  8076. }
  8077. }
  8078. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8079. this._resetIndexBufferBinding();
  8080. vbo.references = 1;
  8081. vbo.is32Bits = need32Bits;
  8082. return vbo;
  8083. };
  8084. Engine.prototype.bindArrayBuffer = function (buffer) {
  8085. if (!this._vaoRecordInProgress) {
  8086. this._unBindVertexArrayObject();
  8087. }
  8088. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8089. };
  8090. Engine.prototype.bindIndexBuffer = function (buffer) {
  8091. if (!this._vaoRecordInProgress) {
  8092. this._unBindVertexArrayObject();
  8093. }
  8094. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8095. };
  8096. Engine.prototype.bindBuffer = function (buffer, target) {
  8097. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8098. this._gl.bindBuffer(target, buffer);
  8099. this._currentBoundBuffer[target] = buffer;
  8100. }
  8101. };
  8102. Engine.prototype.updateArrayBuffer = function (data) {
  8103. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8104. };
  8105. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8106. var pointer = this._currentBufferPointers[indx];
  8107. var changed = false;
  8108. if (!pointer) {
  8109. changed = true;
  8110. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8111. }
  8112. else {
  8113. if (pointer.buffer !== buffer) {
  8114. pointer.buffer = buffer;
  8115. changed = true;
  8116. }
  8117. if (pointer.size !== size) {
  8118. pointer.size = size;
  8119. changed = true;
  8120. }
  8121. if (pointer.type !== type) {
  8122. pointer.type = type;
  8123. changed = true;
  8124. }
  8125. if (pointer.normalized !== normalized) {
  8126. pointer.normalized = normalized;
  8127. changed = true;
  8128. }
  8129. if (pointer.stride !== stride) {
  8130. pointer.stride = stride;
  8131. changed = true;
  8132. }
  8133. if (pointer.offset !== offset) {
  8134. pointer.offset = offset;
  8135. changed = true;
  8136. }
  8137. }
  8138. if (changed || this._vaoRecordInProgress) {
  8139. this.bindArrayBuffer(buffer);
  8140. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8141. }
  8142. };
  8143. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8144. if (indexBuffer == null) {
  8145. return;
  8146. }
  8147. if (this._cachedIndexBuffer !== indexBuffer) {
  8148. this._cachedIndexBuffer = indexBuffer;
  8149. this.bindIndexBuffer(indexBuffer);
  8150. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8151. }
  8152. };
  8153. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8154. var attributes = effect.getAttributesNames();
  8155. if (!this._vaoRecordInProgress) {
  8156. this._unBindVertexArrayObject();
  8157. }
  8158. this.unbindAllAttributes();
  8159. for (var index = 0; index < attributes.length; index++) {
  8160. var order = effect.getAttributeLocation(index);
  8161. if (order >= 0) {
  8162. var vertexBuffer = vertexBuffers[attributes[index]];
  8163. if (!vertexBuffer) {
  8164. continue;
  8165. }
  8166. this._gl.enableVertexAttribArray(order);
  8167. if (!this._vaoRecordInProgress) {
  8168. this._vertexAttribArraysEnabled[order] = true;
  8169. }
  8170. var buffer = vertexBuffer.getBuffer();
  8171. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8172. if (vertexBuffer.getIsInstanced()) {
  8173. this._gl.vertexAttribDivisor(order, 1);
  8174. if (!this._vaoRecordInProgress) {
  8175. this._currentInstanceLocations.push(order);
  8176. this._currentInstanceBuffers.push(buffer);
  8177. }
  8178. }
  8179. }
  8180. }
  8181. };
  8182. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8183. var vao = this._gl.createVertexArray();
  8184. this._vaoRecordInProgress = true;
  8185. this._gl.bindVertexArray(vao);
  8186. this._mustWipeVertexAttributes = true;
  8187. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8188. this.bindIndexBuffer(indexBuffer);
  8189. this._vaoRecordInProgress = false;
  8190. this._gl.bindVertexArray(null);
  8191. return vao;
  8192. };
  8193. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8194. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8195. this._cachedVertexArrayObject = vertexArrayObject;
  8196. this._gl.bindVertexArray(vertexArrayObject);
  8197. this._cachedVertexBuffers = null;
  8198. this._cachedIndexBuffer = null;
  8199. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8200. this._mustWipeVertexAttributes = true;
  8201. }
  8202. };
  8203. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8204. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8205. this._cachedVertexBuffers = vertexBuffer;
  8206. this._cachedEffectForVertexBuffers = effect;
  8207. var attributesCount = effect.getAttributesCount();
  8208. this._unBindVertexArrayObject();
  8209. this.unbindAllAttributes();
  8210. var offset = 0;
  8211. for (var index = 0; index < attributesCount; index++) {
  8212. if (index < vertexDeclaration.length) {
  8213. var order = effect.getAttributeLocation(index);
  8214. if (order >= 0) {
  8215. this._gl.enableVertexAttribArray(order);
  8216. this._vertexAttribArraysEnabled[order] = true;
  8217. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8218. }
  8219. offset += vertexDeclaration[index] * 4;
  8220. }
  8221. }
  8222. }
  8223. this._bindIndexBufferWithCache(indexBuffer);
  8224. };
  8225. Engine.prototype._unBindVertexArrayObject = function () {
  8226. if (!this._cachedVertexArrayObject) {
  8227. return;
  8228. }
  8229. this._cachedVertexArrayObject = null;
  8230. this._gl.bindVertexArray(null);
  8231. };
  8232. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8233. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8234. this._cachedVertexBuffers = vertexBuffers;
  8235. this._cachedEffectForVertexBuffers = effect;
  8236. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8237. }
  8238. this._bindIndexBufferWithCache(indexBuffer);
  8239. };
  8240. Engine.prototype.unbindInstanceAttributes = function () {
  8241. var boundBuffer;
  8242. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8243. var instancesBuffer = this._currentInstanceBuffers[i];
  8244. if (boundBuffer != instancesBuffer) {
  8245. boundBuffer = instancesBuffer;
  8246. this.bindArrayBuffer(instancesBuffer);
  8247. }
  8248. var offsetLocation = this._currentInstanceLocations[i];
  8249. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8250. }
  8251. this._currentInstanceBuffers.length = 0;
  8252. this._currentInstanceLocations.length = 0;
  8253. };
  8254. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8255. this._gl.deleteVertexArray(vao);
  8256. };
  8257. Engine.prototype._releaseBuffer = function (buffer) {
  8258. buffer.references--;
  8259. if (buffer.references === 0) {
  8260. this._gl.deleteBuffer(buffer);
  8261. return true;
  8262. }
  8263. return false;
  8264. };
  8265. Engine.prototype.createInstancesBuffer = function (capacity) {
  8266. var buffer = this._gl.createBuffer();
  8267. buffer.capacity = capacity;
  8268. this.bindArrayBuffer(buffer);
  8269. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8270. return buffer;
  8271. };
  8272. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8273. this._gl.deleteBuffer(buffer);
  8274. };
  8275. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8276. this.bindArrayBuffer(instancesBuffer);
  8277. if (data) {
  8278. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8279. }
  8280. if (offsetLocations[0].index !== undefined) {
  8281. var stride = 0;
  8282. for (var i = 0; i < offsetLocations.length; i++) {
  8283. var ai = offsetLocations[i];
  8284. stride += ai.attributeSize * 4;
  8285. }
  8286. for (var i = 0; i < offsetLocations.length; i++) {
  8287. var ai = offsetLocations[i];
  8288. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8289. this._gl.enableVertexAttribArray(ai.index);
  8290. this._vertexAttribArraysEnabled[ai.index] = true;
  8291. }
  8292. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8293. this._gl.vertexAttribDivisor(ai.index, 1);
  8294. this._currentInstanceLocations.push(ai.index);
  8295. this._currentInstanceBuffers.push(instancesBuffer);
  8296. }
  8297. }
  8298. else {
  8299. for (var index = 0; index < 4; index++) {
  8300. var offsetLocation = offsetLocations[index];
  8301. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8302. this._gl.enableVertexAttribArray(offsetLocation);
  8303. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8304. }
  8305. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8306. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8307. this._currentInstanceLocations.push(offsetLocation);
  8308. this._currentInstanceBuffers.push(instancesBuffer);
  8309. }
  8310. }
  8311. };
  8312. Engine.prototype.applyStates = function () {
  8313. this._depthCullingState.apply(this._gl);
  8314. this._stencilState.apply(this._gl);
  8315. this._alphaState.apply(this._gl);
  8316. };
  8317. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8318. // Apply states
  8319. this.applyStates();
  8320. this._drawCalls.addCount(1, false);
  8321. // Render
  8322. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8323. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8324. if (instancesCount) {
  8325. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8326. return;
  8327. }
  8328. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8329. };
  8330. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8331. // Apply states
  8332. this.applyStates();
  8333. this._drawCalls.addCount(1, false);
  8334. if (instancesCount) {
  8335. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8336. return;
  8337. }
  8338. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8339. };
  8340. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8341. // Apply states
  8342. this.applyStates();
  8343. this._drawCalls.addCount(1, false);
  8344. if (instancesCount) {
  8345. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8346. return;
  8347. }
  8348. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8349. };
  8350. // Shaders
  8351. Engine.prototype._releaseEffect = function (effect) {
  8352. if (this._compiledEffects[effect._key]) {
  8353. delete this._compiledEffects[effect._key];
  8354. if (effect.getProgram()) {
  8355. this._gl.deleteProgram(effect.getProgram());
  8356. }
  8357. }
  8358. };
  8359. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8360. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8361. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8362. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8363. if (this._compiledEffects[name]) {
  8364. return this._compiledEffects[name];
  8365. }
  8366. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8367. effect._key = name;
  8368. this._compiledEffects[name] = effect;
  8369. return effect;
  8370. };
  8371. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8372. if (uniformsNames === void 0) { uniformsNames = []; }
  8373. if (samplers === void 0) { samplers = []; }
  8374. if (defines === void 0) { defines = ""; }
  8375. return this.createEffect({
  8376. vertex: "particles",
  8377. fragmentElement: fragmentName
  8378. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8379. };
  8380. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8381. context = context || this._gl;
  8382. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8383. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8384. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8385. var shaderProgram = context.createProgram();
  8386. context.attachShader(shaderProgram, vertexShader);
  8387. context.attachShader(shaderProgram, fragmentShader);
  8388. context.linkProgram(shaderProgram);
  8389. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8390. if (!linked) {
  8391. var error = context.getProgramInfoLog(shaderProgram);
  8392. if (error) {
  8393. throw new Error(error);
  8394. }
  8395. }
  8396. context.deleteShader(vertexShader);
  8397. context.deleteShader(fragmentShader);
  8398. return shaderProgram;
  8399. };
  8400. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8401. var results = [];
  8402. for (var index = 0; index < uniformsNames.length; index++) {
  8403. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8404. }
  8405. return results;
  8406. };
  8407. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8408. var results = [];
  8409. for (var index = 0; index < attributesNames.length; index++) {
  8410. try {
  8411. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8412. }
  8413. catch (e) {
  8414. results.push(-1);
  8415. }
  8416. }
  8417. return results;
  8418. };
  8419. Engine.prototype.enableEffect = function (effect) {
  8420. // Use program
  8421. this.setProgram(effect.getProgram());
  8422. this._currentEffect = effect;
  8423. if (effect.onBind) {
  8424. effect.onBind(effect);
  8425. }
  8426. };
  8427. Engine.prototype.setIntArray = function (uniform, array) {
  8428. if (!uniform)
  8429. return;
  8430. this._gl.uniform1iv(uniform, array);
  8431. };
  8432. Engine.prototype.setIntArray2 = function (uniform, array) {
  8433. if (!uniform || array.length % 2 !== 0)
  8434. return;
  8435. this._gl.uniform2iv(uniform, array);
  8436. };
  8437. Engine.prototype.setIntArray3 = function (uniform, array) {
  8438. if (!uniform || array.length % 3 !== 0)
  8439. return;
  8440. this._gl.uniform3iv(uniform, array);
  8441. };
  8442. Engine.prototype.setIntArray4 = function (uniform, array) {
  8443. if (!uniform || array.length % 4 !== 0)
  8444. return;
  8445. this._gl.uniform4iv(uniform, array);
  8446. };
  8447. Engine.prototype.setFloatArray = function (uniform, array) {
  8448. if (!uniform)
  8449. return;
  8450. this._gl.uniform1fv(uniform, array);
  8451. };
  8452. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8453. if (!uniform || array.length % 2 !== 0)
  8454. return;
  8455. this._gl.uniform2fv(uniform, array);
  8456. };
  8457. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8458. if (!uniform || array.length % 3 !== 0)
  8459. return;
  8460. this._gl.uniform3fv(uniform, array);
  8461. };
  8462. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8463. if (!uniform || array.length % 4 !== 0)
  8464. return;
  8465. this._gl.uniform4fv(uniform, array);
  8466. };
  8467. Engine.prototype.setArray = function (uniform, array) {
  8468. if (!uniform)
  8469. return;
  8470. this._gl.uniform1fv(uniform, array);
  8471. };
  8472. Engine.prototype.setArray2 = function (uniform, array) {
  8473. if (!uniform || array.length % 2 !== 0)
  8474. return;
  8475. this._gl.uniform2fv(uniform, array);
  8476. };
  8477. Engine.prototype.setArray3 = function (uniform, array) {
  8478. if (!uniform || array.length % 3 !== 0)
  8479. return;
  8480. this._gl.uniform3fv(uniform, array);
  8481. };
  8482. Engine.prototype.setArray4 = function (uniform, array) {
  8483. if (!uniform || array.length % 4 !== 0)
  8484. return;
  8485. this._gl.uniform4fv(uniform, array);
  8486. };
  8487. Engine.prototype.setMatrices = function (uniform, matrices) {
  8488. if (!uniform)
  8489. return;
  8490. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8491. };
  8492. Engine.prototype.setMatrix = function (uniform, matrix) {
  8493. if (!uniform)
  8494. return;
  8495. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8496. };
  8497. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8498. if (!uniform)
  8499. return;
  8500. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8501. };
  8502. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8503. if (!uniform)
  8504. return;
  8505. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8506. };
  8507. Engine.prototype.setFloat = function (uniform, value) {
  8508. if (!uniform)
  8509. return;
  8510. this._gl.uniform1f(uniform, value);
  8511. };
  8512. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8513. if (!uniform)
  8514. return;
  8515. this._gl.uniform2f(uniform, x, y);
  8516. };
  8517. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8518. if (!uniform)
  8519. return;
  8520. this._gl.uniform3f(uniform, x, y, z);
  8521. };
  8522. Engine.prototype.setBool = function (uniform, bool) {
  8523. if (!uniform)
  8524. return;
  8525. this._gl.uniform1i(uniform, bool);
  8526. };
  8527. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8528. if (!uniform)
  8529. return;
  8530. this._gl.uniform4f(uniform, x, y, z, w);
  8531. };
  8532. Engine.prototype.setColor3 = function (uniform, color3) {
  8533. if (!uniform)
  8534. return;
  8535. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8536. };
  8537. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8538. if (!uniform)
  8539. return;
  8540. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8541. };
  8542. // States
  8543. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8544. if (zOffset === void 0) { zOffset = 0; }
  8545. if (reverseSide === void 0) { reverseSide = false; }
  8546. // Culling
  8547. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8548. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8549. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8550. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8551. if (culling) {
  8552. this._depthCullingState.cullFace = cullFace;
  8553. this._depthCullingState.cull = true;
  8554. }
  8555. else {
  8556. this._depthCullingState.cull = false;
  8557. }
  8558. }
  8559. // Z offset
  8560. this._depthCullingState.zOffset = zOffset;
  8561. };
  8562. Engine.prototype.setDepthBuffer = function (enable) {
  8563. this._depthCullingState.depthTest = enable;
  8564. };
  8565. Engine.prototype.getDepthWrite = function () {
  8566. return this._depthCullingState.depthMask;
  8567. };
  8568. Engine.prototype.setDepthWrite = function (enable) {
  8569. this._depthCullingState.depthMask = enable;
  8570. };
  8571. Engine.prototype.setColorWrite = function (enable) {
  8572. this._gl.colorMask(enable, enable, enable, enable);
  8573. };
  8574. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8575. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8576. if (this._alphaMode === mode) {
  8577. return;
  8578. }
  8579. switch (mode) {
  8580. case Engine.ALPHA_DISABLE:
  8581. this._alphaState.alphaBlend = false;
  8582. break;
  8583. case Engine.ALPHA_PREMULTIPLIED:
  8584. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8585. this._alphaState.alphaBlend = true;
  8586. break;
  8587. case Engine.ALPHA_COMBINE:
  8588. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8589. this._alphaState.alphaBlend = true;
  8590. break;
  8591. case Engine.ALPHA_ONEONE:
  8592. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8593. this._alphaState.alphaBlend = true;
  8594. break;
  8595. case Engine.ALPHA_ADD:
  8596. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8597. this._alphaState.alphaBlend = true;
  8598. break;
  8599. case Engine.ALPHA_SUBTRACT:
  8600. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8601. this._alphaState.alphaBlend = true;
  8602. break;
  8603. case Engine.ALPHA_MULTIPLY:
  8604. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8605. this._alphaState.alphaBlend = true;
  8606. break;
  8607. case Engine.ALPHA_MAXIMIZED:
  8608. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8609. this._alphaState.alphaBlend = true;
  8610. break;
  8611. }
  8612. if (!noDepthWriteChange) {
  8613. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8614. }
  8615. this._alphaMode = mode;
  8616. };
  8617. Engine.prototype.getAlphaMode = function () {
  8618. return this._alphaMode;
  8619. };
  8620. Engine.prototype.setAlphaTesting = function (enable) {
  8621. this._alphaTest = enable;
  8622. };
  8623. Engine.prototype.getAlphaTesting = function () {
  8624. return !!this._alphaTest;
  8625. };
  8626. // Textures
  8627. Engine.prototype.wipeCaches = function () {
  8628. if (this.preventCacheWipeBetweenFrames) {
  8629. return;
  8630. }
  8631. this.resetTextureCache();
  8632. this._currentEffect = null;
  8633. this._stencilState.reset();
  8634. this._depthCullingState.reset();
  8635. this.setDepthFunctionToLessOrEqual();
  8636. this._alphaState.reset();
  8637. this._cachedVertexBuffers = null;
  8638. this._cachedIndexBuffer = null;
  8639. this._cachedEffectForVertexBuffers = null;
  8640. this._unBindVertexArrayObject();
  8641. this.bindIndexBuffer(null);
  8642. this.bindArrayBuffer(null);
  8643. };
  8644. /**
  8645. * Set the compressed texture format to use, based on the formats you have, and the formats
  8646. * supported by the hardware / browser.
  8647. *
  8648. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8649. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8650. * to API arguments needed to compressed textures. This puts the burden on the container
  8651. * generator to house the arcane code for determining these for current & future formats.
  8652. *
  8653. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  8654. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  8655. *
  8656. * Note: The result of this call is not taken into account when a texture is base64.
  8657. *
  8658. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  8659. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  8660. *
  8661. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  8662. * @returns The extension selected.
  8663. */
  8664. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8665. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8666. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8667. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8668. return this._textureFormatInUse = this._texturesSupported[i];
  8669. }
  8670. }
  8671. }
  8672. // actively set format to nothing, to allow this to be called more than once
  8673. // and possibly fail the 2nd time
  8674. return this._textureFormatInUse = null;
  8675. };
  8676. /**
  8677. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  8678. * @param {string} urlArg- This contains one of the following:
  8679. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  8680. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  8681. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  8682. *
  8683. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  8684. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  8685. * @param {Scene} scene- Needed for loading to the correct scene.
  8686. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  8687. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  8688. * @param {callback} onError- Optional callback to be called upon failure.
  8689. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  8690. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  8691. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  8692. *
  8693. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  8694. */
  8695. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  8696. var _this = this;
  8697. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8698. if (onLoad === void 0) { onLoad = null; }
  8699. if (onError === void 0) { onError = null; }
  8700. if (buffer === void 0) { buffer = null; }
  8701. var texture = fallBack ? fallBack : this._gl.createTexture();
  8702. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  8703. var fromData = url.substr(0, 5) === "data:";
  8704. var isBase64 = fromData && url.indexOf("base64") !== -1;
  8705. // establish the file extension, if possible
  8706. var lastDot = url.lastIndexOf('.');
  8707. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  8708. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8709. if (isDDS) {
  8710. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  8711. }
  8712. var isTGA = (extension === ".tga");
  8713. // determine if a ktx file should be substituted
  8714. var isKTX = false;
  8715. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  8716. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8717. isKTX = true;
  8718. }
  8719. scene._addPendingData(texture);
  8720. texture.url = url;
  8721. texture.noMipmap = noMipmap;
  8722. texture.references = 1;
  8723. texture.samplingMode = samplingMode;
  8724. texture.onLoadedCallbacks = [];
  8725. if (onLoad) {
  8726. texture.onLoadedCallbacks.push(onLoad);
  8727. }
  8728. if (!fallBack)
  8729. this._loadedTexturesCache.push(texture);
  8730. var onerror = function () {
  8731. scene._removePendingData(texture);
  8732. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  8733. if (isKTX) {
  8734. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  8735. }
  8736. else if (onError) {
  8737. onError();
  8738. }
  8739. };
  8740. var callback;
  8741. // processing for non-image formats
  8742. if (isKTX || isTGA || isDDS) {
  8743. if (isKTX) {
  8744. callback = function (data) {
  8745. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  8746. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  8747. ktx.uploadLevels(_this._gl, !noMipmap);
  8748. }, samplingMode);
  8749. };
  8750. }
  8751. else if (isTGA) {
  8752. callback = function (arrayBuffer) {
  8753. var data = new Uint8Array(arrayBuffer);
  8754. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8755. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8756. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8757. }, samplingMode);
  8758. };
  8759. }
  8760. else if (isDDS) {
  8761. callback = function (data) {
  8762. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8763. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8764. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8765. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8766. }, samplingMode);
  8767. };
  8768. }
  8769. if (!buffer) {
  8770. BABYLON.Tools.LoadFile(url, function (data) {
  8771. callback(data);
  8772. }, null, scene.database, true, onerror);
  8773. }
  8774. else {
  8775. callback(buffer);
  8776. }
  8777. // image format processing
  8778. }
  8779. else {
  8780. var onload = function (img) {
  8781. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8782. var isPot = (img.width === potWidth && img.height === potHeight);
  8783. if (!isPot) {
  8784. _this._prepareWorkingCanvas();
  8785. _this._workingCanvas.width = potWidth;
  8786. _this._workingCanvas.height = potHeight;
  8787. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8788. _this._workingContext.imageSmoothingEnabled = false;
  8789. _this._workingContext.mozImageSmoothingEnabled = false;
  8790. _this._workingContext.oImageSmoothingEnabled = false;
  8791. _this._workingContext.webkitImageSmoothingEnabled = false;
  8792. _this._workingContext.msImageSmoothingEnabled = false;
  8793. }
  8794. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8795. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8796. _this._workingContext.imageSmoothingEnabled = true;
  8797. _this._workingContext.mozImageSmoothingEnabled = true;
  8798. _this._workingContext.oImageSmoothingEnabled = true;
  8799. _this._workingContext.webkitImageSmoothingEnabled = true;
  8800. _this._workingContext.msImageSmoothingEnabled = true;
  8801. }
  8802. }
  8803. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  8804. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8805. }, samplingMode);
  8806. };
  8807. if (!fromData || isBase64)
  8808. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8809. else if (buffer instanceof Array || typeof buffer === "string")
  8810. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8811. else
  8812. onload(buffer);
  8813. }
  8814. return texture;
  8815. };
  8816. Engine.prototype._getInternalFormat = function (format) {
  8817. var internalFormat = this._gl.RGBA;
  8818. switch (format) {
  8819. case Engine.TEXTUREFORMAT_ALPHA:
  8820. internalFormat = this._gl.ALPHA;
  8821. break;
  8822. case Engine.TEXTUREFORMAT_LUMINANCE:
  8823. internalFormat = this._gl.LUMINANCE;
  8824. break;
  8825. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8826. internalFormat = this._gl.LUMINANCE_ALPHA;
  8827. break;
  8828. case Engine.TEXTUREFORMAT_RGB:
  8829. internalFormat = this._gl.RGB;
  8830. break;
  8831. case Engine.TEXTUREFORMAT_RGBA:
  8832. internalFormat = this._gl.RGBA;
  8833. break;
  8834. }
  8835. return internalFormat;
  8836. };
  8837. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8838. if (compression === void 0) { compression = null; }
  8839. var internalFormat = this._getInternalFormat(format);
  8840. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8841. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8842. if (texture._width % 4 !== 0) {
  8843. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8844. }
  8845. if (compression) {
  8846. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8847. }
  8848. else {
  8849. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8850. }
  8851. if (texture.generateMipMaps) {
  8852. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8853. }
  8854. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8855. this.resetTextureCache();
  8856. texture.isReady = true;
  8857. };
  8858. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8859. if (compression === void 0) { compression = null; }
  8860. var texture = this._gl.createTexture();
  8861. texture._baseWidth = width;
  8862. texture._baseHeight = height;
  8863. texture._width = width;
  8864. texture._height = height;
  8865. texture.references = 1;
  8866. this.updateRawTexture(texture, data, format, invertY, compression);
  8867. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8868. // Filters
  8869. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8870. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8871. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8872. if (generateMipMaps) {
  8873. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8874. }
  8875. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8876. texture.samplingMode = samplingMode;
  8877. this._loadedTexturesCache.push(texture);
  8878. return texture;
  8879. };
  8880. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8881. var texture = this._gl.createTexture();
  8882. texture._baseWidth = width;
  8883. texture._baseHeight = height;
  8884. if (generateMipMaps) {
  8885. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8886. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8887. }
  8888. this.resetTextureCache();
  8889. texture._width = width;
  8890. texture._height = height;
  8891. texture.isReady = false;
  8892. texture.generateMipMaps = generateMipMaps;
  8893. texture.references = 1;
  8894. texture.samplingMode = samplingMode;
  8895. this.updateTextureSamplingMode(samplingMode, texture);
  8896. this._loadedTexturesCache.push(texture);
  8897. return texture;
  8898. };
  8899. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8900. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8901. if (texture.isCube) {
  8902. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8903. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8904. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8905. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8906. }
  8907. else {
  8908. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8909. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8910. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8911. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8912. }
  8913. texture.samplingMode = samplingMode;
  8914. };
  8915. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  8916. if (premulAlpha === void 0) { premulAlpha = false; }
  8917. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8918. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8919. if (premulAlpha) {
  8920. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8921. }
  8922. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  8923. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  8924. if (texture.generateMipMaps) {
  8925. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8926. }
  8927. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8928. if (premulAlpha) {
  8929. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8930. }
  8931. this.resetTextureCache();
  8932. texture.isReady = true;
  8933. };
  8934. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8935. if (texture._isDisabled) {
  8936. return;
  8937. }
  8938. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8939. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8940. try {
  8941. // Testing video texture support
  8942. if (this._videoTextureSupported === undefined) {
  8943. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8944. if (this._gl.getError() !== 0) {
  8945. this._videoTextureSupported = false;
  8946. }
  8947. else {
  8948. this._videoTextureSupported = true;
  8949. }
  8950. }
  8951. // Copy video through the current working canvas if video texture is not supported
  8952. if (!this._videoTextureSupported) {
  8953. if (!texture._workingCanvas) {
  8954. texture._workingCanvas = document.createElement("canvas");
  8955. texture._workingContext = texture._workingCanvas.getContext("2d");
  8956. texture._workingCanvas.width = texture._width;
  8957. texture._workingCanvas.height = texture._height;
  8958. }
  8959. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8960. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8961. }
  8962. else {
  8963. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8964. }
  8965. if (texture.generateMipMaps) {
  8966. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8967. }
  8968. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8969. this.resetTextureCache();
  8970. texture.isReady = true;
  8971. }
  8972. catch (ex) {
  8973. // Something unexpected
  8974. // Let's disable the texture
  8975. texture._isDisabled = true;
  8976. }
  8977. };
  8978. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8979. // old version had a "generateMipMaps" arg instead of options.
  8980. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8981. // in the same way, generateDepthBuffer is defaulted to true
  8982. var generateMipMaps = false;
  8983. var generateDepthBuffer = true;
  8984. var generateStencilBuffer = false;
  8985. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8986. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8987. if (options !== undefined) {
  8988. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8989. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8990. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8991. type = options.type === undefined ? type : options.type;
  8992. if (options.samplingMode !== undefined) {
  8993. samplingMode = options.samplingMode;
  8994. }
  8995. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8996. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8997. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8998. }
  8999. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9000. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9001. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9002. }
  9003. }
  9004. var gl = this._gl;
  9005. var texture = gl.createTexture();
  9006. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9007. var width = size.width || size;
  9008. var height = size.height || size;
  9009. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9010. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9011. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9012. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9013. }
  9014. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9016. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9017. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9018. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9019. // Create the framebuffer
  9020. var framebuffer = gl.createFramebuffer();
  9021. this.bindUnboundFramebuffer(framebuffer);
  9022. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9023. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9024. if (generateMipMaps) {
  9025. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9026. }
  9027. // Unbind
  9028. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9029. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9030. this.bindUnboundFramebuffer(null);
  9031. texture._framebuffer = framebuffer;
  9032. texture._baseWidth = width;
  9033. texture._baseHeight = height;
  9034. texture._width = width;
  9035. texture._height = height;
  9036. texture.isReady = true;
  9037. texture.samples = 1;
  9038. texture.generateMipMaps = generateMipMaps;
  9039. texture.references = 1;
  9040. texture.samplingMode = samplingMode;
  9041. texture.type = type;
  9042. texture._generateDepthBuffer = generateDepthBuffer;
  9043. texture._generateStencilBuffer = generateStencilBuffer;
  9044. this.resetTextureCache();
  9045. this._loadedTexturesCache.push(texture);
  9046. return texture;
  9047. };
  9048. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9049. if (samples === void 0) { samples = 1; }
  9050. var depthStencilBuffer = null;
  9051. var gl = this._gl;
  9052. // Create the depth/stencil buffer
  9053. if (generateStencilBuffer) {
  9054. depthStencilBuffer = gl.createRenderbuffer();
  9055. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9056. if (samples > 1) {
  9057. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9058. }
  9059. else {
  9060. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9061. }
  9062. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9063. }
  9064. else if (generateDepthBuffer) {
  9065. depthStencilBuffer = gl.createRenderbuffer();
  9066. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9067. if (samples > 1) {
  9068. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9069. }
  9070. else {
  9071. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9072. }
  9073. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9074. }
  9075. return depthStencilBuffer;
  9076. };
  9077. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9078. if (this.webGLVersion < 2) {
  9079. return 1;
  9080. }
  9081. if (texture.samples === samples) {
  9082. return samples;
  9083. }
  9084. var gl = this._gl;
  9085. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9086. // Dispose previous render buffers
  9087. if (texture._depthStencilBuffer) {
  9088. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9089. }
  9090. if (texture._MSAAFramebuffer) {
  9091. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9092. }
  9093. if (texture._MSAARenderBuffer) {
  9094. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9095. }
  9096. if (samples > 1) {
  9097. texture._MSAAFramebuffer = gl.createFramebuffer();
  9098. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9099. var colorRenderbuffer = gl.createRenderbuffer();
  9100. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9101. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9102. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9103. texture._MSAARenderBuffer = colorRenderbuffer;
  9104. }
  9105. else {
  9106. this.bindUnboundFramebuffer(texture._framebuffer);
  9107. }
  9108. texture.samples = samples;
  9109. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9110. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9111. this.bindUnboundFramebuffer(null);
  9112. return samples;
  9113. };
  9114. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9115. var gl = this._gl;
  9116. var texture = gl.createTexture();
  9117. var generateMipMaps = true;
  9118. var generateDepthBuffer = true;
  9119. var generateStencilBuffer = false;
  9120. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9121. if (options !== undefined) {
  9122. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9123. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9124. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9125. if (options.samplingMode !== undefined) {
  9126. samplingMode = options.samplingMode;
  9127. }
  9128. }
  9129. texture.isCube = true;
  9130. texture.references = 1;
  9131. texture.generateMipMaps = generateMipMaps;
  9132. texture.references = 1;
  9133. texture.samples = 1;
  9134. texture.samplingMode = samplingMode;
  9135. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9136. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9137. for (var face = 0; face < 6; face++) {
  9138. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9139. }
  9140. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9141. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9142. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9143. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9144. // Create the framebuffer
  9145. var framebuffer = gl.createFramebuffer();
  9146. this.bindUnboundFramebuffer(framebuffer);
  9147. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9148. // Mipmaps
  9149. if (texture.generateMipMaps) {
  9150. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9151. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9152. }
  9153. // Unbind
  9154. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9155. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9156. this.bindUnboundFramebuffer(null);
  9157. texture._framebuffer = framebuffer;
  9158. texture._width = size;
  9159. texture._height = size;
  9160. texture.isReady = true;
  9161. this.resetTextureCache();
  9162. this._loadedTexturesCache.push(texture);
  9163. return texture;
  9164. };
  9165. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9166. var _this = this;
  9167. if (onLoad === void 0) { onLoad = null; }
  9168. if (onError === void 0) { onError = null; }
  9169. var gl = this._gl;
  9170. var texture = gl.createTexture();
  9171. texture.isCube = true;
  9172. texture.url = rootUrl;
  9173. texture.references = 1;
  9174. texture.onLoadedCallbacks = [];
  9175. var isKTX = false;
  9176. var lastDot = rootUrl.lastIndexOf('.');
  9177. var extension = rootUrl.substring(lastDot).toLowerCase();
  9178. if (this._textureFormatInUse) {
  9179. extension = this._textureFormatInUse;
  9180. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9181. isKTX = true;
  9182. }
  9183. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9184. if (isDDS) {
  9185. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9186. }
  9187. if (isKTX) {
  9188. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9189. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9190. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9191. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9192. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9193. ktx.uploadLevels(_this._gl, !noMipmap);
  9194. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9195. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9196. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9197. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9198. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9199. _this.resetTextureCache();
  9200. texture._width = ktx.pixelWidth;
  9201. texture._height = ktx.pixelHeight;
  9202. texture.isReady = true;
  9203. }, null, null, true, onError);
  9204. }
  9205. else if (isDDS) {
  9206. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9207. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9208. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9209. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9210. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9211. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9212. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9213. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9214. }
  9215. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9216. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9217. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9218. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9219. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9220. _this.resetTextureCache();
  9221. texture._width = info.width;
  9222. texture._height = info.height;
  9223. texture.isReady = true;
  9224. }, null, null, true, onError);
  9225. }
  9226. else {
  9227. cascadeLoad(rootUrl, scene, function (imgs) {
  9228. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9229. var height = width;
  9230. _this._prepareWorkingCanvas();
  9231. _this._workingCanvas.width = width;
  9232. _this._workingCanvas.height = height;
  9233. var faces = [
  9234. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9235. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9236. ];
  9237. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9238. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9239. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9240. for (var index = 0; index < faces.length; index++) {
  9241. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9242. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9243. }
  9244. if (!noMipmap) {
  9245. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9246. }
  9247. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9248. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9249. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9250. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9251. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9252. _this.resetTextureCache();
  9253. texture._width = width;
  9254. texture._height = height;
  9255. texture.isReady = true;
  9256. texture.onLoadedCallbacks.forEach(function (callback) {
  9257. callback();
  9258. });
  9259. if (onLoad) {
  9260. onLoad();
  9261. }
  9262. }, files, onError);
  9263. }
  9264. this._loadedTexturesCache.push(texture);
  9265. return texture;
  9266. };
  9267. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9268. texture._width = width;
  9269. texture._height = height;
  9270. texture._size = width * height;
  9271. texture._baseWidth = width;
  9272. texture._baseHeight = height;
  9273. };
  9274. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  9275. var _this = this;
  9276. if (onLoad === void 0) { onLoad = null; }
  9277. if (onError === void 0) { onError = null; }
  9278. var gl = this._gl;
  9279. var texture = gl.createTexture();
  9280. scene._addPendingData(texture);
  9281. texture.isCube = true;
  9282. texture.references = 1;
  9283. texture.url = url;
  9284. var textureType = gl.UNSIGNED_BYTE;
  9285. if (type === Engine.TEXTURETYPE_FLOAT) {
  9286. textureType = gl.FLOAT;
  9287. }
  9288. var internalFormat = this._getInternalFormat(format);
  9289. var needConversion = false;
  9290. if (internalFormat === gl.RGB) {
  9291. internalFormat = gl.RGBA;
  9292. needConversion = true;
  9293. }
  9294. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9295. var width = size;
  9296. var height = width;
  9297. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9298. texture._width = width;
  9299. texture._height = height;
  9300. var onerror = function () {
  9301. scene._removePendingData(texture);
  9302. if (onError) {
  9303. onError();
  9304. }
  9305. };
  9306. var internalCallback = function (data) {
  9307. var rgbeDataArrays = callback(data);
  9308. var facesIndex = [
  9309. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9310. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9311. ];
  9312. width = texture._width;
  9313. height = texture._height;
  9314. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9315. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9316. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9317. if (mipmmapGenerator) {
  9318. var arrayTemp = [];
  9319. // Data are known to be in +X +Y +Z -X -Y -Z
  9320. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9321. arrayTemp.push(rgbeDataArrays[0]); // +X
  9322. arrayTemp.push(rgbeDataArrays[3]); // -X
  9323. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9324. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9325. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9326. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9327. var mipData = mipmmapGenerator(arrayTemp);
  9328. // mipData is order in +X -X +Y -Y +Z -Z
  9329. var mipFaces = [0, 2, 4, 1, 3, 5];
  9330. for (var level = 0; level < mipData.length; level++) {
  9331. var mipSize = width >> level;
  9332. for (var mipIndex in mipFaces) {
  9333. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9334. if (needConversion) {
  9335. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9336. }
  9337. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9338. }
  9339. }
  9340. }
  9341. else {
  9342. // Data are known to be in +X +Y +Z -X -Y -Z
  9343. for (var index = 0; index < facesIndex.length; index++) {
  9344. var faceData = rgbeDataArrays[index];
  9345. if (needConversion) {
  9346. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  9347. }
  9348. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  9349. }
  9350. if (!noMipmap && isPot) {
  9351. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9352. }
  9353. else {
  9354. noMipmap = true;
  9355. }
  9356. }
  9357. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  9358. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9359. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9360. }
  9361. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  9362. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9363. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9364. }
  9365. else {
  9366. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9367. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9368. }
  9369. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9370. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9371. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9372. texture.isReady = true;
  9373. _this.resetTextureCache();
  9374. scene._removePendingData(texture);
  9375. if (onLoad) {
  9376. onLoad();
  9377. }
  9378. };
  9379. BABYLON.Tools.LoadFile(url, function (data) {
  9380. internalCallback(data);
  9381. }, onerror, scene.database, true);
  9382. return texture;
  9383. };
  9384. ;
  9385. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9386. // Create new RGBA data container.
  9387. var rgbaData;
  9388. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9389. rgbaData = new Float32Array(width * height * 4);
  9390. }
  9391. else {
  9392. rgbaData = new Uint32Array(width * height * 4);
  9393. }
  9394. // Convert each pixel.
  9395. for (var x = 0; x < width; x++) {
  9396. for (var y = 0; y < height; y++) {
  9397. var index = (y * width + x) * 3;
  9398. var newIndex = (y * width + x) * 4;
  9399. // Map Old Value to new value.
  9400. rgbaData[newIndex + 0] = rgbData[index + 0];
  9401. rgbaData[newIndex + 1] = rgbData[index + 1];
  9402. rgbaData[newIndex + 2] = rgbData[index + 2];
  9403. // Add fully opaque alpha channel.
  9404. rgbaData[newIndex + 3] = 1;
  9405. }
  9406. }
  9407. return rgbaData;
  9408. };
  9409. Engine.prototype._releaseTexture = function (texture) {
  9410. var gl = this._gl;
  9411. if (texture._framebuffer) {
  9412. gl.deleteFramebuffer(texture._framebuffer);
  9413. }
  9414. if (texture._depthStencilBuffer) {
  9415. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9416. }
  9417. if (texture._MSAAFramebuffer) {
  9418. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9419. }
  9420. if (texture._MSAARenderBuffer) {
  9421. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9422. }
  9423. gl.deleteTexture(texture);
  9424. // Unbind channels
  9425. this.unbindAllTextures();
  9426. var index = this._loadedTexturesCache.indexOf(texture);
  9427. if (index !== -1) {
  9428. this._loadedTexturesCache.splice(index, 1);
  9429. }
  9430. };
  9431. Engine.prototype.setProgram = function (program) {
  9432. if (this._currentProgram !== program) {
  9433. this._gl.useProgram(program);
  9434. this._currentProgram = program;
  9435. }
  9436. };
  9437. Engine.prototype.bindSamplers = function (effect) {
  9438. this.setProgram(effect.getProgram());
  9439. var samplers = effect.getSamplers();
  9440. for (var index = 0; index < samplers.length; index++) {
  9441. var uniform = effect.getUniform(samplers[index]);
  9442. this._gl.uniform1i(uniform, index);
  9443. }
  9444. this._currentEffect = null;
  9445. };
  9446. Engine.prototype.activateTexture = function (texture) {
  9447. if (this._activeTexture !== texture) {
  9448. this._gl.activeTexture(texture);
  9449. this._activeTexture = texture;
  9450. }
  9451. };
  9452. Engine.prototype._bindTextureDirectly = function (target, texture) {
  9453. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  9454. this._gl.bindTexture(target, texture);
  9455. this._activeTexturesCache[this._activeTexture] = texture;
  9456. }
  9457. };
  9458. Engine.prototype._bindTexture = function (channel, texture) {
  9459. if (channel < 0) {
  9460. return;
  9461. }
  9462. this.activateTexture(this._gl.TEXTURE0 + channel);
  9463. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9464. };
  9465. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9466. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  9467. };
  9468. Engine.prototype.unbindAllTextures = function () {
  9469. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  9470. this.activateTexture(this._gl["TEXTURE" + channel]);
  9471. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9472. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9473. }
  9474. };
  9475. Engine.prototype.setTexture = function (channel, uniform, texture) {
  9476. if (channel < 0) {
  9477. return;
  9478. }
  9479. this._gl.uniform1i(uniform, channel);
  9480. this._setTexture(channel, texture);
  9481. };
  9482. Engine.prototype._setTexture = function (channel, texture) {
  9483. // Not ready?
  9484. if (!texture || !texture.isReady()) {
  9485. if (this._activeTexturesCache[channel] != null) {
  9486. this.activateTexture(this._gl["TEXTURE" + channel]);
  9487. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9488. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9489. }
  9490. return;
  9491. }
  9492. // Video
  9493. var alreadyActivated = false;
  9494. if (texture.video) {
  9495. this.activateTexture(this._gl["TEXTURE" + channel]);
  9496. alreadyActivated = true;
  9497. texture.update();
  9498. }
  9499. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  9500. texture.delayLoad();
  9501. return;
  9502. }
  9503. var internalTexture = texture.getInternalTexture();
  9504. if (this._activeTexturesCache[channel] === internalTexture) {
  9505. return;
  9506. }
  9507. if (!alreadyActivated) {
  9508. this.activateTexture(this._gl["TEXTURE" + channel]);
  9509. }
  9510. if (internalTexture.isCube) {
  9511. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  9512. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  9513. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  9514. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  9515. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  9516. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  9517. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  9518. }
  9519. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  9520. }
  9521. else {
  9522. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  9523. if (internalTexture._cachedWrapU !== texture.wrapU) {
  9524. internalTexture._cachedWrapU = texture.wrapU;
  9525. switch (texture.wrapU) {
  9526. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9527. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  9528. break;
  9529. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9530. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  9531. break;
  9532. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9533. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  9534. break;
  9535. }
  9536. }
  9537. if (internalTexture._cachedWrapV !== texture.wrapV) {
  9538. internalTexture._cachedWrapV = texture.wrapV;
  9539. switch (texture.wrapV) {
  9540. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9541. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  9542. break;
  9543. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9544. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  9545. break;
  9546. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9547. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  9548. break;
  9549. }
  9550. }
  9551. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  9552. }
  9553. };
  9554. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  9555. if (channel < 0) {
  9556. return;
  9557. }
  9558. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  9559. this._textureUnits = new Int32Array(textures.length);
  9560. }
  9561. for (var i = 0; i < textures.length; i++) {
  9562. this._textureUnits[i] = channel + i;
  9563. }
  9564. this._gl.uniform1iv(uniform, this._textureUnits);
  9565. for (var index = 0; index < textures.length; index++) {
  9566. this._setTexture(channel + index, textures[index]);
  9567. }
  9568. };
  9569. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  9570. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  9571. var value = texture.anisotropicFilteringLevel;
  9572. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9573. value = 1;
  9574. }
  9575. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  9576. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  9577. texture._cachedAnisotropicFilteringLevel = value;
  9578. }
  9579. };
  9580. Engine.prototype.readPixels = function (x, y, width, height) {
  9581. var data = new Uint8Array(height * width * 4);
  9582. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  9583. return data;
  9584. };
  9585. /**
  9586. * Add an externaly attached data from its key.
  9587. * This method call will fail and return false, if such key already exists.
  9588. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  9589. * @param key the unique key that identifies the data
  9590. * @param data the data object to associate to the key for this Engine instance
  9591. * @return true if no such key were already present and the data was added successfully, false otherwise
  9592. */
  9593. Engine.prototype.addExternalData = function (key, data) {
  9594. if (!this._externalData) {
  9595. this._externalData = new BABYLON.StringDictionary();
  9596. }
  9597. return this._externalData.add(key, data);
  9598. };
  9599. /**
  9600. * Get an externaly attached data from its key
  9601. * @param key the unique key that identifies the data
  9602. * @return the associated data, if present (can be null), or undefined if not present
  9603. */
  9604. Engine.prototype.getExternalData = function (key) {
  9605. if (!this._externalData) {
  9606. this._externalData = new BABYLON.StringDictionary();
  9607. }
  9608. return this._externalData.get(key);
  9609. };
  9610. /**
  9611. * Get an externaly attached data from its key, create it using a factory if it's not already present
  9612. * @param key the unique key that identifies the data
  9613. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  9614. * @return the associated data, can be null if the factory returned null.
  9615. */
  9616. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  9617. if (!this._externalData) {
  9618. this._externalData = new BABYLON.StringDictionary();
  9619. }
  9620. return this._externalData.getOrAddWithFactory(key, factory);
  9621. };
  9622. /**
  9623. * Remove an externaly attached data from the Engine instance
  9624. * @param key the unique key that identifies the data
  9625. * @return true if the data was successfully removed, false if it doesn't exist
  9626. */
  9627. Engine.prototype.removeExternalData = function (key) {
  9628. if (!this._externalData) {
  9629. this._externalData = new BABYLON.StringDictionary();
  9630. }
  9631. return this._externalData.remove(key);
  9632. };
  9633. Engine.prototype.releaseInternalTexture = function (texture) {
  9634. if (!texture) {
  9635. return;
  9636. }
  9637. texture.references--;
  9638. // Final reference ?
  9639. if (texture.references === 0) {
  9640. var texturesCache = this.getLoadedTexturesCache();
  9641. var index = texturesCache.indexOf(texture);
  9642. if (index > -1) {
  9643. texturesCache.splice(index, 1);
  9644. }
  9645. this._releaseTexture(texture);
  9646. }
  9647. };
  9648. Engine.prototype.unbindAllAttributes = function () {
  9649. if (this._mustWipeVertexAttributes) {
  9650. this._mustWipeVertexAttributes = false;
  9651. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9652. this._gl.disableVertexAttribArray(i);
  9653. this._vertexAttribArraysEnabled[i] = false;
  9654. this._currentBufferPointers[i] = null;
  9655. }
  9656. return;
  9657. }
  9658. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  9659. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  9660. continue;
  9661. }
  9662. this._gl.disableVertexAttribArray(i);
  9663. this._vertexAttribArraysEnabled[i] = false;
  9664. this._currentBufferPointers[i] = null;
  9665. }
  9666. };
  9667. Engine.prototype.releaseEffects = function () {
  9668. for (var name in this._compiledEffects) {
  9669. this._gl.deleteProgram(this._compiledEffects[name]._program);
  9670. }
  9671. this._compiledEffects = {};
  9672. };
  9673. // Dispose
  9674. Engine.prototype.dispose = function () {
  9675. this.hideLoadingUI();
  9676. this.stopRenderLoop();
  9677. // Release scenes
  9678. while (this.scenes.length) {
  9679. this.scenes[0].dispose();
  9680. }
  9681. // Release audio engine
  9682. Engine.audioEngine.dispose();
  9683. // Release effects
  9684. this.releaseEffects();
  9685. // Unbind
  9686. this.unbindAllAttributes();
  9687. this._gl = null;
  9688. //WebVR
  9689. this.disableVR();
  9690. // Events
  9691. window.removeEventListener("blur", this._onBlur);
  9692. window.removeEventListener("focus", this._onFocus);
  9693. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  9694. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  9695. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  9696. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  9697. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  9698. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  9699. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  9700. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  9701. // Remove from Instances
  9702. var index = Engine.Instances.indexOf(this);
  9703. if (index >= 0) {
  9704. Engine.Instances.splice(index, 1);
  9705. }
  9706. };
  9707. // Loading screen
  9708. Engine.prototype.displayLoadingUI = function () {
  9709. this.loadingScreen.displayLoadingUI();
  9710. };
  9711. Engine.prototype.hideLoadingUI = function () {
  9712. this.loadingScreen.hideLoadingUI();
  9713. };
  9714. Object.defineProperty(Engine.prototype, "loadingScreen", {
  9715. get: function () {
  9716. if (!this._loadingScreen)
  9717. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  9718. return this._loadingScreen;
  9719. },
  9720. set: function (loadingScreen) {
  9721. this._loadingScreen = loadingScreen;
  9722. },
  9723. enumerable: true,
  9724. configurable: true
  9725. });
  9726. Object.defineProperty(Engine.prototype, "loadingUIText", {
  9727. set: function (text) {
  9728. this.loadingScreen.loadingUIText = text;
  9729. },
  9730. enumerable: true,
  9731. configurable: true
  9732. });
  9733. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  9734. set: function (color) {
  9735. this.loadingScreen.loadingUIBackgroundColor = color;
  9736. },
  9737. enumerable: true,
  9738. configurable: true
  9739. });
  9740. Engine.prototype.attachContextLostEvent = function (callback) {
  9741. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  9742. };
  9743. Engine.prototype.attachContextRestoredEvent = function (callback) {
  9744. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  9745. };
  9746. Engine.prototype.getVertexShaderSource = function (program) {
  9747. var shaders = this._gl.getAttachedShaders(program);
  9748. return this._gl.getShaderSource(shaders[0]);
  9749. };
  9750. Engine.prototype.getFragmentShaderSource = function (program) {
  9751. var shaders = this._gl.getAttachedShaders(program);
  9752. return this._gl.getShaderSource(shaders[1]);
  9753. };
  9754. // FPS
  9755. Engine.prototype.getFps = function () {
  9756. return this.fps;
  9757. };
  9758. Engine.prototype.getDeltaTime = function () {
  9759. return this.deltaTime;
  9760. };
  9761. Engine.prototype._measureFps = function () {
  9762. this.previousFramesDuration.push(BABYLON.Tools.Now);
  9763. var length = this.previousFramesDuration.length;
  9764. if (length >= 2) {
  9765. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  9766. }
  9767. if (length >= this.fpsRange) {
  9768. if (length > this.fpsRange) {
  9769. this.previousFramesDuration.splice(0, 1);
  9770. length = this.previousFramesDuration.length;
  9771. }
  9772. var sum = 0;
  9773. for (var id = 0; id < length - 1; id++) {
  9774. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  9775. }
  9776. this.fps = 1000.0 / (sum / (length - 1));
  9777. }
  9778. };
  9779. Engine.prototype._canRenderToFloatFramebuffer = function () {
  9780. if (this._webGLVersion > 1) {
  9781. return this._caps.colorBufferFloat;
  9782. }
  9783. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  9784. };
  9785. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  9786. if (this._webGLVersion > 1) {
  9787. return this._caps.colorBufferFloat;
  9788. }
  9789. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  9790. };
  9791. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9792. Engine.prototype._canRenderToFramebuffer = function (type) {
  9793. var gl = this._gl;
  9794. //clear existing errors
  9795. while (gl.getError() !== gl.NO_ERROR) { }
  9796. var successful = true;
  9797. var texture = gl.createTexture();
  9798. gl.bindTexture(gl.TEXTURE_2D, texture);
  9799. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9800. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9801. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9802. var fb = gl.createFramebuffer();
  9803. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9804. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9805. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9806. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  9807. successful = successful && (gl.getError() === gl.NO_ERROR);
  9808. //try render by clearing frame buffer's color buffer
  9809. if (successful) {
  9810. gl.clear(gl.COLOR_BUFFER_BIT);
  9811. successful = successful && (gl.getError() === gl.NO_ERROR);
  9812. }
  9813. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  9814. if (successful) {
  9815. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  9816. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9817. var readFormat = gl.RGBA;
  9818. var readType = gl.UNSIGNED_BYTE;
  9819. var buffer = new Uint8Array(4);
  9820. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  9821. successful = successful && (gl.getError() === gl.NO_ERROR);
  9822. }
  9823. //clean up
  9824. gl.deleteTexture(texture);
  9825. gl.deleteFramebuffer(fb);
  9826. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9827. //clear accumulated errors
  9828. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  9829. return successful;
  9830. };
  9831. Engine.prototype._getWebGLTextureType = function (type) {
  9832. if (type === Engine.TEXTURETYPE_FLOAT) {
  9833. return this._gl.FLOAT;
  9834. }
  9835. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9836. // Add Half Float Constant.
  9837. return Engine.HALF_FLOAT_OES;
  9838. }
  9839. return this._gl.UNSIGNED_BYTE;
  9840. };
  9841. ;
  9842. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  9843. if (this._webGLVersion === 1) {
  9844. return this._gl.RGBA;
  9845. }
  9846. if (type === Engine.TEXTURETYPE_FLOAT) {
  9847. return Engine.RGBA32F;
  9848. }
  9849. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9850. return Engine.RGBA16F;
  9851. }
  9852. return this._gl.RGBA;
  9853. };
  9854. ;
  9855. // Statics
  9856. Engine.isSupported = function () {
  9857. try {
  9858. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9859. if (navigator.isCocoonJS) {
  9860. return true;
  9861. }
  9862. var tempcanvas = document.createElement("canvas");
  9863. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9864. return gl != null && !!window.WebGLRenderingContext;
  9865. }
  9866. catch (e) {
  9867. return false;
  9868. }
  9869. };
  9870. return Engine;
  9871. }());
  9872. Engine.Instances = new Array();
  9873. // Const statics
  9874. Engine._ALPHA_DISABLE = 0;
  9875. Engine._ALPHA_ADD = 1;
  9876. Engine._ALPHA_COMBINE = 2;
  9877. Engine._ALPHA_SUBTRACT = 3;
  9878. Engine._ALPHA_MULTIPLY = 4;
  9879. Engine._ALPHA_MAXIMIZED = 5;
  9880. Engine._ALPHA_ONEONE = 6;
  9881. Engine._ALPHA_PREMULTIPLIED = 7;
  9882. Engine._DELAYLOADSTATE_NONE = 0;
  9883. Engine._DELAYLOADSTATE_LOADED = 1;
  9884. Engine._DELAYLOADSTATE_LOADING = 2;
  9885. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9886. Engine._TEXTUREFORMAT_ALPHA = 0;
  9887. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9888. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9889. Engine._TEXTUREFORMAT_RGB = 4;
  9890. Engine._TEXTUREFORMAT_RGBA = 5;
  9891. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9892. Engine._TEXTURETYPE_FLOAT = 1;
  9893. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9894. // Depht or Stencil test Constants.
  9895. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9896. 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.
  9897. 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.
  9898. 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.
  9899. 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.
  9900. 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.
  9901. 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.
  9902. 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.
  9903. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9904. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9905. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9906. // Stencil Actions Constants.
  9907. Engine._KEEP = 0x1E00;
  9908. Engine._REPLACE = 0x1E01;
  9909. Engine._INCR = 0x1E02;
  9910. Engine._DECR = 0x1E03;
  9911. Engine._INVERT = 0x150A;
  9912. Engine._INCR_WRAP = 0x8507;
  9913. Engine._DECR_WRAP = 0x8508;
  9914. // Updatable statics so stick with vars here
  9915. Engine.CollisionsEpsilon = 0.001;
  9916. Engine.CodeRepository = "src/";
  9917. Engine.ShadersRepository = "src/Shaders/";
  9918. BABYLON.Engine = Engine;
  9919. })(BABYLON || (BABYLON = {}));
  9920. //# sourceMappingURL=babylon.engine.js.map
  9921. /// <reference path="Tools\babylon.decorators.ts" />
  9922. var BABYLON;
  9923. (function (BABYLON) {
  9924. /**
  9925. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9926. */
  9927. var Node = (function () {
  9928. /**
  9929. * @constructor
  9930. * @param {string} name - the name and id to be given to this node
  9931. * @param {BABYLON.Scene} the scene this node will be added to
  9932. */
  9933. function Node(name, scene) {
  9934. this.state = "";
  9935. this.metadata = null;
  9936. this.doNotSerialize = false;
  9937. this.animations = new Array();
  9938. this._ranges = {};
  9939. this._childrenFlag = -1;
  9940. this._isEnabled = true;
  9941. this._isReady = true;
  9942. this._currentRenderId = -1;
  9943. this._parentRenderId = -1;
  9944. /**
  9945. * An event triggered when the mesh is disposed.
  9946. * @type {BABYLON.Observable}
  9947. */
  9948. this.onDisposeObservable = new BABYLON.Observable();
  9949. this.name = name;
  9950. this.id = name;
  9951. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  9952. this._initCache();
  9953. }
  9954. Object.defineProperty(Node.prototype, "parent", {
  9955. get: function () {
  9956. return this._parentNode;
  9957. },
  9958. set: function (parent) {
  9959. if (this._parentNode === parent) {
  9960. return;
  9961. }
  9962. if (this._parentNode) {
  9963. var index = this._parentNode._children.indexOf(this);
  9964. if (index !== -1) {
  9965. this._parentNode._children.splice(index, 1);
  9966. }
  9967. }
  9968. this._parentNode = parent;
  9969. if (this._parentNode) {
  9970. if (!this._parentNode._children) {
  9971. this._parentNode._children = new Array();
  9972. }
  9973. this._parentNode._children.push(this);
  9974. }
  9975. },
  9976. enumerable: true,
  9977. configurable: true
  9978. });
  9979. Node.prototype.getClassName = function () {
  9980. return "Node";
  9981. };
  9982. Object.defineProperty(Node.prototype, "onDispose", {
  9983. set: function (callback) {
  9984. if (this._onDisposeObserver) {
  9985. this.onDisposeObservable.remove(this._onDisposeObserver);
  9986. }
  9987. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9988. },
  9989. enumerable: true,
  9990. configurable: true
  9991. });
  9992. Node.prototype.getScene = function () {
  9993. return this._scene;
  9994. };
  9995. Node.prototype.getEngine = function () {
  9996. return this._scene.getEngine();
  9997. };
  9998. // override it in derived class
  9999. Node.prototype.getWorldMatrix = function () {
  10000. return BABYLON.Matrix.Identity();
  10001. };
  10002. // override it in derived class if you add new variables to the cache
  10003. // and call the parent class method
  10004. Node.prototype._initCache = function () {
  10005. this._cache = {};
  10006. this._cache.parent = undefined;
  10007. };
  10008. Node.prototype.updateCache = function (force) {
  10009. if (!force && this.isSynchronized())
  10010. return;
  10011. this._cache.parent = this.parent;
  10012. this._updateCache();
  10013. };
  10014. // override it in derived class if you add new variables to the cache
  10015. // and call the parent class method if !ignoreParentClass
  10016. Node.prototype._updateCache = function (ignoreParentClass) {
  10017. };
  10018. // override it in derived class if you add new variables to the cache
  10019. Node.prototype._isSynchronized = function () {
  10020. return true;
  10021. };
  10022. Node.prototype._markSyncedWithParent = function () {
  10023. this._parentRenderId = this.parent._currentRenderId;
  10024. };
  10025. Node.prototype.isSynchronizedWithParent = function () {
  10026. if (!this.parent) {
  10027. return true;
  10028. }
  10029. if (this._parentRenderId !== this.parent._currentRenderId) {
  10030. return false;
  10031. }
  10032. return this.parent.isSynchronized();
  10033. };
  10034. Node.prototype.isSynchronized = function (updateCache) {
  10035. var check = this.hasNewParent();
  10036. check = check || !this.isSynchronizedWithParent();
  10037. check = check || !this._isSynchronized();
  10038. if (updateCache)
  10039. this.updateCache(true);
  10040. return !check;
  10041. };
  10042. Node.prototype.hasNewParent = function (update) {
  10043. if (this._cache.parent === this.parent)
  10044. return false;
  10045. if (update)
  10046. this._cache.parent = this.parent;
  10047. return true;
  10048. };
  10049. /**
  10050. * Is this node ready to be used/rendered
  10051. * @return {boolean} is it ready
  10052. */
  10053. Node.prototype.isReady = function () {
  10054. return this._isReady;
  10055. };
  10056. /**
  10057. * Is this node enabled.
  10058. * If the node has a parent and is enabled, the parent will be inspected as well.
  10059. * @return {boolean} whether this node (and its parent) is enabled.
  10060. * @see setEnabled
  10061. */
  10062. Node.prototype.isEnabled = function () {
  10063. if (!this._isEnabled) {
  10064. return false;
  10065. }
  10066. if (this.parent) {
  10067. return this.parent.isEnabled();
  10068. }
  10069. return true;
  10070. };
  10071. /**
  10072. * Set the enabled state of this node.
  10073. * @param {boolean} value - the new enabled state
  10074. * @see isEnabled
  10075. */
  10076. Node.prototype.setEnabled = function (value) {
  10077. this._isEnabled = value;
  10078. };
  10079. /**
  10080. * Is this node a descendant of the given node.
  10081. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10082. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10083. * @see parent
  10084. */
  10085. Node.prototype.isDescendantOf = function (ancestor) {
  10086. if (this.parent) {
  10087. if (this.parent === ancestor) {
  10088. return true;
  10089. }
  10090. return this.parent.isDescendantOf(ancestor);
  10091. }
  10092. return false;
  10093. };
  10094. /**
  10095. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10096. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10097. * @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.
  10098. * @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.
  10099. */
  10100. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10101. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10102. if (!this._children) {
  10103. return;
  10104. }
  10105. for (var index = 0; index < this._children.length; index++) {
  10106. var item = this._children[index];
  10107. if (!predicate || predicate(item)) {
  10108. results.push(item);
  10109. }
  10110. if (!directDescendantsOnly) {
  10111. item._getDescendants(results, false, predicate);
  10112. }
  10113. }
  10114. };
  10115. /**
  10116. * Will return all nodes that have this node as ascendant.
  10117. * @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.
  10118. * @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.
  10119. * @return {BABYLON.Node[]} all children nodes of all types.
  10120. */
  10121. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10122. var results = [];
  10123. this._getDescendants(results, directDescendantsOnly, predicate);
  10124. return results;
  10125. };
  10126. /**
  10127. * Get all child-meshes of this node.
  10128. */
  10129. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10130. var results = [];
  10131. this._getDescendants(results, directDecendantsOnly, function (node) {
  10132. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10133. });
  10134. return results;
  10135. };
  10136. /**
  10137. * Get all direct children of this node.
  10138. */
  10139. Node.prototype.getChildren = function (predicate) {
  10140. return this.getDescendants(true, predicate);
  10141. };
  10142. Node.prototype._setReady = function (state) {
  10143. if (state === this._isReady) {
  10144. return;
  10145. }
  10146. if (!state) {
  10147. this._isReady = false;
  10148. return;
  10149. }
  10150. this._isReady = true;
  10151. if (this.onReady) {
  10152. this.onReady(this);
  10153. }
  10154. };
  10155. Node.prototype.getAnimationByName = function (name) {
  10156. for (var i = 0; i < this.animations.length; i++) {
  10157. var animation = this.animations[i];
  10158. if (animation.name === name) {
  10159. return animation;
  10160. }
  10161. }
  10162. return null;
  10163. };
  10164. Node.prototype.createAnimationRange = function (name, from, to) {
  10165. // check name not already in use
  10166. if (!this._ranges[name]) {
  10167. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10168. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10169. if (this.animations[i]) {
  10170. this.animations[i].createRange(name, from, to);
  10171. }
  10172. }
  10173. }
  10174. };
  10175. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10176. if (deleteFrames === void 0) { deleteFrames = true; }
  10177. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10178. if (this.animations[i]) {
  10179. this.animations[i].deleteRange(name, deleteFrames);
  10180. }
  10181. }
  10182. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10183. };
  10184. Node.prototype.getAnimationRange = function (name) {
  10185. return this._ranges[name];
  10186. };
  10187. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10188. var range = this.getAnimationRange(name);
  10189. if (!range) {
  10190. return null;
  10191. }
  10192. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10193. };
  10194. Node.prototype.serializeAnimationRanges = function () {
  10195. var serializationRanges = [];
  10196. for (var name in this._ranges) {
  10197. var range = {};
  10198. range.name = name;
  10199. range.from = this._ranges[name].from;
  10200. range.to = this._ranges[name].to;
  10201. serializationRanges.push(range);
  10202. }
  10203. return serializationRanges;
  10204. };
  10205. Node.prototype.dispose = function () {
  10206. this.parent = null;
  10207. // Callback
  10208. this.onDisposeObservable.notifyObservers(this);
  10209. this.onDisposeObservable.clear();
  10210. };
  10211. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10212. if (parsedNode.ranges) {
  10213. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10214. var data = parsedNode.ranges[index];
  10215. node.createAnimationRange(data.name, data.from, data.to);
  10216. }
  10217. }
  10218. };
  10219. return Node;
  10220. }());
  10221. __decorate([
  10222. BABYLON.serialize()
  10223. ], Node.prototype, "name", void 0);
  10224. __decorate([
  10225. BABYLON.serialize()
  10226. ], Node.prototype, "id", void 0);
  10227. __decorate([
  10228. BABYLON.serialize()
  10229. ], Node.prototype, "uniqueId", void 0);
  10230. __decorate([
  10231. BABYLON.serialize()
  10232. ], Node.prototype, "state", void 0);
  10233. __decorate([
  10234. BABYLON.serialize()
  10235. ], Node.prototype, "metadata", void 0);
  10236. BABYLON.Node = Node;
  10237. })(BABYLON || (BABYLON = {}));
  10238. //# sourceMappingURL=babylon.node.js.map
  10239. var BABYLON;
  10240. (function (BABYLON) {
  10241. var BoundingSphere = (function () {
  10242. function BoundingSphere(minimum, maximum) {
  10243. this.minimum = minimum;
  10244. this.maximum = maximum;
  10245. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10246. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10247. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10248. this.radius = distance * 0.5;
  10249. this.centerWorld = BABYLON.Vector3.Zero();
  10250. this._update(BABYLON.Matrix.Identity());
  10251. }
  10252. // Methods
  10253. BoundingSphere.prototype._update = function (world) {
  10254. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10255. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10256. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10257. };
  10258. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10259. for (var i = 0; i < 6; i++) {
  10260. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10261. return false;
  10262. }
  10263. return true;
  10264. };
  10265. BoundingSphere.prototype.intersectsPoint = function (point) {
  10266. var x = this.centerWorld.x - point.x;
  10267. var y = this.centerWorld.y - point.y;
  10268. var z = this.centerWorld.z - point.z;
  10269. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10270. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10271. return false;
  10272. return true;
  10273. };
  10274. // Statics
  10275. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10276. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10277. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10278. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10279. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10280. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10281. return false;
  10282. return true;
  10283. };
  10284. return BoundingSphere;
  10285. }());
  10286. BABYLON.BoundingSphere = BoundingSphere;
  10287. })(BABYLON || (BABYLON = {}));
  10288. //# sourceMappingURL=babylon.boundingSphere.js.map
  10289. var BABYLON;
  10290. (function (BABYLON) {
  10291. var BoundingBox = (function () {
  10292. function BoundingBox(minimum, maximum) {
  10293. this.minimum = minimum;
  10294. this.maximum = maximum;
  10295. this.vectors = new Array();
  10296. this.vectorsWorld = new Array();
  10297. // Bounding vectors
  10298. this.vectors.push(this.minimum.clone());
  10299. this.vectors.push(this.maximum.clone());
  10300. this.vectors.push(this.minimum.clone());
  10301. this.vectors[2].x = this.maximum.x;
  10302. this.vectors.push(this.minimum.clone());
  10303. this.vectors[3].y = this.maximum.y;
  10304. this.vectors.push(this.minimum.clone());
  10305. this.vectors[4].z = this.maximum.z;
  10306. this.vectors.push(this.maximum.clone());
  10307. this.vectors[5].z = this.minimum.z;
  10308. this.vectors.push(this.maximum.clone());
  10309. this.vectors[6].x = this.minimum.x;
  10310. this.vectors.push(this.maximum.clone());
  10311. this.vectors[7].y = this.minimum.y;
  10312. // OBB
  10313. this.center = this.maximum.add(this.minimum).scale(0.5);
  10314. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10315. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10316. // World
  10317. for (var index = 0; index < this.vectors.length; index++) {
  10318. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10319. }
  10320. this.minimumWorld = BABYLON.Vector3.Zero();
  10321. this.maximumWorld = BABYLON.Vector3.Zero();
  10322. this.centerWorld = BABYLON.Vector3.Zero();
  10323. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10324. this._update(BABYLON.Matrix.Identity());
  10325. }
  10326. // Methods
  10327. BoundingBox.prototype.getWorldMatrix = function () {
  10328. return this._worldMatrix;
  10329. };
  10330. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10331. this._worldMatrix.copyFrom(matrix);
  10332. return this;
  10333. };
  10334. BoundingBox.prototype._update = function (world) {
  10335. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10336. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10337. for (var index = 0; index < this.vectors.length; index++) {
  10338. var v = this.vectorsWorld[index];
  10339. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10340. if (v.x < this.minimumWorld.x)
  10341. this.minimumWorld.x = v.x;
  10342. if (v.y < this.minimumWorld.y)
  10343. this.minimumWorld.y = v.y;
  10344. if (v.z < this.minimumWorld.z)
  10345. this.minimumWorld.z = v.z;
  10346. if (v.x > this.maximumWorld.x)
  10347. this.maximumWorld.x = v.x;
  10348. if (v.y > this.maximumWorld.y)
  10349. this.maximumWorld.y = v.y;
  10350. if (v.z > this.maximumWorld.z)
  10351. this.maximumWorld.z = v.z;
  10352. }
  10353. // Extend
  10354. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10355. this.extendSizeWorld.scaleInPlace(0.5);
  10356. // OBB
  10357. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10358. this.centerWorld.scaleInPlace(0.5);
  10359. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10360. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10361. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10362. this._worldMatrix = world;
  10363. };
  10364. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10365. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10366. };
  10367. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10368. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10369. };
  10370. BoundingBox.prototype.intersectsPoint = function (point) {
  10371. var delta = -BABYLON.Epsilon;
  10372. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10373. return false;
  10374. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10375. return false;
  10376. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10377. return false;
  10378. return true;
  10379. };
  10380. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10381. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10382. };
  10383. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10384. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10385. return false;
  10386. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10387. return false;
  10388. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10389. return false;
  10390. return true;
  10391. };
  10392. // Statics
  10393. BoundingBox.Intersects = function (box0, box1) {
  10394. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10395. return false;
  10396. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10397. return false;
  10398. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10399. return false;
  10400. return true;
  10401. };
  10402. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10403. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10404. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10405. return (num <= (sphereRadius * sphereRadius));
  10406. };
  10407. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10408. for (var p = 0; p < 6; p++) {
  10409. for (var i = 0; i < 8; i++) {
  10410. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10411. return false;
  10412. }
  10413. }
  10414. }
  10415. return true;
  10416. };
  10417. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  10418. for (var p = 0; p < 6; p++) {
  10419. var inCount = 8;
  10420. for (var i = 0; i < 8; i++) {
  10421. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10422. --inCount;
  10423. }
  10424. else {
  10425. break;
  10426. }
  10427. }
  10428. if (inCount === 0)
  10429. return false;
  10430. }
  10431. return true;
  10432. };
  10433. return BoundingBox;
  10434. }());
  10435. BABYLON.BoundingBox = BoundingBox;
  10436. })(BABYLON || (BABYLON = {}));
  10437. //# sourceMappingURL=babylon.boundingBox.js.map
  10438. var BABYLON;
  10439. (function (BABYLON) {
  10440. var computeBoxExtents = function (axis, box) {
  10441. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  10442. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  10443. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  10444. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  10445. var r = r0 + r1 + r2;
  10446. return {
  10447. min: p - r,
  10448. max: p + r
  10449. };
  10450. };
  10451. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  10452. var axisOverlap = function (axis, box0, box1) {
  10453. var result0 = computeBoxExtents(axis, box0);
  10454. var result1 = computeBoxExtents(axis, box1);
  10455. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  10456. };
  10457. var BoundingInfo = (function () {
  10458. function BoundingInfo(minimum, maximum) {
  10459. this.minimum = minimum;
  10460. this.maximum = maximum;
  10461. this._isLocked = false;
  10462. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  10463. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  10464. }
  10465. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  10466. get: function () {
  10467. return this._isLocked;
  10468. },
  10469. set: function (value) {
  10470. this._isLocked = value;
  10471. },
  10472. enumerable: true,
  10473. configurable: true
  10474. });
  10475. // Methods
  10476. BoundingInfo.prototype.update = function (world) {
  10477. if (this._isLocked) {
  10478. return;
  10479. }
  10480. this.boundingBox._update(world);
  10481. this.boundingSphere._update(world);
  10482. };
  10483. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  10484. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  10485. return false;
  10486. return this.boundingBox.isInFrustum(frustumPlanes);
  10487. };
  10488. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10489. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  10490. };
  10491. BoundingInfo.prototype._checkCollision = function (collider) {
  10492. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  10493. };
  10494. BoundingInfo.prototype.intersectsPoint = function (point) {
  10495. if (!this.boundingSphere.centerWorld) {
  10496. return false;
  10497. }
  10498. if (!this.boundingSphere.intersectsPoint(point)) {
  10499. return false;
  10500. }
  10501. if (!this.boundingBox.intersectsPoint(point)) {
  10502. return false;
  10503. }
  10504. return true;
  10505. };
  10506. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  10507. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  10508. return false;
  10509. }
  10510. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  10511. return false;
  10512. }
  10513. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  10514. return false;
  10515. }
  10516. if (!precise) {
  10517. return true;
  10518. }
  10519. var box0 = this.boundingBox;
  10520. var box1 = boundingInfo.boundingBox;
  10521. if (!axisOverlap(box0.directions[0], box0, box1))
  10522. return false;
  10523. if (!axisOverlap(box0.directions[1], box0, box1))
  10524. return false;
  10525. if (!axisOverlap(box0.directions[2], box0, box1))
  10526. return false;
  10527. if (!axisOverlap(box1.directions[0], box0, box1))
  10528. return false;
  10529. if (!axisOverlap(box1.directions[1], box0, box1))
  10530. return false;
  10531. if (!axisOverlap(box1.directions[2], box0, box1))
  10532. return false;
  10533. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  10534. return false;
  10535. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  10536. return false;
  10537. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  10538. return false;
  10539. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  10540. return false;
  10541. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  10542. return false;
  10543. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  10544. return false;
  10545. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  10546. return false;
  10547. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  10548. return false;
  10549. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  10550. return false;
  10551. return true;
  10552. };
  10553. return BoundingInfo;
  10554. }());
  10555. BABYLON.BoundingInfo = BoundingInfo;
  10556. })(BABYLON || (BABYLON = {}));
  10557. //# sourceMappingURL=babylon.boundingInfo.js.map
  10558. var BABYLON;
  10559. (function (BABYLON) {
  10560. var AbstractMesh = (function (_super) {
  10561. __extends(AbstractMesh, _super);
  10562. // Constructor
  10563. function AbstractMesh(name, scene) {
  10564. var _this = _super.call(this, name, scene) || this;
  10565. _this._facetNb = 0; // facet number
  10566. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  10567. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  10568. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  10569. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  10570. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  10571. _this._subDiv = {
  10572. max: 1,
  10573. X: 1,
  10574. Y: 1,
  10575. Z: 1
  10576. };
  10577. // Events
  10578. /**
  10579. * An event triggered when this mesh collides with another one
  10580. * @type {BABYLON.Observable}
  10581. */
  10582. _this.onCollideObservable = new BABYLON.Observable();
  10583. /**
  10584. * An event triggered when the collision's position changes
  10585. * @type {BABYLON.Observable}
  10586. */
  10587. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10588. /**
  10589. * An event triggered after the world matrix is updated
  10590. * @type {BABYLON.Observable}
  10591. */
  10592. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10593. // Properties
  10594. _this.definedFacingForward = true; // orientation for POV movement & rotation
  10595. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10596. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10597. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  10598. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10599. _this.visibility = 1.0;
  10600. _this.alphaIndex = Number.MAX_VALUE;
  10601. _this.infiniteDistance = false;
  10602. _this.isVisible = true;
  10603. _this.isPickable = true;
  10604. _this.showBoundingBox = false;
  10605. _this.showSubMeshesBoundingBox = false;
  10606. _this.isBlocker = false;
  10607. _this.renderingGroupId = 0;
  10608. _this._receiveShadows = false;
  10609. _this.renderOutline = false;
  10610. _this.outlineColor = BABYLON.Color3.Red();
  10611. _this.outlineWidth = 0.02;
  10612. _this.renderOverlay = false;
  10613. _this.overlayColor = BABYLON.Color3.Red();
  10614. _this.overlayAlpha = 0.5;
  10615. _this._hasVertexAlpha = false;
  10616. _this._useVertexColors = true;
  10617. _this._computeBonesUsingShaders = true;
  10618. _this._numBoneInfluencers = 4;
  10619. _this._applyFog = true;
  10620. _this.scalingDeterminant = 1;
  10621. _this.useOctreeForRenderingSelection = true;
  10622. _this.useOctreeForPicking = true;
  10623. _this.useOctreeForCollisions = true;
  10624. _this.layerMask = 0x0FFFFFFF;
  10625. /**
  10626. * True if the mesh must be rendered in any case.
  10627. */
  10628. _this.alwaysSelectAsActiveMesh = false;
  10629. // Collisions
  10630. _this._checkCollisions = false;
  10631. _this._collisionMask = -1;
  10632. _this._collisionGroup = -1;
  10633. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10634. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10635. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10636. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10637. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10638. // Edges
  10639. _this.edgesWidth = 1;
  10640. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10641. // Cache
  10642. _this._localWorld = BABYLON.Matrix.Zero();
  10643. _this._worldMatrix = BABYLON.Matrix.Zero();
  10644. _this._absolutePosition = BABYLON.Vector3.Zero();
  10645. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10646. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10647. _this._isDirty = false;
  10648. _this._pivotMatrix = BABYLON.Matrix.Identity();
  10649. _this._isDisposed = false;
  10650. _this._renderId = 0;
  10651. _this._intersectionsInProgress = new Array();
  10652. _this._isWorldMatrixFrozen = false;
  10653. _this._unIndexed = false;
  10654. _this._lightSources = new Array();
  10655. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10656. if (collidedMesh === void 0) { collidedMesh = null; }
  10657. //TODO move this to the collision coordinator!
  10658. if (_this.getScene().workerCollisions)
  10659. newPosition.multiplyInPlace(_this._collider.radius);
  10660. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10661. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10662. _this.position.addInPlace(_this._diffPositionForCollisions);
  10663. }
  10664. if (collidedMesh) {
  10665. _this.onCollideObservable.notifyObservers(collidedMesh);
  10666. }
  10667. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10668. };
  10669. _this.getScene().addMesh(_this);
  10670. _this._resyncLightSources();
  10671. return _this;
  10672. }
  10673. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10674. get: function () {
  10675. return AbstractMesh._BILLBOARDMODE_NONE;
  10676. },
  10677. enumerable: true,
  10678. configurable: true
  10679. });
  10680. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10681. get: function () {
  10682. return AbstractMesh._BILLBOARDMODE_X;
  10683. },
  10684. enumerable: true,
  10685. configurable: true
  10686. });
  10687. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10688. get: function () {
  10689. return AbstractMesh._BILLBOARDMODE_Y;
  10690. },
  10691. enumerable: true,
  10692. configurable: true
  10693. });
  10694. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10695. get: function () {
  10696. return AbstractMesh._BILLBOARDMODE_Z;
  10697. },
  10698. enumerable: true,
  10699. configurable: true
  10700. });
  10701. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10702. get: function () {
  10703. return AbstractMesh._BILLBOARDMODE_ALL;
  10704. },
  10705. enumerable: true,
  10706. configurable: true
  10707. });
  10708. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  10709. /**
  10710. * Read-only : the number of facets in the mesh
  10711. */
  10712. get: function () {
  10713. return this._facetNb;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  10719. /**
  10720. * The number (integer) of subdivisions per axis in the partioning space
  10721. */
  10722. get: function () {
  10723. return this._partitioningSubdivisions;
  10724. },
  10725. set: function (nb) {
  10726. this._partitioningSubdivisions = nb;
  10727. },
  10728. enumerable: true,
  10729. configurable: true
  10730. });
  10731. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  10732. /**
  10733. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  10734. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  10735. */
  10736. get: function () {
  10737. return this._partitioningBBoxRatio;
  10738. },
  10739. set: function (ratio) {
  10740. this._partitioningBBoxRatio = ratio;
  10741. },
  10742. enumerable: true,
  10743. configurable: true
  10744. });
  10745. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  10746. /**
  10747. * Read-only boolean : is the feature facetData enabled ?
  10748. */
  10749. get: function () {
  10750. return this._facetDataEnabled;
  10751. },
  10752. enumerable: true,
  10753. configurable: true
  10754. });
  10755. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10756. set: function (callback) {
  10757. if (this._onCollideObserver) {
  10758. this.onCollideObservable.remove(this._onCollideObserver);
  10759. }
  10760. this._onCollideObserver = this.onCollideObservable.add(callback);
  10761. },
  10762. enumerable: true,
  10763. configurable: true
  10764. });
  10765. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10766. set: function (callback) {
  10767. if (this._onCollisionPositionChangeObserver) {
  10768. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10769. }
  10770. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10771. },
  10772. enumerable: true,
  10773. configurable: true
  10774. });
  10775. Object.defineProperty(AbstractMesh.prototype, "material", {
  10776. get: function () {
  10777. return this._material;
  10778. },
  10779. set: function (value) {
  10780. if (this._material === value) {
  10781. return;
  10782. }
  10783. this._material = value;
  10784. if (!this.subMeshes) {
  10785. return;
  10786. }
  10787. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  10788. var subMesh = _a[_i];
  10789. subMesh.setEffect(null);
  10790. }
  10791. },
  10792. enumerable: true,
  10793. configurable: true
  10794. });
  10795. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  10796. get: function () {
  10797. return this._receiveShadows;
  10798. },
  10799. set: function (value) {
  10800. if (this._receiveShadows === value) {
  10801. return;
  10802. }
  10803. this._receiveShadows = value;
  10804. this._markSubMeshesAsLightDirty();
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  10810. get: function () {
  10811. return this._hasVertexAlpha;
  10812. },
  10813. set: function (value) {
  10814. if (this._hasVertexAlpha === value) {
  10815. return;
  10816. }
  10817. this._hasVertexAlpha = value;
  10818. this._markSubMeshesAsAttributesDirty();
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  10824. get: function () {
  10825. return this._useVertexColors;
  10826. },
  10827. set: function (value) {
  10828. if (this._useVertexColors === value) {
  10829. return;
  10830. }
  10831. this._useVertexColors = value;
  10832. this._markSubMeshesAsAttributesDirty();
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  10838. get: function () {
  10839. return this._computeBonesUsingShaders;
  10840. },
  10841. set: function (value) {
  10842. if (this._computeBonesUsingShaders === value) {
  10843. return;
  10844. }
  10845. this._computeBonesUsingShaders = value;
  10846. this._markSubMeshesAsAttributesDirty();
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  10852. get: function () {
  10853. return this._numBoneInfluencers;
  10854. },
  10855. set: function (value) {
  10856. if (this._numBoneInfluencers === value) {
  10857. return;
  10858. }
  10859. this._numBoneInfluencers = value;
  10860. this._markSubMeshesAsAttributesDirty();
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  10866. get: function () {
  10867. return this._applyFog;
  10868. },
  10869. set: function (value) {
  10870. if (this._applyFog === value) {
  10871. return;
  10872. }
  10873. this._applyFog = value;
  10874. this._markSubMeshesAsMiscDirty();
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  10880. get: function () {
  10881. return this._collisionMask;
  10882. },
  10883. set: function (mask) {
  10884. this._collisionMask = !isNaN(mask) ? mask : -1;
  10885. },
  10886. enumerable: true,
  10887. configurable: true
  10888. });
  10889. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  10890. get: function () {
  10891. return this._collisionGroup;
  10892. },
  10893. set: function (mask) {
  10894. this._collisionGroup = !isNaN(mask) ? mask : -1;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10900. get: function () {
  10901. return this._skeleton;
  10902. },
  10903. set: function (value) {
  10904. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10905. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10906. }
  10907. if (value && value.needInitialSkinMatrix) {
  10908. value._registerMeshWithPoseMatrix(this);
  10909. }
  10910. this._skeleton = value;
  10911. if (!this._skeleton) {
  10912. this._bonesTransformMatrices = null;
  10913. }
  10914. this._markSubMeshesAsAttributesDirty();
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. /**
  10920. * Returns the string "AbstractMesh"
  10921. */
  10922. AbstractMesh.prototype.getClassName = function () {
  10923. return "AbstractMesh";
  10924. };
  10925. /**
  10926. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10927. */
  10928. AbstractMesh.prototype.toString = function (fullDetails) {
  10929. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10930. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10931. if (this._skeleton) {
  10932. ret += ", skeleton: " + this._skeleton.name;
  10933. }
  10934. if (fullDetails) {
  10935. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10936. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10937. }
  10938. return ret;
  10939. };
  10940. AbstractMesh.prototype._resyncLightSources = function () {
  10941. this._lightSources.length = 0;
  10942. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  10943. var light = _a[_i];
  10944. if (!light.isEnabled()) {
  10945. continue;
  10946. }
  10947. if (light.canAffectMesh(this)) {
  10948. this._lightSources.push(light);
  10949. }
  10950. }
  10951. this._markSubMeshesAsLightDirty();
  10952. };
  10953. AbstractMesh.prototype._resyncLighSource = function (light) {
  10954. var isIn = light.isEnabled() && light.canAffectMesh(this);
  10955. var index = this._lightSources.indexOf(light);
  10956. if (index === -1) {
  10957. if (!isIn) {
  10958. return;
  10959. }
  10960. this._lightSources.push(light);
  10961. }
  10962. else {
  10963. if (isIn) {
  10964. return;
  10965. }
  10966. this._lightSources.splice(index, 1);
  10967. }
  10968. this._markSubMeshesAsLightDirty();
  10969. };
  10970. AbstractMesh.prototype._removeLightSource = function (light) {
  10971. var index = this._lightSources.indexOf(light);
  10972. if (index === -1) {
  10973. return;
  10974. }
  10975. this._lightSources.splice(index, 1);
  10976. };
  10977. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  10978. if (!this.subMeshes) {
  10979. return;
  10980. }
  10981. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  10982. var subMesh = _a[_i];
  10983. if (subMesh._materialDefines) {
  10984. func(subMesh._materialDefines);
  10985. }
  10986. }
  10987. };
  10988. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  10989. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  10990. };
  10991. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  10992. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  10993. };
  10994. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  10995. if (!this.subMeshes) {
  10996. return;
  10997. }
  10998. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  10999. var subMesh = _a[_i];
  11000. var material = subMesh.getMaterial();
  11001. if (material) {
  11002. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11003. }
  11004. }
  11005. };
  11006. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11007. /**
  11008. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11009. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11010. * Default : (0.0, 0.0, 0.0)
  11011. */
  11012. get: function () {
  11013. return this._rotation;
  11014. },
  11015. set: function (newRotation) {
  11016. this._rotation = newRotation;
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11022. /**
  11023. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11024. * Default : (1.0, 1.0, 1.0)
  11025. */
  11026. get: function () {
  11027. return this._scaling;
  11028. },
  11029. set: function (newScaling) {
  11030. this._scaling = newScaling;
  11031. if (this.physicsImpostor) {
  11032. this.physicsImpostor.forceUpdate();
  11033. }
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11039. /**
  11040. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11041. * It's null by default.
  11042. * 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)
  11043. */
  11044. get: function () {
  11045. return this._rotationQuaternion;
  11046. },
  11047. set: function (quaternion) {
  11048. this._rotationQuaternion = quaternion;
  11049. //reset the rotation vector.
  11050. if (quaternion && this.rotation.length()) {
  11051. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11052. }
  11053. },
  11054. enumerable: true,
  11055. configurable: true
  11056. });
  11057. // Methods
  11058. /**
  11059. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11060. * Returns the AbstractMesh.
  11061. */
  11062. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11063. this._poseMatrix.copyFrom(matrix);
  11064. return this;
  11065. };
  11066. /**
  11067. * Returns the mesh Pose matrix.
  11068. * Returned object : Matrix
  11069. */
  11070. AbstractMesh.prototype.getPoseMatrix = function () {
  11071. return this._poseMatrix;
  11072. };
  11073. /**
  11074. * Disables the mesh edger rendering mode.
  11075. * Returns the AbstractMesh.
  11076. */
  11077. AbstractMesh.prototype.disableEdgesRendering = function () {
  11078. if (this._edgesRenderer !== undefined) {
  11079. this._edgesRenderer.dispose();
  11080. this._edgesRenderer = undefined;
  11081. }
  11082. return this;
  11083. };
  11084. /**
  11085. * Enables the edge rendering mode on the mesh.
  11086. * This mode makes the mesh edges visible.
  11087. * Returns the AbstractMesh.
  11088. */
  11089. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11090. if (epsilon === void 0) { epsilon = 0.95; }
  11091. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11092. this.disableEdgesRendering();
  11093. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11094. return this;
  11095. };
  11096. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11097. /**
  11098. * Returns true if the mesh is blocked. Used by the class Mesh.
  11099. * Returns the boolean `false` by default.
  11100. */
  11101. get: function () {
  11102. return false;
  11103. },
  11104. enumerable: true,
  11105. configurable: true
  11106. });
  11107. /**
  11108. * Returns the mesh itself by default, used by the class Mesh.
  11109. * Returned type : AbstractMesh
  11110. */
  11111. AbstractMesh.prototype.getLOD = function (camera) {
  11112. return this;
  11113. };
  11114. /**
  11115. * Returns 0 by default, used by the class Mesh.
  11116. * Returns an integer.
  11117. */
  11118. AbstractMesh.prototype.getTotalVertices = function () {
  11119. return 0;
  11120. };
  11121. /**
  11122. * Returns null by default, used by the class Mesh.
  11123. * Returned type : integer array
  11124. */
  11125. AbstractMesh.prototype.getIndices = function () {
  11126. return null;
  11127. };
  11128. /**
  11129. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11130. * Returned type : float array or Float32Array
  11131. */
  11132. AbstractMesh.prototype.getVerticesData = function (kind) {
  11133. return null;
  11134. };
  11135. /**
  11136. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11137. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11138. * The `data` are either a numeric array either a Float32Array.
  11139. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11140. * 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).
  11141. * Note that a new underlying VertexBuffer object is created each call.
  11142. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11143. *
  11144. * Possible `kind` values :
  11145. * - BABYLON.VertexBuffer.PositionKind
  11146. * - BABYLON.VertexBuffer.UVKind
  11147. * - BABYLON.VertexBuffer.UV2Kind
  11148. * - BABYLON.VertexBuffer.UV3Kind
  11149. * - BABYLON.VertexBuffer.UV4Kind
  11150. * - BABYLON.VertexBuffer.UV5Kind
  11151. * - BABYLON.VertexBuffer.UV6Kind
  11152. * - BABYLON.VertexBuffer.ColorKind
  11153. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11154. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11155. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11156. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11157. *
  11158. * Returns the Mesh.
  11159. */
  11160. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11161. return null;
  11162. };
  11163. /**
  11164. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11165. * If the mesh has no geometry, it is simply returned as it is.
  11166. * The `data` are either a numeric array either a Float32Array.
  11167. * No new underlying VertexBuffer object is created.
  11168. * 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.
  11169. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11170. *
  11171. * Possible `kind` values :
  11172. * - BABYLON.VertexBuffer.PositionKind
  11173. * - BABYLON.VertexBuffer.UVKind
  11174. * - BABYLON.VertexBuffer.UV2Kind
  11175. * - BABYLON.VertexBuffer.UV3Kind
  11176. * - BABYLON.VertexBuffer.UV4Kind
  11177. * - BABYLON.VertexBuffer.UV5Kind
  11178. * - BABYLON.VertexBuffer.UV6Kind
  11179. * - BABYLON.VertexBuffer.ColorKind
  11180. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11181. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11182. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11183. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11184. *
  11185. * Returns the Mesh.
  11186. */
  11187. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11188. return null;
  11189. };
  11190. /**
  11191. * Sets the mesh indices.
  11192. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11193. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11194. * This method creates a new index buffer each call.
  11195. * Returns the Mesh.
  11196. */
  11197. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11198. return null;
  11199. };
  11200. /** Returns false by default, used by the class Mesh.
  11201. * Returns a boolean
  11202. */
  11203. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11204. return false;
  11205. };
  11206. /**
  11207. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11208. * Returns a BoundingInfo
  11209. */
  11210. AbstractMesh.prototype.getBoundingInfo = function () {
  11211. if (this._masterMesh) {
  11212. return this._masterMesh.getBoundingInfo();
  11213. }
  11214. if (!this._boundingInfo) {
  11215. this._updateBoundingInfo();
  11216. }
  11217. return this._boundingInfo;
  11218. };
  11219. /**
  11220. * Sets a mesh new object BoundingInfo.
  11221. * Returns the AbstractMesh.
  11222. */
  11223. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11224. this._boundingInfo = boundingInfo;
  11225. return this;
  11226. };
  11227. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11228. get: function () {
  11229. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11230. },
  11231. enumerable: true,
  11232. configurable: true
  11233. });
  11234. AbstractMesh.prototype._preActivate = function () {
  11235. };
  11236. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11237. };
  11238. AbstractMesh.prototype._activate = function (renderId) {
  11239. this._renderId = renderId;
  11240. };
  11241. /**
  11242. * Returns the last update of the World matrix
  11243. * Returns a Matrix.
  11244. */
  11245. AbstractMesh.prototype.getWorldMatrix = function () {
  11246. if (this._masterMesh) {
  11247. return this._masterMesh.getWorldMatrix();
  11248. }
  11249. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11250. this.computeWorldMatrix();
  11251. }
  11252. return this._worldMatrix;
  11253. };
  11254. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11255. /**
  11256. * Returns directly the last state of the mesh World matrix.
  11257. * A Matrix is returned.
  11258. */
  11259. get: function () {
  11260. return this._worldMatrix;
  11261. },
  11262. enumerable: true,
  11263. configurable: true
  11264. });
  11265. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11266. /**
  11267. * Returns the current mesh absolute position.
  11268. * Retuns a Vector3.
  11269. */
  11270. get: function () {
  11271. return this._absolutePosition;
  11272. },
  11273. enumerable: true,
  11274. configurable: true
  11275. });
  11276. /**
  11277. * Prevents the World matrix to be computed any longer.
  11278. * Returns the AbstractMesh.
  11279. */
  11280. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11281. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11282. this.computeWorldMatrix(true);
  11283. this._isWorldMatrixFrozen = true;
  11284. return this;
  11285. };
  11286. /**
  11287. * Allows back the World matrix computation.
  11288. * Returns the AbstractMesh.
  11289. */
  11290. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11291. this._isWorldMatrixFrozen = false;
  11292. this.computeWorldMatrix(true);
  11293. return this;
  11294. };
  11295. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11296. /**
  11297. * True if the World matrix has been frozen.
  11298. * Returns a boolean.
  11299. */
  11300. get: function () {
  11301. return this._isWorldMatrixFrozen;
  11302. },
  11303. enumerable: true,
  11304. configurable: true
  11305. });
  11306. /**
  11307. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11308. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11309. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11310. * The passed axis is also normalized.
  11311. * Returns the AbstractMesh.
  11312. */
  11313. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11314. axis.normalize();
  11315. if (!this.rotationQuaternion) {
  11316. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11317. this.rotation = BABYLON.Vector3.Zero();
  11318. }
  11319. var rotationQuaternion;
  11320. if (!space || space === BABYLON.Space.LOCAL) {
  11321. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11322. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11323. }
  11324. else {
  11325. if (this.parent) {
  11326. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11327. invertParentWorldMatrix.invert();
  11328. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11329. }
  11330. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11331. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11332. }
  11333. return this;
  11334. };
  11335. /**
  11336. * Translates the mesh along the axis vector for the passed distance in the given space.
  11337. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11338. * Returns the AbstractMesh.
  11339. */
  11340. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11341. var displacementVector = axis.scale(distance);
  11342. if (!space || space === BABYLON.Space.LOCAL) {
  11343. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11344. this.setPositionWithLocalVector(tempV3);
  11345. }
  11346. else {
  11347. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11348. }
  11349. return this;
  11350. };
  11351. /**
  11352. * Adds a rotation step to the mesh current rotation.
  11353. * x, y, z are Euler angles expressed in radians.
  11354. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11355. * This means this rotation is made in the mesh local space only.
  11356. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11357. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11358. * ```javascript
  11359. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11360. * ```
  11361. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11362. * 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.
  11363. * Returns the AbstractMesh.
  11364. */
  11365. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11366. var rotationQuaternion;
  11367. if (this.rotationQuaternion) {
  11368. rotationQuaternion = this.rotationQuaternion;
  11369. }
  11370. else {
  11371. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11372. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11373. }
  11374. var accumulation = BABYLON.Tmp.Quaternion[0];
  11375. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11376. rotationQuaternion.multiplyInPlace(accumulation);
  11377. if (!this.rotationQuaternion) {
  11378. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11379. }
  11380. return this;
  11381. };
  11382. /**
  11383. * Retuns the mesh absolute position in the World.
  11384. * Returns a Vector3.
  11385. */
  11386. AbstractMesh.prototype.getAbsolutePosition = function () {
  11387. this.computeWorldMatrix();
  11388. return this._absolutePosition;
  11389. };
  11390. /**
  11391. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11392. * Returns the AbstractMesh.
  11393. */
  11394. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11395. if (!absolutePosition) {
  11396. return;
  11397. }
  11398. var absolutePositionX;
  11399. var absolutePositionY;
  11400. var absolutePositionZ;
  11401. if (absolutePosition.x === undefined) {
  11402. if (arguments.length < 3) {
  11403. return;
  11404. }
  11405. absolutePositionX = arguments[0];
  11406. absolutePositionY = arguments[1];
  11407. absolutePositionZ = arguments[2];
  11408. }
  11409. else {
  11410. absolutePositionX = absolutePosition.x;
  11411. absolutePositionY = absolutePosition.y;
  11412. absolutePositionZ = absolutePosition.z;
  11413. }
  11414. if (this.parent) {
  11415. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11416. invertParentWorldMatrix.invert();
  11417. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  11418. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  11419. }
  11420. else {
  11421. this.position.x = absolutePositionX;
  11422. this.position.y = absolutePositionY;
  11423. this.position.z = absolutePositionZ;
  11424. }
  11425. return this;
  11426. };
  11427. // ================================== Point of View Movement =================================
  11428. /**
  11429. * Perform relative position change from the point of view of behind the front of the mesh.
  11430. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11431. * Supports definition of mesh facing forward or backward.
  11432. * @param {number} amountRight
  11433. * @param {number} amountUp
  11434. * @param {number} amountForward
  11435. *
  11436. * Returns the AbstractMesh.
  11437. */
  11438. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  11439. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  11440. return this;
  11441. };
  11442. /**
  11443. * Calculate relative position change from the point of view of behind the front of the mesh.
  11444. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11445. * Supports definition of mesh facing forward or backward.
  11446. * @param {number} amountRight
  11447. * @param {number} amountUp
  11448. * @param {number} amountForward
  11449. *
  11450. * Returns a new Vector3.
  11451. */
  11452. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  11453. var rotMatrix = new BABYLON.Matrix();
  11454. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11455. rotQuaternion.toRotationMatrix(rotMatrix);
  11456. var translationDelta = BABYLON.Vector3.Zero();
  11457. var defForwardMult = this.definedFacingForward ? -1 : 1;
  11458. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  11459. return translationDelta;
  11460. };
  11461. // ================================== Point of View Rotation =================================
  11462. /**
  11463. * Perform relative rotation change from the point of view of behind the front of the mesh.
  11464. * Supports definition of mesh facing forward or backward.
  11465. * @param {number} flipBack
  11466. * @param {number} twirlClockwise
  11467. * @param {number} tiltRight
  11468. *
  11469. * Returns the AbstractMesh.
  11470. */
  11471. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11472. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  11473. return this;
  11474. };
  11475. /**
  11476. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  11477. * Supports definition of mesh facing forward or backward.
  11478. * @param {number} flipBack
  11479. * @param {number} twirlClockwise
  11480. * @param {number} tiltRight
  11481. *
  11482. * Returns a new Vector3.
  11483. */
  11484. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11485. var defForwardMult = this.definedFacingForward ? 1 : -1;
  11486. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  11487. };
  11488. /**
  11489. * Sets a new pivot matrix to the mesh.
  11490. * Returns the AbstractMesh.
  11491. */
  11492. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  11493. this._pivotMatrix = matrix;
  11494. this._cache.pivotMatrixUpdated = true;
  11495. return this;
  11496. };
  11497. /**
  11498. * Returns the mesh pivot matrix.
  11499. * Default : Identity.
  11500. * A Matrix is returned.
  11501. */
  11502. AbstractMesh.prototype.getPivotMatrix = function () {
  11503. return this._pivotMatrix;
  11504. };
  11505. AbstractMesh.prototype._isSynchronized = function () {
  11506. if (this._isDirty) {
  11507. return false;
  11508. }
  11509. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  11510. return false;
  11511. if (this._cache.pivotMatrixUpdated) {
  11512. return false;
  11513. }
  11514. if (this.infiniteDistance) {
  11515. return false;
  11516. }
  11517. if (!this._cache.position.equals(this.position))
  11518. return false;
  11519. if (this.rotationQuaternion) {
  11520. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  11521. return false;
  11522. }
  11523. if (!this._cache.rotation.equals(this.rotation))
  11524. return false;
  11525. if (!this._cache.scaling.equals(this.scaling))
  11526. return false;
  11527. return true;
  11528. };
  11529. AbstractMesh.prototype._initCache = function () {
  11530. _super.prototype._initCache.call(this);
  11531. this._cache.localMatrixUpdated = false;
  11532. this._cache.position = BABYLON.Vector3.Zero();
  11533. this._cache.scaling = BABYLON.Vector3.Zero();
  11534. this._cache.rotation = BABYLON.Vector3.Zero();
  11535. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  11536. this._cache.billboardMode = -1;
  11537. };
  11538. AbstractMesh.prototype.markAsDirty = function (property) {
  11539. if (property === "rotation") {
  11540. this.rotationQuaternion = null;
  11541. }
  11542. this._currentRenderId = Number.MAX_VALUE;
  11543. this._isDirty = true;
  11544. return this;
  11545. };
  11546. /**
  11547. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  11548. * Returns the AbstractMesh.
  11549. */
  11550. AbstractMesh.prototype._updateBoundingInfo = function () {
  11551. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  11552. this._boundingInfo.update(this.worldMatrixFromCache);
  11553. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11554. return this;
  11555. };
  11556. /**
  11557. * Update a mesh's children BoundingInfo objects only.
  11558. * Returns the AbstractMesh.
  11559. */
  11560. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  11561. if (!this.subMeshes) {
  11562. return;
  11563. }
  11564. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  11565. var subMesh = this.subMeshes[subIndex];
  11566. if (!subMesh.IsGlobal) {
  11567. subMesh.updateBoundingInfo(matrix);
  11568. }
  11569. }
  11570. return this;
  11571. };
  11572. /**
  11573. * Computes the mesh World matrix and returns it.
  11574. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  11575. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  11576. * If the parameter `force`is set to `true`, the actual computation is done.
  11577. * Returns the mesh World Matrix.
  11578. */
  11579. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  11580. if (this._isWorldMatrixFrozen) {
  11581. return this._worldMatrix;
  11582. }
  11583. if (!force && this.isSynchronized(true)) {
  11584. this._currentRenderId = this.getScene().getRenderId();
  11585. return this._worldMatrix;
  11586. }
  11587. this._cache.position.copyFrom(this.position);
  11588. this._cache.scaling.copyFrom(this.scaling);
  11589. this._cache.pivotMatrixUpdated = false;
  11590. this._cache.billboardMode = this.billboardMode;
  11591. this._currentRenderId = this.getScene().getRenderId();
  11592. this._isDirty = false;
  11593. // Scaling
  11594. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  11595. // Rotation
  11596. //rotate, if quaternion is set and rotation was used
  11597. if (this.rotationQuaternion) {
  11598. var len = this.rotation.length();
  11599. if (len) {
  11600. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  11601. this.rotation.copyFromFloats(0, 0, 0);
  11602. }
  11603. }
  11604. if (this.rotationQuaternion) {
  11605. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  11606. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  11607. }
  11608. else {
  11609. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  11610. this._cache.rotation.copyFrom(this.rotation);
  11611. }
  11612. // Translation
  11613. if (this.infiniteDistance && !this.parent) {
  11614. var camera = this.getScene().activeCamera;
  11615. if (camera) {
  11616. var cameraWorldMatrix = camera.getWorldMatrix();
  11617. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  11618. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  11619. }
  11620. }
  11621. else {
  11622. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  11623. }
  11624. // Composing transformations
  11625. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  11626. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11627. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  11628. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  11629. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  11630. // Need to decompose each rotation here
  11631. var currentPosition = BABYLON.Tmp.Vector3[3];
  11632. if (this.parent && this.parent.getWorldMatrix) {
  11633. if (this._meshToBoneReferal) {
  11634. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11635. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  11636. }
  11637. else {
  11638. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  11639. }
  11640. }
  11641. else {
  11642. currentPosition.copyFrom(this.position);
  11643. }
  11644. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  11645. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  11646. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  11647. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  11648. }
  11649. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  11650. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  11651. }
  11652. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  11653. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  11654. }
  11655. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  11656. }
  11657. else {
  11658. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  11659. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  11660. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  11661. }
  11662. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  11663. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11664. }
  11665. // Local world
  11666. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  11667. // Parent
  11668. if (this.parent && this.parent.getWorldMatrix) {
  11669. this._markSyncedWithParent();
  11670. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  11671. if (this._meshToBoneReferal) {
  11672. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11673. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  11674. }
  11675. else {
  11676. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  11677. }
  11678. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  11679. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  11680. this._worldMatrix.copyFrom(this._localWorld);
  11681. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  11682. }
  11683. else {
  11684. if (this._meshToBoneReferal) {
  11685. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11686. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  11687. }
  11688. else {
  11689. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  11690. }
  11691. }
  11692. }
  11693. else {
  11694. this._worldMatrix.copyFrom(this._localWorld);
  11695. }
  11696. // Bounding info
  11697. this._updateBoundingInfo();
  11698. // Absolute position
  11699. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  11700. // Callbacks
  11701. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  11702. if (!this._poseMatrix) {
  11703. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  11704. }
  11705. return this._worldMatrix;
  11706. };
  11707. /**
  11708. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  11709. * @param func: callback function to add
  11710. *
  11711. * Returns the AbstractMesh.
  11712. */
  11713. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  11714. this.onAfterWorldMatrixUpdateObservable.add(func);
  11715. return this;
  11716. };
  11717. /**
  11718. * Removes a registered callback function.
  11719. * Returns the AbstractMesh.
  11720. */
  11721. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  11722. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  11723. return this;
  11724. };
  11725. /**
  11726. * Sets the mesh position in its local space.
  11727. * Returns the AbstractMesh.
  11728. */
  11729. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  11730. this.computeWorldMatrix();
  11731. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  11732. return this;
  11733. };
  11734. /**
  11735. * Returns the mesh position in the local space from the current World matrix values.
  11736. * Returns a new Vector3.
  11737. */
  11738. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  11739. this.computeWorldMatrix();
  11740. var invLocalWorldMatrix = this._localWorld.clone();
  11741. invLocalWorldMatrix.invert();
  11742. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  11743. };
  11744. /**
  11745. * Translates the mesh along the passed Vector3 in its local space.
  11746. * Returns the AbstractMesh.
  11747. */
  11748. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  11749. this.computeWorldMatrix(true);
  11750. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  11751. return this;
  11752. };
  11753. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  11754. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  11755. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  11756. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  11757. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  11758. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  11759. /// <returns>Mesh oriented towards targetMesh</returns>
  11760. if (yawCor === void 0) { yawCor = 0; }
  11761. if (pitchCor === void 0) { pitchCor = 0; }
  11762. if (rollCor === void 0) { rollCor = 0; }
  11763. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11764. var dv = AbstractMesh._lookAtVectorCache;
  11765. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  11766. targetPoint.subtractToRef(pos, dv);
  11767. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  11768. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  11769. var pitch = Math.atan2(dv.y, len);
  11770. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  11771. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  11772. return this;
  11773. };
  11774. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  11775. this._meshToBoneReferal = affectedMesh;
  11776. this.parent = bone;
  11777. if (bone.getWorldMatrix().determinant() < 0) {
  11778. this.scalingDeterminant *= -1;
  11779. }
  11780. return this;
  11781. };
  11782. AbstractMesh.prototype.detachFromBone = function () {
  11783. if (this.parent.getWorldMatrix().determinant() < 0) {
  11784. this.scalingDeterminant *= -1;
  11785. }
  11786. this._meshToBoneReferal = null;
  11787. this.parent = null;
  11788. return this;
  11789. };
  11790. /**
  11791. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  11792. * A mesh is in the frustum if its bounding box intersects the frustum.
  11793. * Boolean returned.
  11794. */
  11795. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11796. return this._boundingInfo.isInFrustum(frustumPlanes);
  11797. };
  11798. /**
  11799. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  11800. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  11801. * Boolean returned.
  11802. */
  11803. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11804. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11805. ;
  11806. };
  11807. /**
  11808. * True if the mesh intersects another mesh or a SolidParticle object.
  11809. * 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)
  11810. * Returns a boolean.
  11811. */
  11812. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11813. if (!this._boundingInfo || !mesh._boundingInfo) {
  11814. return false;
  11815. }
  11816. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11817. };
  11818. /**
  11819. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  11820. * Returns a boolean.
  11821. */
  11822. AbstractMesh.prototype.intersectsPoint = function (point) {
  11823. if (!this._boundingInfo) {
  11824. return false;
  11825. }
  11826. return this._boundingInfo.intersectsPoint(point);
  11827. };
  11828. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11829. return this.physicsImpostor;
  11830. };
  11831. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11832. if (!camera) {
  11833. camera = this.getScene().activeCamera;
  11834. }
  11835. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11836. };
  11837. /**
  11838. * Returns the distance from the mesh to the active camera.
  11839. * Returns a float.
  11840. */
  11841. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11842. if (!camera) {
  11843. camera = this.getScene().activeCamera;
  11844. }
  11845. return this.absolutePosition.subtract(camera.position).length();
  11846. };
  11847. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11848. if (!this.physicsImpostor) {
  11849. return;
  11850. }
  11851. this.physicsImpostor.applyImpulse(force, contactPoint);
  11852. return this;
  11853. };
  11854. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11855. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11856. return;
  11857. }
  11858. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11859. mainPivot: pivot1,
  11860. connectedPivot: pivot2,
  11861. nativeParams: options
  11862. });
  11863. return this;
  11864. };
  11865. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11866. // Collisions
  11867. /**
  11868. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  11869. * Default `false`.
  11870. */
  11871. get: function () {
  11872. return this._checkCollisions;
  11873. },
  11874. set: function (collisionEnabled) {
  11875. this._checkCollisions = collisionEnabled;
  11876. if (this.getScene().workerCollisions) {
  11877. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11878. }
  11879. },
  11880. enumerable: true,
  11881. configurable: true
  11882. });
  11883. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11884. var globalPosition = this.getAbsolutePosition();
  11885. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11886. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11887. if (!this._collider) {
  11888. this._collider = new BABYLON.Collider();
  11889. }
  11890. this._collider.radius = this.ellipsoid;
  11891. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11892. return this;
  11893. };
  11894. // Submeshes octree
  11895. /**
  11896. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  11897. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  11898. * Returns an Octree of submeshes.
  11899. */
  11900. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11901. if (maxCapacity === void 0) { maxCapacity = 64; }
  11902. if (maxDepth === void 0) { maxDepth = 2; }
  11903. if (!this._submeshesOctree) {
  11904. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11905. }
  11906. this.computeWorldMatrix(true);
  11907. // Update octree
  11908. var bbox = this.getBoundingInfo().boundingBox;
  11909. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11910. return this._submeshesOctree;
  11911. };
  11912. // Collisions
  11913. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11914. this._generatePointsArray();
  11915. // Transformation
  11916. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11917. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11918. subMesh._lastColliderWorldVertices = [];
  11919. subMesh._trianglePlanes = [];
  11920. var start = subMesh.verticesStart;
  11921. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11922. for (var i = start; i < end; i++) {
  11923. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11924. }
  11925. }
  11926. // Collide
  11927. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11928. if (collider.collisionFound) {
  11929. collider.collidedMesh = this;
  11930. }
  11931. return this;
  11932. };
  11933. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11934. var subMeshes;
  11935. var len;
  11936. // Octrees
  11937. if (this._submeshesOctree && this.useOctreeForCollisions) {
  11938. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  11939. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  11940. len = intersections.length;
  11941. subMeshes = intersections.data;
  11942. }
  11943. else {
  11944. subMeshes = this.subMeshes;
  11945. len = subMeshes.length;
  11946. }
  11947. for (var index = 0; index < len; index++) {
  11948. var subMesh = subMeshes[index];
  11949. // Bounding test
  11950. if (len > 1 && !subMesh._checkCollision(collider))
  11951. continue;
  11952. this._collideForSubMesh(subMesh, transformMatrix, collider);
  11953. }
  11954. return this;
  11955. };
  11956. AbstractMesh.prototype._checkCollision = function (collider) {
  11957. // Bounding box test
  11958. if (!this._boundingInfo._checkCollision(collider))
  11959. return this;
  11960. // Transformation matrix
  11961. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  11962. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  11963. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  11964. return this;
  11965. };
  11966. // Picking
  11967. AbstractMesh.prototype._generatePointsArray = function () {
  11968. return false;
  11969. };
  11970. /**
  11971. * Checks if the passed Ray intersects with the mesh.
  11972. * Returns an object PickingInfo.
  11973. */
  11974. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  11975. var pickingInfo = new BABYLON.PickingInfo();
  11976. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  11977. return pickingInfo;
  11978. }
  11979. if (!this._generatePointsArray()) {
  11980. return pickingInfo;
  11981. }
  11982. var intersectInfo = null;
  11983. // Octrees
  11984. var subMeshes;
  11985. var len;
  11986. if (this._submeshesOctree && this.useOctreeForPicking) {
  11987. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  11988. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  11989. len = intersections.length;
  11990. subMeshes = intersections.data;
  11991. }
  11992. else {
  11993. subMeshes = this.subMeshes;
  11994. len = subMeshes.length;
  11995. }
  11996. for (var index = 0; index < len; index++) {
  11997. var subMesh = subMeshes[index];
  11998. // Bounding test
  11999. if (len > 1 && !subMesh.canIntersects(ray))
  12000. continue;
  12001. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12002. if (currentIntersectInfo) {
  12003. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12004. intersectInfo = currentIntersectInfo;
  12005. intersectInfo.subMeshId = index;
  12006. if (fastCheck) {
  12007. break;
  12008. }
  12009. }
  12010. }
  12011. }
  12012. if (intersectInfo) {
  12013. // Get picked point
  12014. var world = this.getWorldMatrix();
  12015. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12016. var direction = ray.direction.clone();
  12017. direction = direction.scale(intersectInfo.distance);
  12018. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12019. var pickedPoint = worldOrigin.add(worldDirection);
  12020. // Return result
  12021. pickingInfo.hit = true;
  12022. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12023. pickingInfo.pickedPoint = pickedPoint;
  12024. pickingInfo.pickedMesh = this;
  12025. pickingInfo.bu = intersectInfo.bu;
  12026. pickingInfo.bv = intersectInfo.bv;
  12027. pickingInfo.faceId = intersectInfo.faceId;
  12028. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12029. return pickingInfo;
  12030. }
  12031. return pickingInfo;
  12032. };
  12033. /**
  12034. * Clones the mesh, used by the class Mesh.
  12035. * Just returns `null` for an AbstractMesh.
  12036. */
  12037. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12038. return null;
  12039. };
  12040. /**
  12041. * Disposes all the mesh submeshes.
  12042. * Returns the AbstractMesh.
  12043. */
  12044. AbstractMesh.prototype.releaseSubMeshes = function () {
  12045. if (this.subMeshes) {
  12046. while (this.subMeshes.length) {
  12047. this.subMeshes[0].dispose();
  12048. }
  12049. }
  12050. else {
  12051. this.subMeshes = new Array();
  12052. }
  12053. return this;
  12054. };
  12055. /**
  12056. * Disposes the AbstractMesh.
  12057. * Some internal references are kept for further use.
  12058. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12059. * Returns nothing.
  12060. */
  12061. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12062. var _this = this;
  12063. var index;
  12064. // Action manager
  12065. if (this.actionManager) {
  12066. this.actionManager.dispose();
  12067. this.actionManager = null;
  12068. }
  12069. // Skeleton
  12070. this.skeleton = null;
  12071. // Animations
  12072. this.getScene().stopAnimation(this);
  12073. // Physics
  12074. if (this.physicsImpostor) {
  12075. this.physicsImpostor.dispose();
  12076. }
  12077. // Intersections in progress
  12078. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12079. var other = this._intersectionsInProgress[index];
  12080. var pos = other._intersectionsInProgress.indexOf(this);
  12081. other._intersectionsInProgress.splice(pos, 1);
  12082. }
  12083. this._intersectionsInProgress = [];
  12084. // Lights
  12085. var lights = this.getScene().lights;
  12086. lights.forEach(function (light) {
  12087. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12088. if (meshIndex !== -1) {
  12089. light.includedOnlyMeshes.splice(meshIndex, 1);
  12090. }
  12091. meshIndex = light.excludedMeshes.indexOf(_this);
  12092. if (meshIndex !== -1) {
  12093. light.excludedMeshes.splice(meshIndex, 1);
  12094. }
  12095. // Shadow generators
  12096. var generator = light.getShadowGenerator();
  12097. if (generator) {
  12098. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  12099. if (meshIndex !== -1) {
  12100. generator.getShadowMap().renderList.splice(meshIndex, 1);
  12101. }
  12102. }
  12103. });
  12104. // Edges
  12105. if (this._edgesRenderer) {
  12106. this._edgesRenderer.dispose();
  12107. this._edgesRenderer = null;
  12108. }
  12109. // SubMeshes
  12110. if (this.getClassName() !== "InstancedMesh") {
  12111. this.releaseSubMeshes();
  12112. }
  12113. // Octree
  12114. var sceneOctree = this.getScene().selectionOctree;
  12115. if (sceneOctree) {
  12116. var index = sceneOctree.dynamicContent.indexOf(this);
  12117. if (index !== -1) {
  12118. sceneOctree.dynamicContent.splice(index, 1);
  12119. }
  12120. }
  12121. // Engine
  12122. this.getScene().getEngine().wipeCaches();
  12123. // Remove from scene
  12124. this.getScene().removeMesh(this);
  12125. if (!doNotRecurse) {
  12126. // Particles
  12127. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12128. if (this.getScene().particleSystems[index].emitter === this) {
  12129. this.getScene().particleSystems[index].dispose();
  12130. index--;
  12131. }
  12132. }
  12133. // Children
  12134. var objects = this.getDescendants(true);
  12135. for (index = 0; index < objects.length; index++) {
  12136. objects[index].dispose();
  12137. }
  12138. }
  12139. else {
  12140. var childMeshes = this.getChildMeshes(true);
  12141. for (index = 0; index < childMeshes.length; index++) {
  12142. var child = childMeshes[index];
  12143. child.parent = null;
  12144. child.computeWorldMatrix(true);
  12145. }
  12146. }
  12147. // facet data
  12148. if (this._facetDataEnabled) {
  12149. this.disableFacetData();
  12150. }
  12151. this.onAfterWorldMatrixUpdateObservable.clear();
  12152. this.onCollideObservable.clear();
  12153. this.onCollisionPositionChangeObservable.clear();
  12154. this._isDisposed = true;
  12155. _super.prototype.dispose.call(this);
  12156. };
  12157. /**
  12158. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12159. * This Vector3 is expressed in the World space.
  12160. */
  12161. AbstractMesh.prototype.getDirection = function (localAxis) {
  12162. var result = BABYLON.Vector3.Zero();
  12163. this.getDirectionToRef(localAxis, result);
  12164. return result;
  12165. };
  12166. /**
  12167. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12168. * localAxis is expressed in the mesh local space.
  12169. * result is computed in the Wordl space from the mesh World matrix.
  12170. * Returns the AbstractMesh.
  12171. */
  12172. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12173. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12174. return this;
  12175. };
  12176. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12177. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12178. if (this.getScene().getRenderId() == 0) {
  12179. this.computeWorldMatrix(true);
  12180. }
  12181. var wm = this.getWorldMatrix();
  12182. if (space == BABYLON.Space.WORLD) {
  12183. var tmat = BABYLON.Tmp.Matrix[0];
  12184. wm.invertToRef(tmat);
  12185. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12186. }
  12187. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12188. this._pivotMatrix.m[12] = -point.x;
  12189. this._pivotMatrix.m[13] = -point.y;
  12190. this._pivotMatrix.m[14] = -point.z;
  12191. this._cache.pivotMatrixUpdated = true;
  12192. return this;
  12193. };
  12194. /**
  12195. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12196. */
  12197. AbstractMesh.prototype.getPivotPoint = function () {
  12198. var point = BABYLON.Vector3.Zero();
  12199. this.getPivotPointToRef(point);
  12200. return point;
  12201. };
  12202. /**
  12203. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12204. * Returns the AbstractMesh.
  12205. */
  12206. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12207. result.x = -this._pivotMatrix.m[12];
  12208. result.y = -this._pivotMatrix.m[13];
  12209. result.z = -this._pivotMatrix.m[14];
  12210. return this;
  12211. };
  12212. /**
  12213. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12214. */
  12215. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12216. var point = BABYLON.Vector3.Zero();
  12217. this.getAbsolutePivotPointToRef(point);
  12218. return point;
  12219. };
  12220. /**
  12221. * Defines the passed mesh as the parent of the current mesh.
  12222. * If keepWorldPositionRotation is set to `true` (default `false`), the current mesh position and rotation are kept.
  12223. * Returns the AbstractMesh.
  12224. */
  12225. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  12226. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  12227. var child = this;
  12228. var parent = mesh;
  12229. if (mesh == null) {
  12230. if (child.parent && keepWorldPositionRotation) {
  12231. var rotation = BABYLON.Tmp.Quaternion[0];
  12232. var position = BABYLON.Tmp.Vector3[0];
  12233. var scale = BABYLON.Tmp.Vector3[1];
  12234. child.getWorldMatrix().decompose(scale, rotation, position);
  12235. if (child.rotationQuaternion) {
  12236. child.rotationQuaternion.copyFrom(rotation);
  12237. }
  12238. else {
  12239. rotation.toEulerAnglesToRef(child.rotation);
  12240. }
  12241. child.position.x = position.x;
  12242. child.position.y = position.y;
  12243. child.position.z = position.z;
  12244. }
  12245. }
  12246. else {
  12247. if (keepWorldPositionRotation) {
  12248. var rotation = BABYLON.Tmp.Quaternion[0];
  12249. var position = BABYLON.Tmp.Vector3[0];
  12250. var scale = BABYLON.Tmp.Vector3[1];
  12251. var m1 = BABYLON.Tmp.Matrix[0];
  12252. var m2 = BABYLON.Tmp.Matrix[1];
  12253. parent.getWorldMatrix().decompose(scale, rotation, position);
  12254. rotation.toRotationMatrix(m1);
  12255. m2.setTranslation(position);
  12256. m2.multiplyToRef(m1, m1);
  12257. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12258. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12259. m.decompose(scale, rotation, position);
  12260. if (child.rotationQuaternion) {
  12261. child.rotationQuaternion.copyFrom(rotation);
  12262. }
  12263. else {
  12264. rotation.toEulerAnglesToRef(child.rotation);
  12265. }
  12266. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12267. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12268. m.decompose(scale, rotation, position);
  12269. child.position.x = position.x;
  12270. child.position.y = position.y;
  12271. child.position.z = position.z;
  12272. }
  12273. }
  12274. child.parent = parent;
  12275. return this;
  12276. };
  12277. /**
  12278. * Adds the passed mesh as a child to the current mesh.
  12279. * If keepWorldPositionRotation is set to `true` (default `false`), the child world position and rotation are kept.
  12280. * Returns the AbstractMesh.
  12281. */
  12282. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  12283. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  12284. mesh.setParent(this, keepWorldPositionRotation);
  12285. return this;
  12286. };
  12287. /**
  12288. * Removes the passed mesh from the current mesh children list.
  12289. * Returns the AbstractMesh.
  12290. */
  12291. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  12292. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  12293. mesh.setParent(null, keepWorldPositionRotation);
  12294. return this;
  12295. };
  12296. /**
  12297. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12298. * Returns the AbstractMesh.
  12299. */
  12300. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12301. result.x = this._pivotMatrix.m[12];
  12302. result.y = this._pivotMatrix.m[13];
  12303. result.z = this._pivotMatrix.m[14];
  12304. this.getPivotPointToRef(result);
  12305. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12306. return this;
  12307. };
  12308. // Facet data
  12309. /**
  12310. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12311. * Returns the AbstractMesh.
  12312. */
  12313. AbstractMesh.prototype._initFacetData = function () {
  12314. if (!this._facetNormals) {
  12315. this._facetNormals = new Array();
  12316. }
  12317. if (!this._facetPositions) {
  12318. this._facetPositions = new Array();
  12319. }
  12320. if (!this._facetPartitioning) {
  12321. this._facetPartitioning = new Array();
  12322. }
  12323. this._facetNb = this.getIndices().length / 3;
  12324. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12325. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12326. for (var f = 0; f < this._facetNb; f++) {
  12327. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12328. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12329. }
  12330. this._facetDataEnabled = true;
  12331. return this;
  12332. };
  12333. /**
  12334. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12335. * This method can be called within the render loop.
  12336. * 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.
  12337. * Returns the AbstractMesh.
  12338. */
  12339. AbstractMesh.prototype.updateFacetData = function () {
  12340. if (!this._facetDataEnabled) {
  12341. this._initFacetData();
  12342. }
  12343. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12344. var indices = this.getIndices();
  12345. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12346. var bInfo = this.getBoundingInfo();
  12347. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12348. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12349. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12350. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12351. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12352. this._subDiv.max = this._partitioningSubdivisions;
  12353. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12354. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12355. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12356. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12357. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12358. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12359. // set the parameters for ComputeNormals()
  12360. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12361. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12362. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12363. this._facetParameters.bInfo = bInfo;
  12364. this._facetParameters.bbSize = this._bbSize;
  12365. this._facetParameters.subDiv = this._subDiv;
  12366. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12367. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12368. return this;
  12369. };
  12370. /**
  12371. * Returns the facetLocalNormals array.
  12372. * The normals are expressed in the mesh local space.
  12373. */
  12374. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12375. if (!this._facetNormals) {
  12376. this.updateFacetData();
  12377. }
  12378. return this._facetNormals;
  12379. };
  12380. /**
  12381. * Returns the facetLocalPositions array.
  12382. * The facet positions are expressed in the mesh local space.
  12383. */
  12384. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12385. if (!this._facetPositions) {
  12386. this.updateFacetData();
  12387. }
  12388. return this._facetPositions;
  12389. };
  12390. /**
  12391. * Returns the facetLocalPartioning array.
  12392. */
  12393. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12394. if (!this._facetPartitioning) {
  12395. this.updateFacetData();
  12396. }
  12397. return this._facetPartitioning;
  12398. };
  12399. /**
  12400. * Returns the i-th facet position in the world system.
  12401. * This method allocates a new Vector3 per call.
  12402. */
  12403. AbstractMesh.prototype.getFacetPosition = function (i) {
  12404. var pos = BABYLON.Vector3.Zero();
  12405. this.getFacetPositionToRef(i, pos);
  12406. return pos;
  12407. };
  12408. /**
  12409. * Sets the reference Vector3 with the i-th facet position in the world system.
  12410. * Returns the AbstractMesh.
  12411. */
  12412. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12413. var localPos = (this.getFacetLocalPositions())[i];
  12414. var world = this.getWorldMatrix();
  12415. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12416. return this;
  12417. };
  12418. /**
  12419. * Returns the i-th facet normal in the world system.
  12420. * This method allocates a new Vector3 per call.
  12421. */
  12422. AbstractMesh.prototype.getFacetNormal = function (i) {
  12423. var norm = BABYLON.Vector3.Zero();
  12424. this.getFacetNormalToRef(i, norm);
  12425. return norm;
  12426. };
  12427. /**
  12428. * Sets the reference Vector3 with the i-th facet normal in the world system.
  12429. * Returns the AbstractMesh.
  12430. */
  12431. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  12432. var localNorm = (this.getFacetLocalNormals())[i];
  12433. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  12434. return this;
  12435. };
  12436. /**
  12437. * 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).
  12438. */
  12439. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  12440. var bInfo = this.getBoundingInfo();
  12441. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  12442. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  12443. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  12444. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  12445. return null;
  12446. }
  12447. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  12448. };
  12449. /**
  12450. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  12451. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  12452. * 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.
  12453. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12454. * 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.
  12455. */
  12456. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  12457. if (checkFace === void 0) { checkFace = false; }
  12458. if (facing === void 0) { facing = true; }
  12459. var world = this.getWorldMatrix();
  12460. var invMat = BABYLON.Tmp.Matrix[5];
  12461. world.invertToRef(invMat);
  12462. var invVect = BABYLON.Tmp.Vector3[8];
  12463. var closest = null;
  12464. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  12465. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  12466. if (projected) {
  12467. // tranform the local computed projected vector to world coordinates
  12468. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  12469. }
  12470. return closest;
  12471. };
  12472. /**
  12473. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  12474. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  12475. * 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.
  12476. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12477. * 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.
  12478. */
  12479. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  12480. if (checkFace === void 0) { checkFace = false; }
  12481. if (facing === void 0) { facing = true; }
  12482. var closest = null;
  12483. var tmpx = 0.0;
  12484. var tmpy = 0.0;
  12485. var tmpz = 0.0;
  12486. var d = 0.0; // tmp dot facet normal * facet position
  12487. var t0 = 0.0;
  12488. var projx = 0.0;
  12489. var projy = 0.0;
  12490. var projz = 0.0;
  12491. // Get all the facets in the same partitioning block than (x, y, z)
  12492. var facetPositions = this.getFacetLocalPositions();
  12493. var facetNormals = this.getFacetLocalNormals();
  12494. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  12495. if (!facetsInBlock) {
  12496. return null;
  12497. }
  12498. // Get the closest facet to (x, y, z)
  12499. var shortest = Number.MAX_VALUE; // init distance vars
  12500. var tmpDistance = shortest;
  12501. var fib; // current facet in the block
  12502. var norm; // current facet normal
  12503. var p0; // current facet barycenter position
  12504. // loop on all the facets in the current partitioning block
  12505. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  12506. fib = facetsInBlock[idx];
  12507. norm = facetNormals[fib];
  12508. p0 = facetPositions[fib];
  12509. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  12510. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  12511. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  12512. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  12513. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  12514. projx = x + norm.x * t0;
  12515. projy = y + norm.y * t0;
  12516. projz = z + norm.z * t0;
  12517. tmpx = projx - x;
  12518. tmpy = projy - y;
  12519. tmpz = projz - z;
  12520. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  12521. if (tmpDistance < shortest) {
  12522. shortest = tmpDistance;
  12523. closest = fib;
  12524. if (projected) {
  12525. projected.x = projx;
  12526. projected.y = projy;
  12527. projected.z = projz;
  12528. }
  12529. }
  12530. }
  12531. }
  12532. return closest;
  12533. };
  12534. /**
  12535. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  12536. */
  12537. AbstractMesh.prototype.getFacetDataParameters = function () {
  12538. return this._facetParameters;
  12539. };
  12540. /**
  12541. * Disables the feature FacetData and frees the related memory.
  12542. * Returns the AbstractMesh.
  12543. */
  12544. AbstractMesh.prototype.disableFacetData = function () {
  12545. if (this._facetDataEnabled) {
  12546. this._facetDataEnabled = false;
  12547. this._facetPositions = null;
  12548. this._facetNormals = null;
  12549. this._facetPartitioning = null;
  12550. this._facetParameters = null;
  12551. }
  12552. return this;
  12553. };
  12554. /**
  12555. * Creates new normals data for the mesh.
  12556. * @param updatable.
  12557. */
  12558. AbstractMesh.prototype.createNormals = function (updatable) {
  12559. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12560. var indices = this.getIndices();
  12561. var normals;
  12562. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12563. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12564. }
  12565. else {
  12566. normals = [];
  12567. }
  12568. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  12569. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  12570. };
  12571. return AbstractMesh;
  12572. }(BABYLON.Node));
  12573. // Statics
  12574. AbstractMesh._BILLBOARDMODE_NONE = 0;
  12575. AbstractMesh._BILLBOARDMODE_X = 1;
  12576. AbstractMesh._BILLBOARDMODE_Y = 2;
  12577. AbstractMesh._BILLBOARDMODE_Z = 4;
  12578. AbstractMesh._BILLBOARDMODE_ALL = 7;
  12579. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  12580. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  12581. BABYLON.AbstractMesh = AbstractMesh;
  12582. })(BABYLON || (BABYLON = {}));
  12583. //# sourceMappingURL=babylon.abstractMesh.js.map
  12584. var BABYLON;
  12585. (function (BABYLON) {
  12586. var Light = (function (_super) {
  12587. __extends(Light, _super);
  12588. /**
  12589. * Creates a Light object in the scene.
  12590. * Documentation : http://doc.babylonjs.com/tutorials/lights
  12591. */
  12592. function Light(name, scene) {
  12593. var _this = _super.call(this, name, scene) || this;
  12594. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  12595. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  12596. _this.intensity = 1.0;
  12597. _this.range = Number.MAX_VALUE;
  12598. _this._excludeWithLayerMask = 0;
  12599. _this._includeOnlyWithLayerMask = 0;
  12600. _this._lightmapMode = 0;
  12601. // PBR Properties.
  12602. _this.radius = 0.00001;
  12603. _this._excludedMeshesIds = new Array();
  12604. _this._includedOnlyMeshesIds = new Array();
  12605. _this.getScene().addLight(_this);
  12606. _this.includedOnlyMeshes = new Array();
  12607. _this.excludedMeshes = new Array();
  12608. _this._resyncMeshes();
  12609. return _this;
  12610. }
  12611. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  12612. /**
  12613. * If every light affecting the material is in this lightmapMode,
  12614. * material.lightmapTexture adds or multiplies
  12615. * (depends on material.useLightmapAsShadowmap)
  12616. * after every other light calculations.
  12617. */
  12618. get: function () {
  12619. return Light._LIGHTMAP_DEFAULT;
  12620. },
  12621. enumerable: true,
  12622. configurable: true
  12623. });
  12624. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  12625. /**
  12626. * material.lightmapTexture as only diffuse lighting from this light
  12627. * adds pnly specular lighting from this light
  12628. * adds dynamic shadows
  12629. */
  12630. get: function () {
  12631. return Light._LIGHTMAP_SPECULAR;
  12632. },
  12633. enumerable: true,
  12634. configurable: true
  12635. });
  12636. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  12637. /**
  12638. * material.lightmapTexture as only lighting
  12639. * no light calculation from this light
  12640. * only adds dynamic shadows from this light
  12641. */
  12642. get: function () {
  12643. return Light._LIGHTMAP_SHADOWSONLY;
  12644. },
  12645. enumerable: true,
  12646. configurable: true
  12647. });
  12648. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  12649. get: function () {
  12650. return this._includedOnlyMeshes;
  12651. },
  12652. set: function (value) {
  12653. this._includedOnlyMeshes = value;
  12654. this._hookArrayForIncludedOnly(value);
  12655. },
  12656. enumerable: true,
  12657. configurable: true
  12658. });
  12659. Object.defineProperty(Light.prototype, "excludedMeshes", {
  12660. get: function () {
  12661. return this._excludedMeshes;
  12662. },
  12663. set: function (value) {
  12664. this._excludedMeshes = value;
  12665. this._hookArrayForExcluded(value);
  12666. },
  12667. enumerable: true,
  12668. configurable: true
  12669. });
  12670. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  12671. get: function () {
  12672. return this._excludeWithLayerMask;
  12673. },
  12674. set: function (value) {
  12675. this._excludeWithLayerMask = value;
  12676. this._resyncMeshes();
  12677. },
  12678. enumerable: true,
  12679. configurable: true
  12680. });
  12681. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  12682. get: function () {
  12683. return this._includeOnlyWithLayerMask;
  12684. },
  12685. set: function (value) {
  12686. this._includeOnlyWithLayerMask = value;
  12687. this._resyncMeshes();
  12688. },
  12689. enumerable: true,
  12690. configurable: true
  12691. });
  12692. Object.defineProperty(Light.prototype, "lightmapMode", {
  12693. get: function () {
  12694. return this._lightmapMode;
  12695. },
  12696. set: function (value) {
  12697. if (this._lightmapMode === value) {
  12698. return;
  12699. }
  12700. this._lightmapMode = value;
  12701. this._markMeshesAsLightDirty();
  12702. },
  12703. enumerable: true,
  12704. configurable: true
  12705. });
  12706. /**
  12707. * Returns the string "Light".
  12708. */
  12709. Light.prototype.getClassName = function () {
  12710. return "Light";
  12711. };
  12712. /**
  12713. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12714. */
  12715. Light.prototype.toString = function (fullDetails) {
  12716. var ret = "Name: " + this.name;
  12717. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  12718. if (this.animations) {
  12719. for (var i = 0; i < this.animations.length; i++) {
  12720. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12721. }
  12722. }
  12723. if (fullDetails) {
  12724. }
  12725. return ret;
  12726. };
  12727. /**
  12728. * Set the enabled state of this node.
  12729. * @param {boolean} value - the new enabled state
  12730. * @see isEnabled
  12731. */
  12732. Light.prototype.setEnabled = function (value) {
  12733. _super.prototype.setEnabled.call(this, value);
  12734. this._resyncMeshes();
  12735. };
  12736. /**
  12737. * Returns the Light associated shadow generator.
  12738. */
  12739. Light.prototype.getShadowGenerator = function () {
  12740. return this._shadowGenerator;
  12741. };
  12742. /**
  12743. * Returns a Vector3, the absolute light position in the World.
  12744. */
  12745. Light.prototype.getAbsolutePosition = function () {
  12746. return BABYLON.Vector3.Zero();
  12747. };
  12748. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  12749. };
  12750. Light.prototype._getWorldMatrix = function () {
  12751. return BABYLON.Matrix.Identity();
  12752. };
  12753. /**
  12754. * Boolean : True if the light will affect the passed mesh.
  12755. */
  12756. Light.prototype.canAffectMesh = function (mesh) {
  12757. if (!mesh) {
  12758. return true;
  12759. }
  12760. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  12761. return false;
  12762. }
  12763. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  12764. return false;
  12765. }
  12766. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  12767. return false;
  12768. }
  12769. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  12770. return false;
  12771. }
  12772. return true;
  12773. };
  12774. /**
  12775. * Returns the light World matrix.
  12776. */
  12777. Light.prototype.getWorldMatrix = function () {
  12778. this._currentRenderId = this.getScene().getRenderId();
  12779. var worldMatrix = this._getWorldMatrix();
  12780. if (this.parent && this.parent.getWorldMatrix) {
  12781. if (!this._parentedWorldMatrix) {
  12782. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  12783. }
  12784. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  12785. this._markSyncedWithParent();
  12786. return this._parentedWorldMatrix;
  12787. }
  12788. return worldMatrix;
  12789. };
  12790. /**
  12791. * Disposes the light.
  12792. */
  12793. Light.prototype.dispose = function () {
  12794. if (this._shadowGenerator) {
  12795. this._shadowGenerator.dispose();
  12796. this._shadowGenerator = null;
  12797. }
  12798. // Animations
  12799. this.getScene().stopAnimation(this);
  12800. // Remove from meshes
  12801. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  12802. var mesh = _a[_i];
  12803. mesh._removeLightSource(this);
  12804. }
  12805. // Remove from scene
  12806. this.getScene().removeLight(this);
  12807. _super.prototype.dispose.call(this);
  12808. };
  12809. /**
  12810. * Returns the light type ID (integer).
  12811. */
  12812. Light.prototype.getTypeID = function () {
  12813. return 0;
  12814. };
  12815. /**
  12816. * Returns a new Light object, named "name", from the current one.
  12817. */
  12818. Light.prototype.clone = function (name) {
  12819. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  12820. };
  12821. /**
  12822. * Serializes the current light into a Serialization object.
  12823. * Returns the serialized object.
  12824. */
  12825. Light.prototype.serialize = function () {
  12826. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12827. // Type
  12828. serializationObject.type = this.getTypeID();
  12829. // Parent
  12830. if (this.parent) {
  12831. serializationObject.parentId = this.parent.id;
  12832. }
  12833. // Inclusion / exclusions
  12834. if (this.excludedMeshes.length > 0) {
  12835. serializationObject.excludedMeshesIds = [];
  12836. this.excludedMeshes.forEach(function (mesh) {
  12837. serializationObject.excludedMeshesIds.push(mesh.id);
  12838. });
  12839. }
  12840. if (this.includedOnlyMeshes.length > 0) {
  12841. serializationObject.includedOnlyMeshesIds = [];
  12842. this.includedOnlyMeshes.forEach(function (mesh) {
  12843. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  12844. });
  12845. }
  12846. // Animations
  12847. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12848. serializationObject.ranges = this.serializeAnimationRanges();
  12849. return serializationObject;
  12850. };
  12851. /**
  12852. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  12853. * This new light is named "name" and added to the passed scene.
  12854. */
  12855. Light.GetConstructorFromName = function (type, name, scene) {
  12856. switch (type) {
  12857. case 0:
  12858. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  12859. case 1:
  12860. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  12861. case 2:
  12862. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  12863. case 3:
  12864. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  12865. }
  12866. };
  12867. /**
  12868. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  12869. */
  12870. Light.Parse = function (parsedLight, scene) {
  12871. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  12872. // Inclusion / exclusions
  12873. if (parsedLight.excludedMeshesIds) {
  12874. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  12875. }
  12876. if (parsedLight.includedOnlyMeshesIds) {
  12877. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  12878. }
  12879. // Parent
  12880. if (parsedLight.parentId) {
  12881. light._waitingParentId = parsedLight.parentId;
  12882. }
  12883. // Animations
  12884. if (parsedLight.animations) {
  12885. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  12886. var parsedAnimation = parsedLight.animations[animationIndex];
  12887. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12888. }
  12889. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  12890. }
  12891. if (parsedLight.autoAnimate) {
  12892. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  12893. }
  12894. return light;
  12895. };
  12896. Light.prototype._hookArrayForExcluded = function (array) {
  12897. var _this = this;
  12898. var oldPush = array.push;
  12899. array.push = function () {
  12900. var items = [];
  12901. for (var _i = 0; _i < arguments.length; _i++) {
  12902. items[_i] = arguments[_i];
  12903. }
  12904. var result = oldPush.apply(array, items);
  12905. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  12906. var item = items_1[_a];
  12907. item._resyncLighSource(_this);
  12908. }
  12909. return result;
  12910. };
  12911. var oldSplice = array.splice;
  12912. array.splice = function (index, deleteCount) {
  12913. var deleted = oldSplice.apply(array, [index, deleteCount]);
  12914. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  12915. var item = deleted_1[_i];
  12916. item._resyncLighSource(_this);
  12917. }
  12918. return deleted;
  12919. };
  12920. };
  12921. Light.prototype._hookArrayForIncludedOnly = function (array) {
  12922. var _this = this;
  12923. var oldPush = array.push;
  12924. array.push = function () {
  12925. var items = [];
  12926. for (var _i = 0; _i < arguments.length; _i++) {
  12927. items[_i] = arguments[_i];
  12928. }
  12929. var result = oldPush.apply(array, items);
  12930. _this._resyncMeshes();
  12931. return result;
  12932. };
  12933. var oldSplice = array.splice;
  12934. array.splice = function (index, deleteCount) {
  12935. var deleted = oldSplice.apply(array, [index, deleteCount]);
  12936. _this._resyncMeshes();
  12937. return deleted;
  12938. };
  12939. };
  12940. Light.prototype._resyncMeshes = function () {
  12941. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  12942. var mesh = _a[_i];
  12943. mesh._resyncLighSource(this);
  12944. }
  12945. };
  12946. Light.prototype._markMeshesAsLightDirty = function () {
  12947. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  12948. var mesh = _a[_i];
  12949. if (mesh._lightSources.indexOf(this) !== -1) {
  12950. mesh._markSubMeshesAsLightDirty();
  12951. }
  12952. }
  12953. };
  12954. return Light;
  12955. }(BABYLON.Node));
  12956. //lightmapMode Consts
  12957. Light._LIGHTMAP_DEFAULT = 0;
  12958. Light._LIGHTMAP_SPECULAR = 1;
  12959. Light._LIGHTMAP_SHADOWSONLY = 2;
  12960. __decorate([
  12961. BABYLON.serializeAsColor3()
  12962. ], Light.prototype, "diffuse", void 0);
  12963. __decorate([
  12964. BABYLON.serializeAsColor3()
  12965. ], Light.prototype, "specular", void 0);
  12966. __decorate([
  12967. BABYLON.serialize()
  12968. ], Light.prototype, "intensity", void 0);
  12969. __decorate([
  12970. BABYLON.serialize()
  12971. ], Light.prototype, "range", void 0);
  12972. __decorate([
  12973. BABYLON.serialize("excludeWithLayerMask")
  12974. ], Light.prototype, "_excludeWithLayerMask", void 0);
  12975. __decorate([
  12976. BABYLON.serialize("includeOnlyWithLayerMask")
  12977. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  12978. __decorate([
  12979. BABYLON.serialize("lightmapMode")
  12980. ], Light.prototype, "_lightmapMode", void 0);
  12981. __decorate([
  12982. BABYLON.serialize()
  12983. ], Light.prototype, "radius", void 0);
  12984. BABYLON.Light = Light;
  12985. })(BABYLON || (BABYLON = {}));
  12986. //# sourceMappingURL=babylon.light.js.map
  12987. var BABYLON;
  12988. (function (BABYLON) {
  12989. var Camera = (function (_super) {
  12990. __extends(Camera, _super);
  12991. function Camera(name, position, scene) {
  12992. var _this = _super.call(this, name, scene) || this;
  12993. _this.upVector = BABYLON.Vector3.Up();
  12994. _this.orthoLeft = null;
  12995. _this.orthoRight = null;
  12996. _this.orthoBottom = null;
  12997. _this.orthoTop = null;
  12998. _this.fov = 0.8;
  12999. _this.minZ = 1.0;
  13000. _this.maxZ = 10000.0;
  13001. _this.inertia = 0.9;
  13002. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13003. _this.isIntermediate = false;
  13004. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13005. _this.layerMask = 0x0FFFFFFF;
  13006. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13007. // Camera rig members
  13008. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13009. _this._rigCameras = new Array();
  13010. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13011. // Cache
  13012. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13013. _this._projectionMatrix = new BABYLON.Matrix();
  13014. _this._doNotComputeProjectionMatrix = false;
  13015. _this._postProcesses = new Array();
  13016. _this._transformMatrix = BABYLON.Matrix.Zero();
  13017. _this._activeMeshes = new BABYLON.SmartArray(256);
  13018. _this._globalPosition = BABYLON.Vector3.Zero();
  13019. _this._refreshFrustumPlanes = true;
  13020. _this.getScene().addCamera(_this);
  13021. if (!_this.getScene().activeCamera) {
  13022. _this.getScene().activeCamera = _this;
  13023. }
  13024. _this.position = position;
  13025. return _this;
  13026. }
  13027. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13028. get: function () {
  13029. return Camera._PERSPECTIVE_CAMERA;
  13030. },
  13031. enumerable: true,
  13032. configurable: true
  13033. });
  13034. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13035. get: function () {
  13036. return Camera._ORTHOGRAPHIC_CAMERA;
  13037. },
  13038. enumerable: true,
  13039. configurable: true
  13040. });
  13041. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13042. get: function () {
  13043. return Camera._FOVMODE_VERTICAL_FIXED;
  13044. },
  13045. enumerable: true,
  13046. configurable: true
  13047. });
  13048. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13049. get: function () {
  13050. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13051. },
  13052. enumerable: true,
  13053. configurable: true
  13054. });
  13055. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13056. get: function () {
  13057. return Camera._RIG_MODE_NONE;
  13058. },
  13059. enumerable: true,
  13060. configurable: true
  13061. });
  13062. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13063. get: function () {
  13064. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13065. },
  13066. enumerable: true,
  13067. configurable: true
  13068. });
  13069. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13070. get: function () {
  13071. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13072. },
  13073. enumerable: true,
  13074. configurable: true
  13075. });
  13076. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13077. get: function () {
  13078. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13079. },
  13080. enumerable: true,
  13081. configurable: true
  13082. });
  13083. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13084. get: function () {
  13085. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13086. },
  13087. enumerable: true,
  13088. configurable: true
  13089. });
  13090. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13091. get: function () {
  13092. return Camera._RIG_MODE_VR;
  13093. },
  13094. enumerable: true,
  13095. configurable: true
  13096. });
  13097. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13098. get: function () {
  13099. return Camera._RIG_MODE_WEBVR;
  13100. },
  13101. enumerable: true,
  13102. configurable: true
  13103. });
  13104. Camera.prototype.getClassName = function () {
  13105. return "Camera";
  13106. };
  13107. /**
  13108. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13109. */
  13110. Camera.prototype.toString = function (fullDetails) {
  13111. var ret = "Name: " + this.name;
  13112. ret += ", type: " + this.getClassName();
  13113. if (this.animations) {
  13114. for (var i = 0; i < this.animations.length; i++) {
  13115. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13116. }
  13117. }
  13118. if (fullDetails) {
  13119. }
  13120. return ret;
  13121. };
  13122. Object.defineProperty(Camera.prototype, "globalPosition", {
  13123. get: function () {
  13124. return this._globalPosition;
  13125. },
  13126. enumerable: true,
  13127. configurable: true
  13128. });
  13129. Camera.prototype.getActiveMeshes = function () {
  13130. return this._activeMeshes;
  13131. };
  13132. Camera.prototype.isActiveMesh = function (mesh) {
  13133. return (this._activeMeshes.indexOf(mesh) !== -1);
  13134. };
  13135. //Cache
  13136. Camera.prototype._initCache = function () {
  13137. _super.prototype._initCache.call(this);
  13138. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13139. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13140. this._cache.mode = undefined;
  13141. this._cache.minZ = undefined;
  13142. this._cache.maxZ = undefined;
  13143. this._cache.fov = undefined;
  13144. this._cache.fovMode = undefined;
  13145. this._cache.aspectRatio = undefined;
  13146. this._cache.orthoLeft = undefined;
  13147. this._cache.orthoRight = undefined;
  13148. this._cache.orthoBottom = undefined;
  13149. this._cache.orthoTop = undefined;
  13150. this._cache.renderWidth = undefined;
  13151. this._cache.renderHeight = undefined;
  13152. };
  13153. Camera.prototype._updateCache = function (ignoreParentClass) {
  13154. if (!ignoreParentClass) {
  13155. _super.prototype._updateCache.call(this);
  13156. }
  13157. var engine = this.getEngine();
  13158. this._cache.position.copyFrom(this.position);
  13159. this._cache.upVector.copyFrom(this.upVector);
  13160. this._cache.mode = this.mode;
  13161. this._cache.minZ = this.minZ;
  13162. this._cache.maxZ = this.maxZ;
  13163. this._cache.fov = this.fov;
  13164. this._cache.fovMode = this.fovMode;
  13165. this._cache.aspectRatio = engine.getAspectRatio(this);
  13166. this._cache.orthoLeft = this.orthoLeft;
  13167. this._cache.orthoRight = this.orthoRight;
  13168. this._cache.orthoBottom = this.orthoBottom;
  13169. this._cache.orthoTop = this.orthoTop;
  13170. this._cache.renderWidth = engine.getRenderWidth();
  13171. this._cache.renderHeight = engine.getRenderHeight();
  13172. };
  13173. Camera.prototype._updateFromScene = function () {
  13174. this.updateCache();
  13175. this.update();
  13176. };
  13177. // Synchronized
  13178. Camera.prototype._isSynchronized = function () {
  13179. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13180. };
  13181. Camera.prototype._isSynchronizedViewMatrix = function () {
  13182. if (!_super.prototype._isSynchronized.call(this))
  13183. return false;
  13184. return this._cache.position.equals(this.position)
  13185. && this._cache.upVector.equals(this.upVector)
  13186. && this.isSynchronizedWithParent();
  13187. };
  13188. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13189. var check = this._cache.mode === this.mode
  13190. && this._cache.minZ === this.minZ
  13191. && this._cache.maxZ === this.maxZ;
  13192. if (!check) {
  13193. return false;
  13194. }
  13195. var engine = this.getEngine();
  13196. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13197. check = this._cache.fov === this.fov
  13198. && this._cache.fovMode === this.fovMode
  13199. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13200. }
  13201. else {
  13202. check = this._cache.orthoLeft === this.orthoLeft
  13203. && this._cache.orthoRight === this.orthoRight
  13204. && this._cache.orthoBottom === this.orthoBottom
  13205. && this._cache.orthoTop === this.orthoTop
  13206. && this._cache.renderWidth === engine.getRenderWidth()
  13207. && this._cache.renderHeight === engine.getRenderHeight();
  13208. }
  13209. return check;
  13210. };
  13211. // Controls
  13212. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13213. };
  13214. Camera.prototype.detachControl = function (element) {
  13215. };
  13216. Camera.prototype.update = function () {
  13217. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13218. this._updateRigCameras();
  13219. }
  13220. this._checkInputs();
  13221. };
  13222. Camera.prototype._checkInputs = function () {
  13223. };
  13224. Object.defineProperty(Camera.prototype, "rigCameras", {
  13225. get: function () {
  13226. return this._rigCameras;
  13227. },
  13228. enumerable: true,
  13229. configurable: true
  13230. });
  13231. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  13232. get: function () {
  13233. return this._rigPostProcess;
  13234. },
  13235. enumerable: true,
  13236. configurable: true
  13237. });
  13238. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13239. // invalidate framebuffer
  13240. if (this._postProcesses.length > 0) {
  13241. this._postProcesses[0].markTextureDirty();
  13242. }
  13243. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13244. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13245. var cam = this._rigCameras[i];
  13246. var rigPostProcess = cam._rigPostProcess;
  13247. // for VR rig, there does not have to be a post process
  13248. if (rigPostProcess) {
  13249. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13250. if (isPass) {
  13251. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13252. cam.isIntermediate = this._postProcesses.length === 0;
  13253. }
  13254. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13255. rigPostProcess.markTextureDirty();
  13256. }
  13257. else {
  13258. cam._postProcesses = this._postProcesses.slice(0);
  13259. }
  13260. }
  13261. };
  13262. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13263. if (insertAt === void 0) { insertAt = null; }
  13264. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13265. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13266. return 0;
  13267. }
  13268. if (insertAt == null || insertAt < 0) {
  13269. this._postProcesses.push(postProcess);
  13270. }
  13271. else {
  13272. this._postProcesses.splice(insertAt, 0, postProcess);
  13273. }
  13274. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13275. return this._postProcesses.indexOf(postProcess);
  13276. };
  13277. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13278. if (atIndices === void 0) { atIndices = null; }
  13279. var result = [];
  13280. var i;
  13281. var index;
  13282. if (!atIndices) {
  13283. var idx = this._postProcesses.indexOf(postProcess);
  13284. if (idx !== -1) {
  13285. this._postProcesses.splice(idx, 1);
  13286. }
  13287. }
  13288. else {
  13289. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13290. // iterate descending, so can just splice as we go
  13291. for (i = atIndices.length - 1; i >= 0; i--) {
  13292. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13293. result.push(i);
  13294. continue;
  13295. }
  13296. index = atIndices[i];
  13297. this._postProcesses.splice(index, 1);
  13298. }
  13299. }
  13300. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13301. return result;
  13302. };
  13303. Camera.prototype.getWorldMatrix = function () {
  13304. if (!this._worldMatrix) {
  13305. this._worldMatrix = BABYLON.Matrix.Identity();
  13306. }
  13307. var viewMatrix = this.getViewMatrix();
  13308. viewMatrix.invertToRef(this._worldMatrix);
  13309. return this._worldMatrix;
  13310. };
  13311. Camera.prototype._getViewMatrix = function () {
  13312. return BABYLON.Matrix.Identity();
  13313. };
  13314. Camera.prototype.getViewMatrix = function (force) {
  13315. this._computedViewMatrix = this._computeViewMatrix(force);
  13316. if (!force && this._isSynchronizedViewMatrix()) {
  13317. return this._computedViewMatrix;
  13318. }
  13319. this._refreshFrustumPlanes = true;
  13320. if (!this.parent || !this.parent.getWorldMatrix) {
  13321. this._globalPosition.copyFrom(this.position);
  13322. }
  13323. else {
  13324. if (!this._worldMatrix) {
  13325. this._worldMatrix = BABYLON.Matrix.Identity();
  13326. }
  13327. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13328. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13329. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13330. this._computedViewMatrix.invert();
  13331. this._markSyncedWithParent();
  13332. }
  13333. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  13334. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  13335. }
  13336. this._currentRenderId = this.getScene().getRenderId();
  13337. return this._computedViewMatrix;
  13338. };
  13339. Camera.prototype._computeViewMatrix = function (force) {
  13340. if (!force && this._isSynchronizedViewMatrix()) {
  13341. return this._computedViewMatrix;
  13342. }
  13343. this._computedViewMatrix = this._getViewMatrix();
  13344. this._currentRenderId = this.getScene().getRenderId();
  13345. return this._computedViewMatrix;
  13346. };
  13347. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13348. this._doNotComputeProjectionMatrix = true;
  13349. if (projection !== undefined) {
  13350. this._projectionMatrix = projection;
  13351. }
  13352. };
  13353. ;
  13354. Camera.prototype.unfreezeProjectionMatrix = function () {
  13355. this._doNotComputeProjectionMatrix = false;
  13356. };
  13357. ;
  13358. Camera.prototype.getProjectionMatrix = function (force) {
  13359. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13360. return this._projectionMatrix;
  13361. }
  13362. this._refreshFrustumPlanes = true;
  13363. var engine = this.getEngine();
  13364. var scene = this.getScene();
  13365. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13366. if (this.minZ <= 0) {
  13367. this.minZ = 0.1;
  13368. }
  13369. if (scene.useRightHandedSystem) {
  13370. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13371. }
  13372. else {
  13373. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13374. }
  13375. return this._projectionMatrix;
  13376. }
  13377. var halfWidth = engine.getRenderWidth() / 2.0;
  13378. var halfHeight = engine.getRenderHeight() / 2.0;
  13379. if (scene.useRightHandedSystem) {
  13380. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13381. }
  13382. else {
  13383. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13384. }
  13385. return this._projectionMatrix;
  13386. };
  13387. Camera.prototype.getTranformationMatrix = function () {
  13388. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13389. return this._transformMatrix;
  13390. };
  13391. Camera.prototype.updateFrustumPlanes = function () {
  13392. if (!this._refreshFrustumPlanes) {
  13393. return;
  13394. }
  13395. this.getTranformationMatrix();
  13396. if (!this._frustumPlanes) {
  13397. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13398. }
  13399. else {
  13400. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13401. }
  13402. this._refreshFrustumPlanes = false;
  13403. };
  13404. Camera.prototype.isInFrustum = function (target) {
  13405. this.updateFrustumPlanes();
  13406. return target.isInFrustum(this._frustumPlanes);
  13407. };
  13408. Camera.prototype.isCompletelyInFrustum = function (target) {
  13409. this.updateFrustumPlanes();
  13410. return target.isCompletelyInFrustum(this._frustumPlanes);
  13411. };
  13412. Camera.prototype.dispose = function () {
  13413. // Animations
  13414. this.getScene().stopAnimation(this);
  13415. // Remove from scene
  13416. this.getScene().removeCamera(this);
  13417. while (this._rigCameras.length > 0) {
  13418. this._rigCameras.pop().dispose();
  13419. }
  13420. // Postprocesses
  13421. var i = this._postProcesses.length;
  13422. while (--i >= 0) {
  13423. this._postProcesses[i].dispose(this);
  13424. }
  13425. _super.prototype.dispose.call(this);
  13426. };
  13427. // ---- Camera rigs section ----
  13428. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13429. while (this._rigCameras.length > 0) {
  13430. this._rigCameras.pop().dispose();
  13431. }
  13432. this.cameraRigMode = mode;
  13433. this._cameraRigParams = {};
  13434. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13435. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13436. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13437. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13438. // create the rig cameras, unless none
  13439. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13440. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13441. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13442. }
  13443. switch (this.cameraRigMode) {
  13444. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13445. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13446. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13447. break;
  13448. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13449. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13450. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13451. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13452. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13453. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13454. break;
  13455. case Camera.RIG_MODE_VR:
  13456. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13457. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13458. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13459. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13460. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13461. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13462. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13463. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13464. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13465. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13466. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13467. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13468. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13469. if (metrics.compensateDistortion) {
  13470. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13471. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13472. }
  13473. break;
  13474. case Camera.RIG_MODE_WEBVR:
  13475. if (rigParams.vrDisplay) {
  13476. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13477. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13478. //Left eye
  13479. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13480. this._rigCameras[0].setCameraRigParameter("left", true);
  13481. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  13482. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  13483. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13484. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  13485. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13486. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13487. this._rigCameras[0].parent = this;
  13488. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13489. //Right eye
  13490. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13491. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  13492. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  13493. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13494. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  13495. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13496. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13497. this._rigCameras[1].parent = this;
  13498. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  13499. }
  13500. break;
  13501. }
  13502. this._cascadePostProcessesToRigCams();
  13503. this.
  13504. update();
  13505. };
  13506. Camera.prototype._getVRProjectionMatrix = function () {
  13507. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13508. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13509. return this._projectionMatrix;
  13510. };
  13511. Camera.prototype._updateCameraRotationMatrix = function () {
  13512. //Here for WebVR
  13513. };
  13514. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  13515. //Here for WebVR
  13516. };
  13517. /**
  13518. * This function MUST be overwritten by the different WebVR cameras available.
  13519. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  13520. */
  13521. Camera.prototype._getWebVRProjectionMatrix = function () {
  13522. return BABYLON.Matrix.Identity();
  13523. };
  13524. /**
  13525. * This function MUST be overwritten by the different WebVR cameras available.
  13526. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  13527. */
  13528. Camera.prototype._getWebVRViewMatrix = function () {
  13529. return BABYLON.Matrix.Identity();
  13530. };
  13531. Camera.prototype.setCameraRigParameter = function (name, value) {
  13532. if (!this._cameraRigParams) {
  13533. this._cameraRigParams = {};
  13534. }
  13535. this._cameraRigParams[name] = value;
  13536. //provisionnally:
  13537. if (name === "interaxialDistance") {
  13538. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13539. }
  13540. };
  13541. /**
  13542. * needs to be overridden by children so sub has required properties to be copied
  13543. */
  13544. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13545. return null;
  13546. };
  13547. /**
  13548. * May need to be overridden by children
  13549. */
  13550. Camera.prototype._updateRigCameras = function () {
  13551. for (var i = 0; i < this._rigCameras.length; i++) {
  13552. this._rigCameras[i].minZ = this.minZ;
  13553. this._rigCameras[i].maxZ = this.maxZ;
  13554. this._rigCameras[i].fov = this.fov;
  13555. }
  13556. // only update viewport when ANAGLYPH
  13557. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13558. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13559. }
  13560. };
  13561. Camera.prototype._setupInputs = function () {
  13562. };
  13563. Camera.prototype.serialize = function () {
  13564. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13565. // Type
  13566. serializationObject.type = this.getClassName();
  13567. // Parent
  13568. if (this.parent) {
  13569. serializationObject.parentId = this.parent.id;
  13570. }
  13571. if (this.inputs) {
  13572. this.inputs.serialize(serializationObject);
  13573. }
  13574. // Animations
  13575. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13576. serializationObject.ranges = this.serializeAnimationRanges();
  13577. return serializationObject;
  13578. };
  13579. Camera.prototype.clone = function (name) {
  13580. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13581. };
  13582. Camera.prototype.getDirection = function (localAxis) {
  13583. var result = BABYLON.Vector3.Zero();
  13584. this.getDirectionToRef(localAxis, result);
  13585. return result;
  13586. };
  13587. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  13588. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13589. };
  13590. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13591. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13592. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13593. switch (type) {
  13594. case "ArcRotateCamera":
  13595. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13596. case "DeviceOrientationCamera":
  13597. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13598. case "FollowCamera":
  13599. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13600. case "ArcFollowCamera":
  13601. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13602. case "GamepadCamera":
  13603. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13604. case "TouchCamera":
  13605. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13606. case "VirtualJoysticksCamera":
  13607. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13608. case "WebVRFreeCamera":
  13609. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13610. case "WebVRGamepadCamera":
  13611. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13612. case "VRDeviceOrientationFreeCamera":
  13613. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13614. case "VRDeviceOrientationGamepadCamera":
  13615. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13616. case "AnaglyphArcRotateCamera":
  13617. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13618. case "AnaglyphFreeCamera":
  13619. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13620. case "AnaglyphGamepadCamera":
  13621. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13622. case "AnaglyphUniversalCamera":
  13623. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13624. case "StereoscopicArcRotateCamera":
  13625. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13626. case "StereoscopicFreeCamera":
  13627. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13628. case "StereoscopicGamepadCamera":
  13629. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13630. case "StereoscopicUniversalCamera":
  13631. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13632. case "FreeCamera":
  13633. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13634. default:
  13635. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13636. }
  13637. };
  13638. Camera.Parse = function (parsedCamera, scene) {
  13639. var type = parsedCamera.type;
  13640. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13641. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13642. // Parent
  13643. if (parsedCamera.parentId) {
  13644. camera._waitingParentId = parsedCamera.parentId;
  13645. }
  13646. //If camera has an input manager, let it parse inputs settings
  13647. if (camera.inputs) {
  13648. camera.inputs.parse(parsedCamera);
  13649. camera._setupInputs();
  13650. }
  13651. // Target
  13652. if (parsedCamera.target) {
  13653. if (camera.setTarget) {
  13654. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13655. }
  13656. }
  13657. // Apply 3d rig, when found
  13658. if (parsedCamera.cameraRigMode) {
  13659. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13660. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13661. }
  13662. // Animations
  13663. if (parsedCamera.animations) {
  13664. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13665. var parsedAnimation = parsedCamera.animations[animationIndex];
  13666. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13667. }
  13668. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13669. }
  13670. if (parsedCamera.autoAnimate) {
  13671. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13672. }
  13673. return camera;
  13674. };
  13675. return Camera;
  13676. }(BABYLON.Node));
  13677. // Statics
  13678. Camera._PERSPECTIVE_CAMERA = 0;
  13679. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13680. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13681. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13682. Camera._RIG_MODE_NONE = 0;
  13683. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13684. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13685. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13686. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13687. Camera._RIG_MODE_VR = 20;
  13688. Camera._RIG_MODE_WEBVR = 21;
  13689. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13690. __decorate([
  13691. BABYLON.serializeAsVector3()
  13692. ], Camera.prototype, "position", void 0);
  13693. __decorate([
  13694. BABYLON.serializeAsVector3()
  13695. ], Camera.prototype, "upVector", void 0);
  13696. __decorate([
  13697. BABYLON.serialize()
  13698. ], Camera.prototype, "orthoLeft", void 0);
  13699. __decorate([
  13700. BABYLON.serialize()
  13701. ], Camera.prototype, "orthoRight", void 0);
  13702. __decorate([
  13703. BABYLON.serialize()
  13704. ], Camera.prototype, "orthoBottom", void 0);
  13705. __decorate([
  13706. BABYLON.serialize()
  13707. ], Camera.prototype, "orthoTop", void 0);
  13708. __decorate([
  13709. BABYLON.serialize()
  13710. ], Camera.prototype, "fov", void 0);
  13711. __decorate([
  13712. BABYLON.serialize()
  13713. ], Camera.prototype, "minZ", void 0);
  13714. __decorate([
  13715. BABYLON.serialize()
  13716. ], Camera.prototype, "maxZ", void 0);
  13717. __decorate([
  13718. BABYLON.serialize()
  13719. ], Camera.prototype, "inertia", void 0);
  13720. __decorate([
  13721. BABYLON.serialize()
  13722. ], Camera.prototype, "mode", void 0);
  13723. __decorate([
  13724. BABYLON.serialize()
  13725. ], Camera.prototype, "layerMask", void 0);
  13726. __decorate([
  13727. BABYLON.serialize()
  13728. ], Camera.prototype, "fovMode", void 0);
  13729. __decorate([
  13730. BABYLON.serialize()
  13731. ], Camera.prototype, "cameraRigMode", void 0);
  13732. __decorate([
  13733. BABYLON.serialize()
  13734. ], Camera.prototype, "interaxialDistance", void 0);
  13735. __decorate([
  13736. BABYLON.serialize()
  13737. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13738. BABYLON.Camera = Camera;
  13739. })(BABYLON || (BABYLON = {}));
  13740. //# sourceMappingURL=babylon.camera.js.map
  13741. var BABYLON;
  13742. (function (BABYLON) {
  13743. var RenderingManager = (function () {
  13744. function RenderingManager(scene) {
  13745. this._renderingGroups = new Array();
  13746. this._autoClearDepthStencil = {};
  13747. this._customOpaqueSortCompareFn = {};
  13748. this._customAlphaTestSortCompareFn = {};
  13749. this._customTransparentSortCompareFn = {};
  13750. this._renderinGroupInfo = null;
  13751. this._scene = scene;
  13752. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  13753. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  13754. }
  13755. }
  13756. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  13757. if (depth === void 0) { depth = true; }
  13758. if (stencil === void 0) { stencil = true; }
  13759. if (this._depthStencilBufferAlreadyCleaned) {
  13760. return;
  13761. }
  13762. this._scene.getEngine().clear(null, false, depth, stencil);
  13763. this._depthStencilBufferAlreadyCleaned = true;
  13764. };
  13765. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13766. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  13767. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  13768. var info = null;
  13769. if (observable) {
  13770. if (!this._renderinGroupInfo) {
  13771. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  13772. }
  13773. info = this._renderinGroupInfo;
  13774. info.scene = this._scene;
  13775. info.camera = this._scene.activeCamera;
  13776. }
  13777. // Dispatch sprites
  13778. if (renderSprites) {
  13779. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  13780. var manager = this._scene.spriteManagers[index];
  13781. this.dispatchSprites(manager);
  13782. }
  13783. }
  13784. // Render
  13785. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13786. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  13787. var renderingGroup = this._renderingGroups[index];
  13788. if (!renderingGroup && !observable)
  13789. continue;
  13790. this._currentIndex = index;
  13791. var renderingGroupMask = 0;
  13792. // Fire PRECLEAR stage
  13793. if (observable) {
  13794. renderingGroupMask = Math.pow(2, index);
  13795. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  13796. info.renderingGroupId = index;
  13797. observable.notifyObservers(info, renderingGroupMask);
  13798. }
  13799. // Clear depth/stencil if needed
  13800. var autoClear = this._autoClearDepthStencil[index];
  13801. if (autoClear && autoClear.autoClear) {
  13802. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  13803. }
  13804. if (observable) {
  13805. // Fire PREOPAQUE stage
  13806. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  13807. observable.notifyObservers(info, renderingGroupMask);
  13808. // Fire PRETRANSPARENT stage
  13809. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  13810. observable.notifyObservers(info, renderingGroupMask);
  13811. }
  13812. if (renderingGroup)
  13813. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  13814. // Fire POSTTRANSPARENT stage
  13815. if (observable) {
  13816. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  13817. observable.notifyObservers(info, renderingGroupMask);
  13818. }
  13819. }
  13820. };
  13821. RenderingManager.prototype.reset = function () {
  13822. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13823. var renderingGroup = this._renderingGroups[index];
  13824. if (renderingGroup) {
  13825. renderingGroup.prepare();
  13826. }
  13827. }
  13828. };
  13829. RenderingManager.prototype.dispose = function () {
  13830. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13831. var renderingGroup = this._renderingGroups[index];
  13832. if (renderingGroup) {
  13833. renderingGroup.dispose();
  13834. }
  13835. }
  13836. this._renderingGroups.length = 0;
  13837. };
  13838. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  13839. if (!this._renderingGroups[renderingGroupId]) {
  13840. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  13841. }
  13842. };
  13843. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  13844. var renderingGroupId = spriteManager.renderingGroupId || 0;
  13845. this._prepareRenderingGroup(renderingGroupId);
  13846. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  13847. };
  13848. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  13849. var renderingGroupId = particleSystem.renderingGroupId || 0;
  13850. this._prepareRenderingGroup(renderingGroupId);
  13851. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  13852. };
  13853. RenderingManager.prototype.dispatch = function (subMesh) {
  13854. var mesh = subMesh.getMesh();
  13855. var renderingGroupId = mesh.renderingGroupId || 0;
  13856. this._prepareRenderingGroup(renderingGroupId);
  13857. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13858. };
  13859. /**
  13860. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  13861. * This allowed control for front to back rendering or reversly depending of the special needs.
  13862. *
  13863. * @param renderingGroupId The rendering group id corresponding to its index
  13864. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  13865. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  13866. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  13867. */
  13868. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  13869. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  13870. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  13871. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  13872. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  13873. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  13874. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  13875. if (this._renderingGroups[renderingGroupId]) {
  13876. var group = this._renderingGroups[renderingGroupId];
  13877. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  13878. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  13879. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  13880. }
  13881. };
  13882. /**
  13883. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  13884. *
  13885. * @param renderingGroupId The rendering group id corresponding to its index
  13886. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  13887. * @param depth Automatically clears depth between groups if true and autoClear is true.
  13888. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  13889. */
  13890. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  13891. if (depth === void 0) { depth = true; }
  13892. if (stencil === void 0) { stencil = true; }
  13893. this._autoClearDepthStencil[renderingGroupId] = {
  13894. autoClear: autoClearDepthStencil,
  13895. depth: depth,
  13896. stencil: stencil
  13897. };
  13898. };
  13899. return RenderingManager;
  13900. }());
  13901. /**
  13902. * The max id used for rendering groups (not included)
  13903. */
  13904. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13905. /**
  13906. * The min id used for rendering groups (included)
  13907. */
  13908. RenderingManager.MIN_RENDERINGGROUPS = 0;
  13909. BABYLON.RenderingManager = RenderingManager;
  13910. })(BABYLON || (BABYLON = {}));
  13911. //# sourceMappingURL=babylon.renderingManager.js.map
  13912. var BABYLON;
  13913. (function (BABYLON) {
  13914. var RenderingGroup = (function () {
  13915. /**
  13916. * Creates a new rendering group.
  13917. * @param index The rendering group index
  13918. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  13919. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  13920. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  13921. */
  13922. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  13923. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  13924. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  13925. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  13926. this.index = index;
  13927. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  13928. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  13929. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  13930. this._particleSystems = new BABYLON.SmartArray(256);
  13931. this._spriteManagers = new BABYLON.SmartArray(256);
  13932. this._scene = scene;
  13933. this.opaqueSortCompareFn = opaqueSortCompareFn;
  13934. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  13935. this.transparentSortCompareFn = transparentSortCompareFn;
  13936. }
  13937. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  13938. /**
  13939. * Set the opaque sort comparison function.
  13940. * If null the sub meshes will be render in the order they were created
  13941. */
  13942. set: function (value) {
  13943. this._opaqueSortCompareFn = value;
  13944. if (value) {
  13945. this._renderOpaque = this.renderOpaqueSorted;
  13946. }
  13947. else {
  13948. this._renderOpaque = RenderingGroup.renderUnsorted;
  13949. }
  13950. },
  13951. enumerable: true,
  13952. configurable: true
  13953. });
  13954. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  13955. /**
  13956. * Set the alpha test sort comparison function.
  13957. * If null the sub meshes will be render in the order they were created
  13958. */
  13959. set: function (value) {
  13960. this._alphaTestSortCompareFn = value;
  13961. if (value) {
  13962. this._renderAlphaTest = this.renderAlphaTestSorted;
  13963. }
  13964. else {
  13965. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  13966. }
  13967. },
  13968. enumerable: true,
  13969. configurable: true
  13970. });
  13971. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  13972. /**
  13973. * Set the transparent sort comparison function.
  13974. * If null the sub meshes will be render in the order they were created
  13975. */
  13976. set: function (value) {
  13977. if (value) {
  13978. this._transparentSortCompareFn = value;
  13979. }
  13980. else {
  13981. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  13982. }
  13983. this._renderTransparent = this.renderTransparentSorted;
  13984. },
  13985. enumerable: true,
  13986. configurable: true
  13987. });
  13988. /**
  13989. * Render all the sub meshes contained in the group.
  13990. * @param customRenderFunction Used to override the default render behaviour of the group.
  13991. * @returns true if rendered some submeshes.
  13992. */
  13993. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  13994. if (customRenderFunction) {
  13995. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  13996. return;
  13997. }
  13998. var engine = this._scene.getEngine();
  13999. // Opaque
  14000. if (this._opaqueSubMeshes.length !== 0) {
  14001. this._renderOpaque(this._opaqueSubMeshes);
  14002. }
  14003. // Alpha test
  14004. if (this._alphaTestSubMeshes.length !== 0) {
  14005. engine.setAlphaTesting(true);
  14006. this._renderAlphaTest(this._alphaTestSubMeshes);
  14007. engine.setAlphaTesting(false);
  14008. }
  14009. var stencilState = engine.getStencilBuffer();
  14010. engine.setStencilBuffer(false);
  14011. // Sprites
  14012. if (renderSprites) {
  14013. this._renderSprites();
  14014. }
  14015. // Particles
  14016. if (renderParticles) {
  14017. this._renderParticles(activeMeshes);
  14018. }
  14019. if (this.onBeforeTransparentRendering) {
  14020. this.onBeforeTransparentRendering();
  14021. }
  14022. // Transparent
  14023. if (this._transparentSubMeshes.length !== 0) {
  14024. this._renderTransparent(this._transparentSubMeshes);
  14025. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14026. }
  14027. engine.setStencilBuffer(stencilState);
  14028. };
  14029. /**
  14030. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14031. * @param subMeshes The submeshes to render
  14032. */
  14033. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14034. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14035. };
  14036. /**
  14037. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14038. * @param subMeshes The submeshes to render
  14039. */
  14040. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14041. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14042. };
  14043. /**
  14044. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14045. * @param subMeshes The submeshes to render
  14046. */
  14047. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14048. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14049. };
  14050. /**
  14051. * Renders the submeshes in a specified order.
  14052. * @param subMeshes The submeshes to sort before render
  14053. * @param sortCompareFn The comparison function use to sort
  14054. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14055. * @param transparent Specifies to activate blending if true
  14056. */
  14057. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14058. var subIndex = 0;
  14059. var subMesh;
  14060. for (; subIndex < subMeshes.length; subIndex++) {
  14061. subMesh = subMeshes.data[subIndex];
  14062. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14063. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14064. }
  14065. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14066. sortedArray.sort(sortCompareFn);
  14067. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14068. subMesh = sortedArray[subIndex];
  14069. subMesh.render(transparent);
  14070. }
  14071. };
  14072. /**
  14073. * Renders the submeshes in the order they were dispatched (no sort applied).
  14074. * @param subMeshes The submeshes to render
  14075. */
  14076. RenderingGroup.renderUnsorted = function (subMeshes) {
  14077. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14078. var submesh = subMeshes.data[subIndex];
  14079. submesh.render(false);
  14080. }
  14081. };
  14082. /**
  14083. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14084. * are rendered back to front if in the same alpha index.
  14085. *
  14086. * @param a The first submesh
  14087. * @param b The second submesh
  14088. * @returns The result of the comparison
  14089. */
  14090. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  14091. // Alpha index first
  14092. if (a._alphaIndex > b._alphaIndex) {
  14093. return 1;
  14094. }
  14095. if (a._alphaIndex < b._alphaIndex) {
  14096. return -1;
  14097. }
  14098. // Then distance to camera
  14099. return RenderingGroup.backToFrontSortCompare(a, b);
  14100. };
  14101. /**
  14102. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14103. * are rendered back to front.
  14104. *
  14105. * @param a The first submesh
  14106. * @param b The second submesh
  14107. * @returns The result of the comparison
  14108. */
  14109. RenderingGroup.backToFrontSortCompare = function (a, b) {
  14110. // Then distance to camera
  14111. if (a._distanceToCamera < b._distanceToCamera) {
  14112. return 1;
  14113. }
  14114. if (a._distanceToCamera > b._distanceToCamera) {
  14115. return -1;
  14116. }
  14117. return 0;
  14118. };
  14119. /**
  14120. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14121. * are rendered front to back (prevent overdraw).
  14122. *
  14123. * @param a The first submesh
  14124. * @param b The second submesh
  14125. * @returns The result of the comparison
  14126. */
  14127. RenderingGroup.frontToBackSortCompare = function (a, b) {
  14128. // Then distance to camera
  14129. if (a._distanceToCamera < b._distanceToCamera) {
  14130. return -1;
  14131. }
  14132. if (a._distanceToCamera > b._distanceToCamera) {
  14133. return 1;
  14134. }
  14135. return 0;
  14136. };
  14137. /**
  14138. * Resets the different lists of submeshes to prepare a new frame.
  14139. */
  14140. RenderingGroup.prototype.prepare = function () {
  14141. this._opaqueSubMeshes.reset();
  14142. this._transparentSubMeshes.reset();
  14143. this._alphaTestSubMeshes.reset();
  14144. this._particleSystems.reset();
  14145. this._spriteManagers.reset();
  14146. };
  14147. RenderingGroup.prototype.dispose = function () {
  14148. this._opaqueSubMeshes.dispose();
  14149. this._transparentSubMeshes.dispose();
  14150. this._alphaTestSubMeshes.dispose();
  14151. this._particleSystems.dispose();
  14152. this._spriteManagers.dispose();
  14153. };
  14154. /**
  14155. * Inserts the submesh in its correct queue depending on its material.
  14156. * @param subMesh The submesh to dispatch
  14157. */
  14158. RenderingGroup.prototype.dispatch = function (subMesh) {
  14159. var material = subMesh.getMaterial();
  14160. var mesh = subMesh.getMesh();
  14161. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14162. this._transparentSubMeshes.push(subMesh);
  14163. }
  14164. else if (material.needAlphaTesting()) {
  14165. this._alphaTestSubMeshes.push(subMesh);
  14166. }
  14167. else {
  14168. this._opaqueSubMeshes.push(subMesh); // Opaque
  14169. }
  14170. };
  14171. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  14172. this._spriteManagers.push(spriteManager);
  14173. };
  14174. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  14175. this._particleSystems.push(particleSystem);
  14176. };
  14177. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  14178. if (this._particleSystems.length === 0) {
  14179. return;
  14180. }
  14181. // Particles
  14182. var activeCamera = this._scene.activeCamera;
  14183. this._scene._particlesDuration.beginMonitoring();
  14184. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14185. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14186. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14187. continue;
  14188. }
  14189. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14190. this._scene._activeParticles.addCount(particleSystem.render(), false);
  14191. }
  14192. }
  14193. this._scene._particlesDuration.endMonitoring(false);
  14194. };
  14195. RenderingGroup.prototype._renderSprites = function () {
  14196. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  14197. return;
  14198. }
  14199. // Sprites
  14200. var activeCamera = this._scene.activeCamera;
  14201. this._scene._spritesDuration.beginMonitoring();
  14202. for (var id = 0; id < this._spriteManagers.length; id++) {
  14203. var spriteManager = this._spriteManagers.data[id];
  14204. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14205. spriteManager.render();
  14206. }
  14207. }
  14208. this._scene._spritesDuration.endMonitoring(false);
  14209. };
  14210. return RenderingGroup;
  14211. }());
  14212. BABYLON.RenderingGroup = RenderingGroup;
  14213. })(BABYLON || (BABYLON = {}));
  14214. //# sourceMappingURL=babylon.renderingGroup.js.map
  14215. var BABYLON;
  14216. (function (BABYLON) {
  14217. var ClickInfo = (function () {
  14218. function ClickInfo() {
  14219. this._singleClick = false;
  14220. this._doubleClick = false;
  14221. this._hasSwiped = false;
  14222. this._ignore = false;
  14223. }
  14224. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  14225. get: function () {
  14226. return this._singleClick;
  14227. },
  14228. set: function (b) {
  14229. this._singleClick = b;
  14230. },
  14231. enumerable: true,
  14232. configurable: true
  14233. });
  14234. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  14235. get: function () {
  14236. return this._doubleClick;
  14237. },
  14238. set: function (b) {
  14239. this._doubleClick = b;
  14240. },
  14241. enumerable: true,
  14242. configurable: true
  14243. });
  14244. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  14245. get: function () {
  14246. return this._hasSwiped;
  14247. },
  14248. set: function (b) {
  14249. this._hasSwiped = b;
  14250. },
  14251. enumerable: true,
  14252. configurable: true
  14253. });
  14254. Object.defineProperty(ClickInfo.prototype, "ignore", {
  14255. get: function () {
  14256. return this._ignore;
  14257. },
  14258. set: function (b) {
  14259. this._ignore = b;
  14260. },
  14261. enumerable: true,
  14262. configurable: true
  14263. });
  14264. return ClickInfo;
  14265. }());
  14266. var PointerEventTypes = (function () {
  14267. function PointerEventTypes() {
  14268. }
  14269. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14270. get: function () {
  14271. return PointerEventTypes._POINTERDOWN;
  14272. },
  14273. enumerable: true,
  14274. configurable: true
  14275. });
  14276. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14277. get: function () {
  14278. return PointerEventTypes._POINTERUP;
  14279. },
  14280. enumerable: true,
  14281. configurable: true
  14282. });
  14283. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14284. get: function () {
  14285. return PointerEventTypes._POINTERMOVE;
  14286. },
  14287. enumerable: true,
  14288. configurable: true
  14289. });
  14290. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14291. get: function () {
  14292. return PointerEventTypes._POINTERWHEEL;
  14293. },
  14294. enumerable: true,
  14295. configurable: true
  14296. });
  14297. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14298. get: function () {
  14299. return PointerEventTypes._POINTERPICK;
  14300. },
  14301. enumerable: true,
  14302. configurable: true
  14303. });
  14304. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  14305. get: function () {
  14306. return PointerEventTypes._POINTERTAP;
  14307. },
  14308. enumerable: true,
  14309. configurable: true
  14310. });
  14311. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  14312. get: function () {
  14313. return PointerEventTypes._POINTERDOUBLETAP;
  14314. },
  14315. enumerable: true,
  14316. configurable: true
  14317. });
  14318. return PointerEventTypes;
  14319. }());
  14320. PointerEventTypes._POINTERDOWN = 0x01;
  14321. PointerEventTypes._POINTERUP = 0x02;
  14322. PointerEventTypes._POINTERMOVE = 0x04;
  14323. PointerEventTypes._POINTERWHEEL = 0x08;
  14324. PointerEventTypes._POINTERPICK = 0x10;
  14325. PointerEventTypes._POINTERTAP = 0x20;
  14326. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  14327. BABYLON.PointerEventTypes = PointerEventTypes;
  14328. var PointerInfoBase = (function () {
  14329. function PointerInfoBase(type, event) {
  14330. this.type = type;
  14331. this.event = event;
  14332. }
  14333. return PointerInfoBase;
  14334. }());
  14335. BABYLON.PointerInfoBase = PointerInfoBase;
  14336. /**
  14337. * This class is used to store pointer related info for the onPrePointerObservable event.
  14338. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  14339. */
  14340. var PointerInfoPre = (function (_super) {
  14341. __extends(PointerInfoPre, _super);
  14342. function PointerInfoPre(type, event, localX, localY) {
  14343. var _this = _super.call(this, type, event) || this;
  14344. _this.skipOnPointerObservable = false;
  14345. _this.localPosition = new BABYLON.Vector2(localX, localY);
  14346. return _this;
  14347. }
  14348. return PointerInfoPre;
  14349. }(PointerInfoBase));
  14350. BABYLON.PointerInfoPre = PointerInfoPre;
  14351. /**
  14352. * This type contains all the data related to a pointer event in Babylon.js.
  14353. * 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.
  14354. */
  14355. var PointerInfo = (function (_super) {
  14356. __extends(PointerInfo, _super);
  14357. function PointerInfo(type, event, pickInfo) {
  14358. var _this = _super.call(this, type, event) || this;
  14359. _this.pickInfo = pickInfo;
  14360. return _this;
  14361. }
  14362. return PointerInfo;
  14363. }(PointerInfoBase));
  14364. BABYLON.PointerInfo = PointerInfo;
  14365. /**
  14366. * This class is used by the onRenderingGroupObservable
  14367. */
  14368. var RenderingGroupInfo = (function () {
  14369. function RenderingGroupInfo() {
  14370. }
  14371. return RenderingGroupInfo;
  14372. }());
  14373. /**
  14374. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  14375. * This stage will be fired no matter what
  14376. */
  14377. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  14378. /**
  14379. * Called before opaque object are rendered.
  14380. * This stage will be fired only if there's 3D Opaque content to render
  14381. */
  14382. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  14383. /**
  14384. * Called after the opaque objects are rendered and before the transparent ones
  14385. * This stage will be fired only if there's 3D transparent content to render
  14386. */
  14387. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  14388. /**
  14389. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  14390. * This stage will be fired no matter what
  14391. */
  14392. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  14393. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  14394. /**
  14395. * Represents a scene to be rendered by the engine.
  14396. * @see http://doc.babylonjs.com/page.php?p=21911
  14397. */
  14398. var Scene = (function () {
  14399. /**
  14400. * @constructor
  14401. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14402. */
  14403. function Scene(engine) {
  14404. // Members
  14405. this.autoClear = true;
  14406. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  14407. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14408. this.forceWireframe = false;
  14409. this._forcePointsCloud = false;
  14410. this.forceShowBoundingBoxes = false;
  14411. this.animationsEnabled = true;
  14412. this.constantlyUpdateMeshUnderPointer = false;
  14413. this.useRightHandedSystem = false;
  14414. this.hoverCursor = "pointer";
  14415. // Metadata
  14416. this.metadata = null;
  14417. // Events
  14418. /**
  14419. * An event triggered when the scene is disposed.
  14420. * @type {BABYLON.Observable}
  14421. */
  14422. this.onDisposeObservable = new BABYLON.Observable();
  14423. /**
  14424. * An event triggered before rendering the scene
  14425. * @type {BABYLON.Observable}
  14426. */
  14427. this.onBeforeRenderObservable = new BABYLON.Observable();
  14428. /**
  14429. * An event triggered after rendering the scene
  14430. * @type {BABYLON.Observable}
  14431. */
  14432. this.onAfterRenderObservable = new BABYLON.Observable();
  14433. /**
  14434. * An event triggered when the scene is ready
  14435. * @type {BABYLON.Observable}
  14436. */
  14437. this.onReadyObservable = new BABYLON.Observable();
  14438. /**
  14439. * An event triggered before rendering a camera
  14440. * @type {BABYLON.Observable}
  14441. */
  14442. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14443. /**
  14444. * An event triggered after rendering a camera
  14445. * @type {BABYLON.Observable}
  14446. */
  14447. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14448. /**
  14449. * An event triggered when a camera is created
  14450. * @type {BABYLON.Observable}
  14451. */
  14452. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14453. /**
  14454. * An event triggered when a camera is removed
  14455. * @type {BABYLON.Observable}
  14456. */
  14457. this.onCameraRemovedObservable = new BABYLON.Observable();
  14458. /**
  14459. * An event triggered when a light is created
  14460. * @type {BABYLON.Observable}
  14461. */
  14462. this.onNewLightAddedObservable = new BABYLON.Observable();
  14463. /**
  14464. * An event triggered when a light is removed
  14465. * @type {BABYLON.Observable}
  14466. */
  14467. this.onLightRemovedObservable = new BABYLON.Observable();
  14468. /**
  14469. * An event triggered when a geometry is created
  14470. * @type {BABYLON.Observable}
  14471. */
  14472. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14473. /**
  14474. * An event triggered when a geometry is removed
  14475. * @type {BABYLON.Observable}
  14476. */
  14477. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14478. /**
  14479. * An event triggered when a mesh is created
  14480. * @type {BABYLON.Observable}
  14481. */
  14482. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14483. /**
  14484. * An event triggered when a mesh is removed
  14485. * @type {BABYLON.Observable}
  14486. */
  14487. this.onMeshRemovedObservable = new BABYLON.Observable();
  14488. /**
  14489. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  14490. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  14491. * 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)
  14492. */
  14493. this.onRenderingGroupObservable = new BABYLON.Observable();
  14494. // Animations
  14495. this.animations = [];
  14496. /**
  14497. * 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).
  14498. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  14499. */
  14500. this.onPrePointerObservable = new BABYLON.Observable();
  14501. /**
  14502. * Observable event triggered each time an input event is received from the rendering canvas
  14503. */
  14504. this.onPointerObservable = new BABYLON.Observable();
  14505. this._meshPickProceed = false;
  14506. this._previousHasSwiped = false;
  14507. this._currentPickResult = null;
  14508. this._previousPickResult = null;
  14509. this._isButtonPressed = false;
  14510. this._doubleClickOccured = false;
  14511. 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
  14512. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14513. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  14514. this._startingPointerTime = 0;
  14515. this._previousStartingPointerTime = 0;
  14516. // Fog
  14517. /**
  14518. * is fog enabled on this scene.
  14519. * @type {boolean}
  14520. */
  14521. this._fogEnabled = true;
  14522. this._fogMode = Scene.FOGMODE_NONE;
  14523. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14524. this.fogDensity = 0.1;
  14525. this.fogStart = 0;
  14526. this.fogEnd = 1000.0;
  14527. // Lights
  14528. /**
  14529. * is shadow enabled on this scene.
  14530. * @type {boolean}
  14531. */
  14532. this._shadowsEnabled = true;
  14533. /**
  14534. * is light enabled on this scene.
  14535. * @type {boolean}
  14536. */
  14537. this._lightsEnabled = true;
  14538. /**
  14539. * All of the lights added to this scene.
  14540. * @see BABYLON.Light
  14541. * @type {BABYLON.Light[]}
  14542. */
  14543. this.lights = new Array();
  14544. // Cameras
  14545. /**
  14546. * All of the cameras added to this scene.
  14547. * @see BABYLON.Camera
  14548. * @type {BABYLON.Camera[]}
  14549. */
  14550. this.cameras = new Array();
  14551. this.activeCameras = new Array();
  14552. // Meshes
  14553. /**
  14554. * All of the (abstract) meshes added to this scene.
  14555. * @see BABYLON.AbstractMesh
  14556. * @type {BABYLON.AbstractMesh[]}
  14557. */
  14558. this.meshes = new Array();
  14559. // Geometries
  14560. this._geometries = new Array();
  14561. this.materials = new Array();
  14562. this.multiMaterials = new Array();
  14563. // Textures
  14564. this._texturesEnabled = true;
  14565. this.textures = new Array();
  14566. // Particles
  14567. this.particlesEnabled = true;
  14568. this.particleSystems = new Array();
  14569. // Sprites
  14570. this.spritesEnabled = true;
  14571. this.spriteManagers = new Array();
  14572. // Layers
  14573. this.layers = new Array();
  14574. this.highlightLayers = new Array();
  14575. // Skeletons
  14576. this._skeletonsEnabled = true;
  14577. this.skeletons = new Array();
  14578. // Morph targets
  14579. this.morphTargetManagers = new Array();
  14580. // Lens flares
  14581. this.lensFlaresEnabled = true;
  14582. this.lensFlareSystems = new Array();
  14583. // Collisions
  14584. this.collisionsEnabled = true;
  14585. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14586. // Postprocesses
  14587. this.postProcessesEnabled = true;
  14588. // Customs render targets
  14589. this.renderTargetsEnabled = true;
  14590. this.dumpNextRenderTargets = false;
  14591. this.customRenderTargets = new Array();
  14592. // Imported meshes
  14593. this.importedMeshesFiles = new Array();
  14594. // Probes
  14595. this.probesEnabled = true;
  14596. this.reflectionProbes = new Array();
  14597. this._actionManagers = new Array();
  14598. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14599. // Procedural textures
  14600. this.proceduralTexturesEnabled = true;
  14601. this._proceduralTextures = new Array();
  14602. this.soundTracks = new Array();
  14603. this._audioEnabled = true;
  14604. this._headphone = false;
  14605. // Performance counters
  14606. this._totalMeshesCounter = new BABYLON.PerfCounter();
  14607. this._totalLightsCounter = new BABYLON.PerfCounter();
  14608. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  14609. this._totalTexturesCounter = new BABYLON.PerfCounter();
  14610. this._totalVertices = new BABYLON.PerfCounter();
  14611. this._activeIndices = new BABYLON.PerfCounter();
  14612. this._activeParticles = new BABYLON.PerfCounter();
  14613. this._lastFrameDuration = new BABYLON.PerfCounter();
  14614. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  14615. this._renderTargetsDuration = new BABYLON.PerfCounter();
  14616. this._particlesDuration = new BABYLON.PerfCounter();
  14617. this._renderDuration = new BABYLON.PerfCounter();
  14618. this._spritesDuration = new BABYLON.PerfCounter();
  14619. this._activeBones = new BABYLON.PerfCounter();
  14620. this._animationTime = 0;
  14621. this.animationTimeScale = 1;
  14622. this._renderId = 0;
  14623. this._executeWhenReadyTimeoutId = -1;
  14624. this._intermediateRendering = false;
  14625. this._viewUpdateFlag = -1;
  14626. this._projectionUpdateFlag = -1;
  14627. this._toBeDisposed = new BABYLON.SmartArray(256);
  14628. this._pendingData = []; //ANY
  14629. this._activeMeshes = new BABYLON.SmartArray(256);
  14630. this._processedMaterials = new BABYLON.SmartArray(256);
  14631. this._renderTargets = new BABYLON.SmartArray(256);
  14632. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14633. this._activeSkeletons = new BABYLON.SmartArray(32);
  14634. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14635. this._activeAnimatables = new Array();
  14636. this._transformMatrix = BABYLON.Matrix.Zero();
  14637. this._edgesRenderers = new BABYLON.SmartArray(16);
  14638. this._uniqueIdCounter = 0;
  14639. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  14640. this._engine.scenes.push(this);
  14641. this._uid = null;
  14642. this._renderingManager = new BABYLON.RenderingManager(this);
  14643. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14644. if (BABYLON.OutlineRenderer) {
  14645. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14646. }
  14647. this.attachControl();
  14648. if (BABYLON.SoundTrack) {
  14649. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14650. }
  14651. //simplification queue
  14652. if (BABYLON.SimplificationQueue) {
  14653. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14654. }
  14655. //collision coordinator initialization. For now legacy per default.
  14656. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14657. }
  14658. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14659. get: function () {
  14660. return Scene._FOGMODE_NONE;
  14661. },
  14662. enumerable: true,
  14663. configurable: true
  14664. });
  14665. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14666. get: function () {
  14667. return Scene._FOGMODE_EXP;
  14668. },
  14669. enumerable: true,
  14670. configurable: true
  14671. });
  14672. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14673. get: function () {
  14674. return Scene._FOGMODE_EXP2;
  14675. },
  14676. enumerable: true,
  14677. configurable: true
  14678. });
  14679. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14680. get: function () {
  14681. return Scene._FOGMODE_LINEAR;
  14682. },
  14683. enumerable: true,
  14684. configurable: true
  14685. });
  14686. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  14687. get: function () {
  14688. return this._forcePointsCloud;
  14689. },
  14690. set: function (value) {
  14691. if (this._forcePointsCloud === value) {
  14692. return;
  14693. }
  14694. this._forcePointsCloud = value;
  14695. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14696. },
  14697. enumerable: true,
  14698. configurable: true
  14699. });
  14700. Object.defineProperty(Scene.prototype, "onDispose", {
  14701. set: function (callback) {
  14702. if (this._onDisposeObserver) {
  14703. this.onDisposeObservable.remove(this._onDisposeObserver);
  14704. }
  14705. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14706. },
  14707. enumerable: true,
  14708. configurable: true
  14709. });
  14710. Object.defineProperty(Scene.prototype, "beforeRender", {
  14711. set: function (callback) {
  14712. if (this._onBeforeRenderObserver) {
  14713. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14714. }
  14715. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14716. },
  14717. enumerable: true,
  14718. configurable: true
  14719. });
  14720. Object.defineProperty(Scene.prototype, "afterRender", {
  14721. set: function (callback) {
  14722. if (this._onAfterRenderObserver) {
  14723. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14724. }
  14725. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14726. },
  14727. enumerable: true,
  14728. configurable: true
  14729. });
  14730. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14731. set: function (callback) {
  14732. if (this._onBeforeCameraRenderObserver) {
  14733. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14734. }
  14735. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14736. },
  14737. enumerable: true,
  14738. configurable: true
  14739. });
  14740. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14741. set: function (callback) {
  14742. if (this._onAfterCameraRenderObserver) {
  14743. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14744. }
  14745. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14746. },
  14747. enumerable: true,
  14748. configurable: true
  14749. });
  14750. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  14751. get: function () {
  14752. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  14753. },
  14754. enumerable: true,
  14755. configurable: true
  14756. });
  14757. Object.defineProperty(Scene.prototype, "fogEnabled", {
  14758. get: function () {
  14759. return this._fogEnabled;
  14760. },
  14761. set: function (value) {
  14762. if (this._fogEnabled === value) {
  14763. return;
  14764. }
  14765. this._fogEnabled = value;
  14766. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14767. },
  14768. enumerable: true,
  14769. configurable: true
  14770. });
  14771. Object.defineProperty(Scene.prototype, "fogMode", {
  14772. get: function () {
  14773. return this._fogMode;
  14774. },
  14775. set: function (value) {
  14776. if (this._fogMode === value) {
  14777. return;
  14778. }
  14779. this._fogMode = value;
  14780. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14781. },
  14782. enumerable: true,
  14783. configurable: true
  14784. });
  14785. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  14786. get: function () {
  14787. return this._shadowsEnabled;
  14788. },
  14789. set: function (value) {
  14790. if (this._shadowsEnabled === value) {
  14791. return;
  14792. }
  14793. this._shadowsEnabled = value;
  14794. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  14795. },
  14796. enumerable: true,
  14797. configurable: true
  14798. });
  14799. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  14800. get: function () {
  14801. return this._lightsEnabled;
  14802. },
  14803. set: function (value) {
  14804. if (this._lightsEnabled === value) {
  14805. return;
  14806. }
  14807. this._lightsEnabled = value;
  14808. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  14809. },
  14810. enumerable: true,
  14811. configurable: true
  14812. });
  14813. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  14814. get: function () {
  14815. if (!this._defaultMaterial) {
  14816. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14817. }
  14818. return this._defaultMaterial;
  14819. },
  14820. enumerable: true,
  14821. configurable: true
  14822. });
  14823. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  14824. get: function () {
  14825. return this._texturesEnabled;
  14826. },
  14827. set: function (value) {
  14828. if (this._texturesEnabled === value) {
  14829. return;
  14830. }
  14831. this._texturesEnabled = value;
  14832. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  14833. },
  14834. enumerable: true,
  14835. configurable: true
  14836. });
  14837. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  14838. get: function () {
  14839. return this._skeletonsEnabled;
  14840. },
  14841. set: function (value) {
  14842. if (this._skeletonsEnabled === value) {
  14843. return;
  14844. }
  14845. this._skeletonsEnabled = value;
  14846. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  14847. },
  14848. enumerable: true,
  14849. configurable: true
  14850. });
  14851. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  14852. get: function () {
  14853. if (!this._postProcessRenderPipelineManager) {
  14854. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14855. }
  14856. return this._postProcessRenderPipelineManager;
  14857. },
  14858. enumerable: true,
  14859. configurable: true
  14860. });
  14861. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  14862. get: function () {
  14863. return this._frustumPlanes;
  14864. },
  14865. enumerable: true,
  14866. configurable: true
  14867. });
  14868. Object.defineProperty(Scene.prototype, "debugLayer", {
  14869. // Properties
  14870. get: function () {
  14871. if (!this._debugLayer) {
  14872. this._debugLayer = new BABYLON.DebugLayer(this);
  14873. }
  14874. return this._debugLayer;
  14875. },
  14876. enumerable: true,
  14877. configurable: true
  14878. });
  14879. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14880. get: function () {
  14881. return this._workerCollisions;
  14882. },
  14883. set: function (enabled) {
  14884. if (!BABYLON.CollisionCoordinatorLegacy) {
  14885. return;
  14886. }
  14887. enabled = (enabled && !!Worker);
  14888. this._workerCollisions = enabled;
  14889. if (this.collisionCoordinator) {
  14890. this.collisionCoordinator.destroy();
  14891. }
  14892. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14893. this.collisionCoordinator.init(this);
  14894. },
  14895. enumerable: true,
  14896. configurable: true
  14897. });
  14898. Object.defineProperty(Scene.prototype, "selectionOctree", {
  14899. get: function () {
  14900. return this._selectionOctree;
  14901. },
  14902. enumerable: true,
  14903. configurable: true
  14904. });
  14905. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14906. /**
  14907. * The mesh that is currently under the pointer.
  14908. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14909. */
  14910. get: function () {
  14911. return this._pointerOverMesh;
  14912. },
  14913. enumerable: true,
  14914. configurable: true
  14915. });
  14916. Object.defineProperty(Scene.prototype, "pointerX", {
  14917. /**
  14918. * Current on-screen X position of the pointer
  14919. * @return {number} X position of the pointer
  14920. */
  14921. get: function () {
  14922. return this._pointerX;
  14923. },
  14924. enumerable: true,
  14925. configurable: true
  14926. });
  14927. Object.defineProperty(Scene.prototype, "pointerY", {
  14928. /**
  14929. * Current on-screen Y position of the pointer
  14930. * @return {number} Y position of the pointer
  14931. */
  14932. get: function () {
  14933. return this._pointerY;
  14934. },
  14935. enumerable: true,
  14936. configurable: true
  14937. });
  14938. Scene.prototype.getCachedMaterial = function () {
  14939. return this._cachedMaterial;
  14940. };
  14941. Scene.prototype.getCachedEffect = function () {
  14942. return this._cachedEffect;
  14943. };
  14944. Scene.prototype.getBoundingBoxRenderer = function () {
  14945. if (!this._boundingBoxRenderer) {
  14946. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14947. }
  14948. return this._boundingBoxRenderer;
  14949. };
  14950. Scene.prototype.getOutlineRenderer = function () {
  14951. return this._outlineRenderer;
  14952. };
  14953. Scene.prototype.getEngine = function () {
  14954. return this._engine;
  14955. };
  14956. Scene.prototype.getTotalVertices = function () {
  14957. return this._totalVertices.current;
  14958. };
  14959. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  14960. get: function () {
  14961. return this._totalVertices;
  14962. },
  14963. enumerable: true,
  14964. configurable: true
  14965. });
  14966. Scene.prototype.getActiveIndices = function () {
  14967. return this._activeIndices.current;
  14968. };
  14969. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  14970. get: function () {
  14971. return this._activeIndices;
  14972. },
  14973. enumerable: true,
  14974. configurable: true
  14975. });
  14976. Scene.prototype.getActiveParticles = function () {
  14977. return this._activeParticles.current;
  14978. };
  14979. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  14980. get: function () {
  14981. return this._activeParticles;
  14982. },
  14983. enumerable: true,
  14984. configurable: true
  14985. });
  14986. Scene.prototype.getActiveBones = function () {
  14987. return this._activeBones.current;
  14988. };
  14989. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  14990. get: function () {
  14991. return this._activeBones;
  14992. },
  14993. enumerable: true,
  14994. configurable: true
  14995. });
  14996. // Stats
  14997. Scene.prototype.getLastFrameDuration = function () {
  14998. return this._lastFrameDuration.current;
  14999. };
  15000. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15001. get: function () {
  15002. return this._lastFrameDuration;
  15003. },
  15004. enumerable: true,
  15005. configurable: true
  15006. });
  15007. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15008. return this._evaluateActiveMeshesDuration.current;
  15009. };
  15010. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15011. get: function () {
  15012. return this._evaluateActiveMeshesDuration;
  15013. },
  15014. enumerable: true,
  15015. configurable: true
  15016. });
  15017. Scene.prototype.getActiveMeshes = function () {
  15018. return this._activeMeshes;
  15019. };
  15020. Scene.prototype.getRenderTargetsDuration = function () {
  15021. return this._renderTargetsDuration.current;
  15022. };
  15023. Scene.prototype.getRenderDuration = function () {
  15024. return this._renderDuration.current;
  15025. };
  15026. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15027. get: function () {
  15028. return this._renderDuration;
  15029. },
  15030. enumerable: true,
  15031. configurable: true
  15032. });
  15033. Scene.prototype.getParticlesDuration = function () {
  15034. return this._particlesDuration.current;
  15035. };
  15036. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15037. get: function () {
  15038. return this._particlesDuration;
  15039. },
  15040. enumerable: true,
  15041. configurable: true
  15042. });
  15043. Scene.prototype.getSpritesDuration = function () {
  15044. return this._spritesDuration.current;
  15045. };
  15046. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15047. get: function () {
  15048. return this._spritesDuration;
  15049. },
  15050. enumerable: true,
  15051. configurable: true
  15052. });
  15053. Scene.prototype.getAnimationRatio = function () {
  15054. return this._animationRatio;
  15055. };
  15056. Scene.prototype.getRenderId = function () {
  15057. return this._renderId;
  15058. };
  15059. Scene.prototype.incrementRenderId = function () {
  15060. this._renderId++;
  15061. };
  15062. Scene.prototype._updatePointerPosition = function (evt) {
  15063. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15064. this._pointerX = evt.clientX - canvasRect.left;
  15065. this._pointerY = evt.clientY - canvasRect.top;
  15066. this._unTranslatedPointerX = this._pointerX;
  15067. this._unTranslatedPointerY = this._pointerY;
  15068. if (this.cameraToUseForPointers) {
  15069. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15070. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15071. }
  15072. };
  15073. // Pointers handling
  15074. /**
  15075. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15076. * @param attachUp defines if you want to attach events to pointerup
  15077. * @param attachDown defines if you want to attach events to pointerdown
  15078. * @param attachMove defines if you want to attach events to pointermove
  15079. */
  15080. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15081. var _this = this;
  15082. if (attachUp === void 0) { attachUp = true; }
  15083. if (attachDown === void 0) { attachDown = true; }
  15084. if (attachMove === void 0) { attachMove = true; }
  15085. this._initActionManager = function (act, clickInfo) {
  15086. if (!_this._meshPickProceed) {
  15087. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15088. _this._currentPickResult = pickResult;
  15089. if (pickResult) {
  15090. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  15091. }
  15092. _this._meshPickProceed = true;
  15093. }
  15094. return act;
  15095. };
  15096. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  15097. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  15098. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  15099. btn !== _this._previousButtonPressed) {
  15100. _this._doubleClickOccured = false;
  15101. clickInfo.singleClick = true;
  15102. clickInfo.ignore = false;
  15103. cb(clickInfo, _this._currentPickResult);
  15104. }
  15105. };
  15106. this._initClickEvent = function (obs1, obs2, evt, cb) {
  15107. var clickInfo = new ClickInfo();
  15108. _this._currentPickResult = null;
  15109. var act;
  15110. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  15111. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  15112. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15113. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  15114. act = _this._initActionManager(act, clickInfo);
  15115. if (act)
  15116. checkPicking = act.hasPickTriggers;
  15117. }
  15118. if (checkPicking) {
  15119. var btn = evt.button;
  15120. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  15121. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  15122. if (!clickInfo.hasSwiped) {
  15123. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  15124. if (!checkSingleClickImmediately) {
  15125. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  15126. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15127. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15128. act = _this._initActionManager(act, clickInfo);
  15129. if (act)
  15130. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  15131. }
  15132. }
  15133. if (checkSingleClickImmediately) {
  15134. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  15135. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  15136. btn !== _this._previousButtonPressed) {
  15137. clickInfo.singleClick = true;
  15138. cb(clickInfo, _this._currentPickResult);
  15139. }
  15140. }
  15141. else {
  15142. // wait that no double click has been raised during the double click delay
  15143. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15144. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  15145. }
  15146. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  15147. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15148. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15149. act = _this._initActionManager(act, clickInfo);
  15150. if (act)
  15151. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  15152. }
  15153. if (checkDoubleClick) {
  15154. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  15155. if (btn === _this._previousButtonPressed &&
  15156. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  15157. !_this._doubleClickOccured) {
  15158. // pointer has not moved for 2 clicks, it's a double click
  15159. if (!clickInfo.hasSwiped &&
  15160. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  15161. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  15162. _this._previousStartingPointerTime = 0;
  15163. _this._doubleClickOccured = true;
  15164. clickInfo.doubleClick = true;
  15165. clickInfo.ignore = false;
  15166. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  15167. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  15168. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15169. cb(clickInfo, _this._currentPickResult);
  15170. }
  15171. else {
  15172. _this._doubleClickOccured = false;
  15173. _this._previousStartingPointerTime = _this._startingPointerTime;
  15174. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  15175. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  15176. _this._previousButtonPressed = btn;
  15177. _this._previousHasSwiped = clickInfo.hasSwiped;
  15178. if (Scene.ExclusiveDoubleClickMode) {
  15179. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  15180. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  15181. }
  15182. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15183. cb(clickInfo, _this._previousPickResult);
  15184. }
  15185. else {
  15186. cb(clickInfo, _this._currentPickResult);
  15187. }
  15188. }
  15189. }
  15190. else {
  15191. _this._doubleClickOccured = false;
  15192. _this._previousStartingPointerTime = _this._startingPointerTime;
  15193. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  15194. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  15195. _this._previousButtonPressed = btn;
  15196. _this._previousHasSwiped = clickInfo.hasSwiped;
  15197. }
  15198. }
  15199. }
  15200. }
  15201. clickInfo.ignore = true;
  15202. cb(clickInfo, _this._currentPickResult);
  15203. };
  15204. var spritePredicate = function (sprite) {
  15205. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  15206. };
  15207. this._onPointerMove = function (evt) {
  15208. _this._updatePointerPosition(evt);
  15209. // PreObservable support
  15210. if (_this.onPrePointerObservable.hasObservers()) {
  15211. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15212. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15213. _this.onPrePointerObservable.notifyObservers(pi, type);
  15214. if (pi.skipOnPointerObservable) {
  15215. return;
  15216. }
  15217. }
  15218. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15219. return;
  15220. }
  15221. var canvas = _this._engine.getRenderingCanvas();
  15222. if (!_this.pointerMovePredicate) {
  15223. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  15224. }
  15225. // Meshes
  15226. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  15227. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15228. _this.setPointerOverSprite(null);
  15229. _this.setPointerOverMesh(pickResult.pickedMesh);
  15230. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  15231. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  15232. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  15233. }
  15234. else {
  15235. canvas.style.cursor = _this.hoverCursor;
  15236. }
  15237. }
  15238. else {
  15239. canvas.style.cursor = "";
  15240. }
  15241. }
  15242. else {
  15243. _this.setPointerOverMesh(null);
  15244. // Sprites
  15245. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15246. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  15247. _this.setPointerOverSprite(pickResult.pickedSprite);
  15248. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  15249. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  15250. }
  15251. else {
  15252. canvas.style.cursor = _this.hoverCursor;
  15253. }
  15254. }
  15255. else {
  15256. _this.setPointerOverSprite(null);
  15257. // Restore pointer
  15258. canvas.style.cursor = "";
  15259. }
  15260. }
  15261. if (_this.onPointerMove) {
  15262. _this.onPointerMove(evt, pickResult);
  15263. }
  15264. if (_this.onPointerObservable.hasObservers()) {
  15265. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15266. var pi = new PointerInfo(type, evt, pickResult);
  15267. _this.onPointerObservable.notifyObservers(pi, type);
  15268. }
  15269. };
  15270. this._onPointerDown = function (evt) {
  15271. _this._isButtonPressed = true;
  15272. _this._pickedDownMesh = null;
  15273. _this._meshPickProceed = false;
  15274. _this._updatePointerPosition(evt);
  15275. // PreObservable support
  15276. if (_this.onPrePointerObservable.hasObservers()) {
  15277. var type = PointerEventTypes.POINTERDOWN;
  15278. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15279. _this.onPrePointerObservable.notifyObservers(pi, type);
  15280. if (pi.skipOnPointerObservable) {
  15281. return;
  15282. }
  15283. }
  15284. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15285. return;
  15286. }
  15287. _this._startingPointerPosition.x = _this._pointerX;
  15288. _this._startingPointerPosition.y = _this._pointerY;
  15289. _this._startingPointerTime = new Date().getTime();
  15290. if (!_this.pointerDownPredicate) {
  15291. _this.pointerDownPredicate = function (mesh) {
  15292. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  15293. };
  15294. }
  15295. // Meshes
  15296. _this._pickedDownMesh = null;
  15297. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15298. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15299. _this._pickedDownMesh = pickResult.pickedMesh;
  15300. var actionManager = pickResult.pickedMesh.actionManager;
  15301. if (actionManager) {
  15302. if (actionManager.hasPickTriggers) {
  15303. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15304. switch (evt.button) {
  15305. case 0:
  15306. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15307. break;
  15308. case 1:
  15309. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15310. break;
  15311. case 2:
  15312. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15313. break;
  15314. }
  15315. }
  15316. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15317. window.setTimeout((function () {
  15318. var _this = this;
  15319. 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);
  15320. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15321. if (this._isButtonPressed &&
  15322. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  15323. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  15324. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  15325. this._startingPointerTime = 0;
  15326. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15327. }
  15328. }
  15329. }).bind(_this), Scene.LongPressDelay);
  15330. }
  15331. }
  15332. }
  15333. if (_this.onPointerDown) {
  15334. _this.onPointerDown(evt, pickResult);
  15335. }
  15336. if (_this.onPointerObservable.hasObservers()) {
  15337. var type = PointerEventTypes.POINTERDOWN;
  15338. var pi = new PointerInfo(type, evt, pickResult);
  15339. _this.onPointerObservable.notifyObservers(pi, type);
  15340. }
  15341. // Sprites
  15342. _this._pickedDownSprite = null;
  15343. if (_this.spriteManagers.length > 0) {
  15344. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15345. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  15346. if (pickResult.pickedSprite.actionManager) {
  15347. _this._pickedDownSprite = pickResult.pickedSprite;
  15348. switch (evt.button) {
  15349. case 0:
  15350. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15351. break;
  15352. case 1:
  15353. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15354. break;
  15355. case 2:
  15356. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15357. break;
  15358. }
  15359. if (pickResult.pickedSprite.actionManager) {
  15360. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15361. }
  15362. }
  15363. }
  15364. }
  15365. };
  15366. this._onPointerUp = function (evt) {
  15367. _this._isButtonPressed = false;
  15368. _this._pickedUpMesh = null;
  15369. _this._meshPickProceed = false;
  15370. _this._updatePointerPosition(evt);
  15371. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  15372. // PreObservable support
  15373. if (this.onPrePointerObservable.hasObservers()) {
  15374. if (!clickInfo.ignore) {
  15375. if (!clickInfo.hasSwiped) {
  15376. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  15377. var type = PointerEventTypes.POINTERTAP;
  15378. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15379. this.onPrePointerObservable.notifyObservers(pi, type);
  15380. if (pi.skipOnPointerObservable) {
  15381. return;
  15382. }
  15383. }
  15384. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  15385. var type = PointerEventTypes.POINTERDOUBLETAP;
  15386. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15387. this.onPrePointerObservable.notifyObservers(pi, type);
  15388. if (pi.skipOnPointerObservable) {
  15389. return;
  15390. }
  15391. }
  15392. }
  15393. }
  15394. else {
  15395. var type = PointerEventTypes.POINTERUP;
  15396. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15397. this.onPrePointerObservable.notifyObservers(pi, type);
  15398. if (pi.skipOnPointerObservable) {
  15399. return;
  15400. }
  15401. }
  15402. }
  15403. if (!this.cameraToUseForPointers && !this.activeCamera) {
  15404. return;
  15405. }
  15406. if (!this.pointerUpPredicate) {
  15407. this.pointerUpPredicate = function (mesh) {
  15408. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  15409. };
  15410. }
  15411. // Meshes
  15412. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  15413. this._initActionManager(null, clickInfo);
  15414. }
  15415. if (!pickResult) {
  15416. pickResult = this._currentPickResult;
  15417. }
  15418. if (pickResult && pickResult && pickResult.pickedMesh) {
  15419. this._pickedUpMesh = pickResult.pickedMesh;
  15420. if (this._pickedDownMesh === this._pickedUpMesh) {
  15421. if (this.onPointerPick) {
  15422. this.onPointerPick(evt, pickResult);
  15423. }
  15424. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  15425. var type = PointerEventTypes.POINTERPICK;
  15426. var pi = new PointerInfo(type, evt, pickResult);
  15427. this.onPointerObservable.notifyObservers(pi, type);
  15428. }
  15429. }
  15430. if (pickResult.pickedMesh.actionManager) {
  15431. if (clickInfo.ignore) {
  15432. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15433. }
  15434. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  15435. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15436. }
  15437. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15438. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15439. }
  15440. }
  15441. }
  15442. if (this._pickedDownMesh &&
  15443. this._pickedDownMesh.actionManager &&
  15444. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  15445. this._pickedDownMesh !== this._pickedUpMesh) {
  15446. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  15447. }
  15448. if (this.onPointerUp) {
  15449. this.onPointerUp(evt, pickResult);
  15450. }
  15451. if (this.onPointerObservable.hasObservers()) {
  15452. if (!clickInfo.ignore) {
  15453. if (!clickInfo.hasSwiped) {
  15454. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  15455. var type = PointerEventTypes.POINTERTAP;
  15456. var pi = new PointerInfo(type, evt, pickResult);
  15457. this.onPointerObservable.notifyObservers(pi, type);
  15458. }
  15459. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  15460. var type = PointerEventTypes.POINTERDOUBLETAP;
  15461. var pi = new PointerInfo(type, evt, pickResult);
  15462. this.onPointerObservable.notifyObservers(pi, type);
  15463. }
  15464. }
  15465. }
  15466. else {
  15467. var type = PointerEventTypes.POINTERUP;
  15468. var pi = new PointerInfo(type, evt, pickResult);
  15469. this.onPointerObservable.notifyObservers(pi, type);
  15470. }
  15471. }
  15472. // Sprites
  15473. if (this.spriteManagers.length > 0) {
  15474. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  15475. if (pickResult.hit && pickResult.pickedSprite) {
  15476. if (pickResult.pickedSprite.actionManager) {
  15477. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  15478. if (pickResult.pickedSprite.actionManager) {
  15479. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  15480. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  15481. }
  15482. }
  15483. }
  15484. }
  15485. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  15486. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  15487. }
  15488. }
  15489. this._previousPickResult = this._currentPickResult;
  15490. }).bind(_this));
  15491. };
  15492. this._onKeyDown = function (evt) {
  15493. if (_this.actionManager) {
  15494. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15495. }
  15496. };
  15497. this._onKeyUp = function (evt) {
  15498. if (_this.actionManager) {
  15499. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15500. }
  15501. };
  15502. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15503. var canvas = this._engine.getRenderingCanvas();
  15504. if (attachMove) {
  15505. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15506. // Wheel
  15507. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  15508. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15509. }
  15510. if (attachDown) {
  15511. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15512. }
  15513. if (attachUp) {
  15514. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15515. }
  15516. canvas.tabIndex = 1;
  15517. canvas.addEventListener("keydown", this._onKeyDown, false);
  15518. canvas.addEventListener("keyup", this._onKeyUp, false);
  15519. };
  15520. Scene.prototype.detachControl = function () {
  15521. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15522. var canvas = this._engine.getRenderingCanvas();
  15523. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  15524. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  15525. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  15526. // Wheel
  15527. canvas.removeEventListener('mousewheel', this._onPointerMove);
  15528. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  15529. canvas.removeEventListener("keydown", this._onKeyDown);
  15530. canvas.removeEventListener("keyup", this._onKeyUp);
  15531. };
  15532. // Ready
  15533. Scene.prototype.isReady = function () {
  15534. if (this._pendingData.length > 0) {
  15535. return false;
  15536. }
  15537. var index;
  15538. // Geometries
  15539. for (index = 0; index < this._geometries.length; index++) {
  15540. var geometry = this._geometries[index];
  15541. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15542. return false;
  15543. }
  15544. }
  15545. // Meshes
  15546. for (index = 0; index < this.meshes.length; index++) {
  15547. var mesh = this.meshes[index];
  15548. if (!mesh.isEnabled()) {
  15549. continue;
  15550. }
  15551. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  15552. continue;
  15553. }
  15554. if (!mesh.isReady()) {
  15555. return false;
  15556. }
  15557. var mat = mesh.material;
  15558. if (mat) {
  15559. if (!mat.isReady(mesh)) {
  15560. return false;
  15561. }
  15562. }
  15563. }
  15564. return true;
  15565. };
  15566. Scene.prototype.resetCachedMaterial = function () {
  15567. this._cachedMaterial = null;
  15568. this._cachedEffect = null;
  15569. };
  15570. Scene.prototype.registerBeforeRender = function (func) {
  15571. this.onBeforeRenderObservable.add(func);
  15572. };
  15573. Scene.prototype.unregisterBeforeRender = function (func) {
  15574. this.onBeforeRenderObservable.removeCallback(func);
  15575. };
  15576. Scene.prototype.registerAfterRender = function (func) {
  15577. this.onAfterRenderObservable.add(func);
  15578. };
  15579. Scene.prototype.unregisterAfterRender = function (func) {
  15580. this.onAfterRenderObservable.removeCallback(func);
  15581. };
  15582. Scene.prototype._addPendingData = function (data) {
  15583. this._pendingData.push(data);
  15584. };
  15585. Scene.prototype._removePendingData = function (data) {
  15586. var index = this._pendingData.indexOf(data);
  15587. if (index !== -1) {
  15588. this._pendingData.splice(index, 1);
  15589. }
  15590. };
  15591. Scene.prototype.getWaitingItemsCount = function () {
  15592. return this._pendingData.length;
  15593. };
  15594. /**
  15595. * Registers a function to be executed when the scene is ready.
  15596. * @param {Function} func - the function to be executed.
  15597. */
  15598. Scene.prototype.executeWhenReady = function (func) {
  15599. var _this = this;
  15600. this.onReadyObservable.add(func);
  15601. if (this._executeWhenReadyTimeoutId !== -1) {
  15602. return;
  15603. }
  15604. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15605. _this._checkIsReady();
  15606. }, 150);
  15607. };
  15608. Scene.prototype._checkIsReady = function () {
  15609. var _this = this;
  15610. if (this.isReady()) {
  15611. this.onReadyObservable.notifyObservers(this);
  15612. this.onReadyObservable.clear();
  15613. this._executeWhenReadyTimeoutId = -1;
  15614. return;
  15615. }
  15616. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15617. _this._checkIsReady();
  15618. }, 150);
  15619. };
  15620. // Animations
  15621. /**
  15622. * Will start the animation sequence of a given target
  15623. * @param target - the target
  15624. * @param {number} from - from which frame should animation start
  15625. * @param {number} to - till which frame should animation run.
  15626. * @param {boolean} [loop] - should the animation loop
  15627. * @param {number} [speedRatio] - the speed in which to run the animation
  15628. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15629. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15630. * @return {BABYLON.Animatable} the animatable object created for this animation
  15631. * @see BABYLON.Animatable
  15632. * @see http://doc.babylonjs.com/page.php?p=22081
  15633. */
  15634. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15635. if (speedRatio === void 0) { speedRatio = 1.0; }
  15636. this.stopAnimation(target);
  15637. if (!animatable) {
  15638. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15639. }
  15640. // Local animations
  15641. if (target.animations) {
  15642. animatable.appendAnimations(target, target.animations);
  15643. }
  15644. // Children animations
  15645. if (target.getAnimatables) {
  15646. var animatables = target.getAnimatables();
  15647. for (var index = 0; index < animatables.length; index++) {
  15648. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15649. }
  15650. }
  15651. animatable.reset();
  15652. return animatable;
  15653. };
  15654. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15655. if (speedRatio === undefined) {
  15656. speedRatio = 1.0;
  15657. }
  15658. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15659. return animatable;
  15660. };
  15661. Scene.prototype.getAnimatableByTarget = function (target) {
  15662. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15663. if (this._activeAnimatables[index].target === target) {
  15664. return this._activeAnimatables[index];
  15665. }
  15666. }
  15667. return null;
  15668. };
  15669. Object.defineProperty(Scene.prototype, "Animatables", {
  15670. get: function () {
  15671. return this._activeAnimatables;
  15672. },
  15673. enumerable: true,
  15674. configurable: true
  15675. });
  15676. /**
  15677. * Will stop the animation of the given target
  15678. * @param target - the target
  15679. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  15680. * @see beginAnimation
  15681. */
  15682. Scene.prototype.stopAnimation = function (target, animationName) {
  15683. var animatable = this.getAnimatableByTarget(target);
  15684. if (animatable) {
  15685. animatable.stop(animationName);
  15686. }
  15687. };
  15688. Scene.prototype._animate = function () {
  15689. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15690. return;
  15691. }
  15692. // Getting time
  15693. var now = BABYLON.Tools.Now;
  15694. if (!this._animationTimeLast) {
  15695. if (this._pendingData.length > 0) {
  15696. return;
  15697. }
  15698. this._animationTimeLast = now;
  15699. }
  15700. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  15701. this._animationTime += deltaTime;
  15702. this._animationTimeLast = now;
  15703. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15704. this._activeAnimatables[index]._animate(this._animationTime);
  15705. }
  15706. };
  15707. // Matrix
  15708. Scene.prototype.getViewMatrix = function () {
  15709. return this._viewMatrix;
  15710. };
  15711. Scene.prototype.getProjectionMatrix = function () {
  15712. return this._projectionMatrix;
  15713. };
  15714. Scene.prototype.getTransformMatrix = function () {
  15715. return this._transformMatrix;
  15716. };
  15717. Scene.prototype.setTransformMatrix = function (view, projection) {
  15718. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  15719. return;
  15720. }
  15721. this._viewUpdateFlag = view.updateFlag;
  15722. this._projectionUpdateFlag = projection.updateFlag;
  15723. this._viewMatrix = view;
  15724. this._projectionMatrix = projection;
  15725. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15726. // Update frustum
  15727. if (!this._frustumPlanes) {
  15728. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15729. }
  15730. else {
  15731. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15732. }
  15733. };
  15734. // Methods
  15735. Scene.prototype.getUniqueId = function () {
  15736. var result = this._uniqueIdCounter;
  15737. this._uniqueIdCounter++;
  15738. return result;
  15739. };
  15740. Scene.prototype.addMesh = function (newMesh) {
  15741. newMesh.uniqueId = this.getUniqueId();
  15742. var position = this.meshes.push(newMesh);
  15743. //notify the collision coordinator
  15744. if (this.collisionCoordinator) {
  15745. this.collisionCoordinator.onMeshAdded(newMesh);
  15746. }
  15747. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15748. };
  15749. Scene.prototype.removeMesh = function (toRemove) {
  15750. var index = this.meshes.indexOf(toRemove);
  15751. if (index !== -1) {
  15752. // Remove from the scene if mesh found
  15753. this.meshes.splice(index, 1);
  15754. }
  15755. //notify the collision coordinator
  15756. if (this.collisionCoordinator) {
  15757. this.collisionCoordinator.onMeshRemoved(toRemove);
  15758. }
  15759. this.onMeshRemovedObservable.notifyObservers(toRemove);
  15760. return index;
  15761. };
  15762. Scene.prototype.removeSkeleton = function (toRemove) {
  15763. var index = this.skeletons.indexOf(toRemove);
  15764. if (index !== -1) {
  15765. // Remove from the scene if found
  15766. this.skeletons.splice(index, 1);
  15767. }
  15768. return index;
  15769. };
  15770. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  15771. var index = this.morphTargetManagers.indexOf(toRemove);
  15772. if (index !== -1) {
  15773. // Remove from the scene if found
  15774. this.morphTargetManagers.splice(index, 1);
  15775. }
  15776. return index;
  15777. };
  15778. Scene.prototype.removeLight = function (toRemove) {
  15779. var index = this.lights.indexOf(toRemove);
  15780. if (index !== -1) {
  15781. // Remove from the scene if mesh found
  15782. this.lights.splice(index, 1);
  15783. }
  15784. this.onLightRemovedObservable.notifyObservers(toRemove);
  15785. return index;
  15786. };
  15787. Scene.prototype.removeCamera = function (toRemove) {
  15788. var index = this.cameras.indexOf(toRemove);
  15789. if (index !== -1) {
  15790. // Remove from the scene if mesh found
  15791. this.cameras.splice(index, 1);
  15792. }
  15793. // Remove from activeCameras
  15794. var index2 = this.activeCameras.indexOf(toRemove);
  15795. if (index2 !== -1) {
  15796. // Remove from the scene if mesh found
  15797. this.activeCameras.splice(index2, 1);
  15798. }
  15799. // Reset the activeCamera
  15800. if (this.activeCamera === toRemove) {
  15801. if (this.cameras.length > 0) {
  15802. this.activeCamera = this.cameras[0];
  15803. }
  15804. else {
  15805. this.activeCamera = null;
  15806. }
  15807. }
  15808. this.onCameraRemovedObservable.notifyObservers(toRemove);
  15809. return index;
  15810. };
  15811. Scene.prototype.addLight = function (newLight) {
  15812. newLight.uniqueId = this.getUniqueId();
  15813. var position = this.lights.push(newLight);
  15814. this.onNewLightAddedObservable.notifyObservers(newLight);
  15815. };
  15816. Scene.prototype.addCamera = function (newCamera) {
  15817. newCamera.uniqueId = this.getUniqueId();
  15818. var position = this.cameras.push(newCamera);
  15819. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15820. };
  15821. /**
  15822. * Switch active camera
  15823. * @param {Camera} newCamera - new active camera
  15824. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15825. */
  15826. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  15827. if (attachControl === void 0) { attachControl = true; }
  15828. var canvas = this._engine.getRenderingCanvas();
  15829. this.activeCamera.detachControl(canvas);
  15830. this.activeCamera = newCamera;
  15831. if (attachControl) {
  15832. newCamera.attachControl(canvas);
  15833. }
  15834. };
  15835. /**
  15836. * sets the active camera of the scene using its ID
  15837. * @param {string} id - the camera's ID
  15838. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15839. * @see activeCamera
  15840. */
  15841. Scene.prototype.setActiveCameraByID = function (id) {
  15842. var camera = this.getCameraByID(id);
  15843. if (camera) {
  15844. this.activeCamera = camera;
  15845. return camera;
  15846. }
  15847. return null;
  15848. };
  15849. /**
  15850. * sets the active camera of the scene using its name
  15851. * @param {string} name - the camera's name
  15852. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15853. * @see activeCamera
  15854. */
  15855. Scene.prototype.setActiveCameraByName = function (name) {
  15856. var camera = this.getCameraByName(name);
  15857. if (camera) {
  15858. this.activeCamera = camera;
  15859. return camera;
  15860. }
  15861. return null;
  15862. };
  15863. /**
  15864. * get a material using its id
  15865. * @param {string} the material's ID
  15866. * @return {BABYLON.Material|null} the material or null if none found.
  15867. */
  15868. Scene.prototype.getMaterialByID = function (id) {
  15869. for (var index = 0; index < this.materials.length; index++) {
  15870. if (this.materials[index].id === id) {
  15871. return this.materials[index];
  15872. }
  15873. }
  15874. return null;
  15875. };
  15876. /**
  15877. * get a material using its name
  15878. * @param {string} the material's name
  15879. * @return {BABYLON.Material|null} the material or null if none found.
  15880. */
  15881. Scene.prototype.getMaterialByName = function (name) {
  15882. for (var index = 0; index < this.materials.length; index++) {
  15883. if (this.materials[index].name === name) {
  15884. return this.materials[index];
  15885. }
  15886. }
  15887. return null;
  15888. };
  15889. Scene.prototype.getLensFlareSystemByName = function (name) {
  15890. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15891. if (this.lensFlareSystems[index].name === name) {
  15892. return this.lensFlareSystems[index];
  15893. }
  15894. }
  15895. return null;
  15896. };
  15897. Scene.prototype.getLensFlareSystemByID = function (id) {
  15898. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15899. if (this.lensFlareSystems[index].id === id) {
  15900. return this.lensFlareSystems[index];
  15901. }
  15902. }
  15903. return null;
  15904. };
  15905. Scene.prototype.getCameraByID = function (id) {
  15906. for (var index = 0; index < this.cameras.length; index++) {
  15907. if (this.cameras[index].id === id) {
  15908. return this.cameras[index];
  15909. }
  15910. }
  15911. return null;
  15912. };
  15913. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  15914. for (var index = 0; index < this.cameras.length; index++) {
  15915. if (this.cameras[index].uniqueId === uniqueId) {
  15916. return this.cameras[index];
  15917. }
  15918. }
  15919. return null;
  15920. };
  15921. /**
  15922. * get a camera using its name
  15923. * @param {string} the camera's name
  15924. * @return {BABYLON.Camera|null} the camera or null if none found.
  15925. */
  15926. Scene.prototype.getCameraByName = function (name) {
  15927. for (var index = 0; index < this.cameras.length; index++) {
  15928. if (this.cameras[index].name === name) {
  15929. return this.cameras[index];
  15930. }
  15931. }
  15932. return null;
  15933. };
  15934. /**
  15935. * get a bone using its id
  15936. * @param {string} the bone's id
  15937. * @return {BABYLON.Bone|null} the bone or null if not found
  15938. */
  15939. Scene.prototype.getBoneByID = function (id) {
  15940. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15941. var skeleton = this.skeletons[skeletonIndex];
  15942. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15943. if (skeleton.bones[boneIndex].id === id) {
  15944. return skeleton.bones[boneIndex];
  15945. }
  15946. }
  15947. }
  15948. return null;
  15949. };
  15950. /**
  15951. * get a bone using its id
  15952. * @param {string} the bone's name
  15953. * @return {BABYLON.Bone|null} the bone or null if not found
  15954. */
  15955. Scene.prototype.getBoneByName = function (name) {
  15956. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15957. var skeleton = this.skeletons[skeletonIndex];
  15958. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15959. if (skeleton.bones[boneIndex].name === name) {
  15960. return skeleton.bones[boneIndex];
  15961. }
  15962. }
  15963. }
  15964. return null;
  15965. };
  15966. /**
  15967. * get a light node using its name
  15968. * @param {string} the light's name
  15969. * @return {BABYLON.Light|null} the light or null if none found.
  15970. */
  15971. Scene.prototype.getLightByName = function (name) {
  15972. for (var index = 0; index < this.lights.length; index++) {
  15973. if (this.lights[index].name === name) {
  15974. return this.lights[index];
  15975. }
  15976. }
  15977. return null;
  15978. };
  15979. /**
  15980. * get a light node using its ID
  15981. * @param {string} the light's id
  15982. * @return {BABYLON.Light|null} the light or null if none found.
  15983. */
  15984. Scene.prototype.getLightByID = function (id) {
  15985. for (var index = 0; index < this.lights.length; index++) {
  15986. if (this.lights[index].id === id) {
  15987. return this.lights[index];
  15988. }
  15989. }
  15990. return null;
  15991. };
  15992. /**
  15993. * get a light node using its scene-generated unique ID
  15994. * @param {number} the light's unique id
  15995. * @return {BABYLON.Light|null} the light or null if none found.
  15996. */
  15997. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  15998. for (var index = 0; index < this.lights.length; index++) {
  15999. if (this.lights[index].uniqueId === uniqueId) {
  16000. return this.lights[index];
  16001. }
  16002. }
  16003. return null;
  16004. };
  16005. /**
  16006. * get a particle system by id
  16007. * @param id {number} the particle system id
  16008. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16009. */
  16010. Scene.prototype.getParticleSystemByID = function (id) {
  16011. for (var index = 0; index < this.particleSystems.length; index++) {
  16012. if (this.particleSystems[index].id === id) {
  16013. return this.particleSystems[index];
  16014. }
  16015. }
  16016. return null;
  16017. };
  16018. /**
  16019. * get a geometry using its ID
  16020. * @param {string} the geometry's id
  16021. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16022. */
  16023. Scene.prototype.getGeometryByID = function (id) {
  16024. for (var index = 0; index < this._geometries.length; index++) {
  16025. if (this._geometries[index].id === id) {
  16026. return this._geometries[index];
  16027. }
  16028. }
  16029. return null;
  16030. };
  16031. /**
  16032. * add a new geometry to this scene.
  16033. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16034. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16035. * @return {boolean} was the geometry added or not
  16036. */
  16037. Scene.prototype.pushGeometry = function (geometry, force) {
  16038. if (!force && this.getGeometryByID(geometry.id)) {
  16039. return false;
  16040. }
  16041. this._geometries.push(geometry);
  16042. //notify the collision coordinator
  16043. if (this.collisionCoordinator) {
  16044. this.collisionCoordinator.onGeometryAdded(geometry);
  16045. }
  16046. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16047. return true;
  16048. };
  16049. /**
  16050. * Removes an existing geometry
  16051. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16052. * @return {boolean} was the geometry removed or not
  16053. */
  16054. Scene.prototype.removeGeometry = function (geometry) {
  16055. var index = this._geometries.indexOf(geometry);
  16056. if (index > -1) {
  16057. this._geometries.splice(index, 1);
  16058. //notify the collision coordinator
  16059. if (this.collisionCoordinator) {
  16060. this.collisionCoordinator.onGeometryDeleted(geometry);
  16061. }
  16062. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16063. return true;
  16064. }
  16065. return false;
  16066. };
  16067. Scene.prototype.getGeometries = function () {
  16068. return this._geometries;
  16069. };
  16070. /**
  16071. * Get the first added mesh found of a given ID
  16072. * @param {string} id - the id to search for
  16073. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16074. */
  16075. Scene.prototype.getMeshByID = function (id) {
  16076. for (var index = 0; index < this.meshes.length; index++) {
  16077. if (this.meshes[index].id === id) {
  16078. return this.meshes[index];
  16079. }
  16080. }
  16081. return null;
  16082. };
  16083. Scene.prototype.getMeshesByID = function (id) {
  16084. return this.meshes.filter(function (m) {
  16085. return m.id === id;
  16086. });
  16087. };
  16088. /**
  16089. * Get a mesh with its auto-generated unique id
  16090. * @param {number} uniqueId - the unique id to search for
  16091. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16092. */
  16093. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16094. for (var index = 0; index < this.meshes.length; index++) {
  16095. if (this.meshes[index].uniqueId === uniqueId) {
  16096. return this.meshes[index];
  16097. }
  16098. }
  16099. return null;
  16100. };
  16101. /**
  16102. * Get a the last added mesh found of a given ID
  16103. * @param {string} id - the id to search for
  16104. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16105. */
  16106. Scene.prototype.getLastMeshByID = function (id) {
  16107. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16108. if (this.meshes[index].id === id) {
  16109. return this.meshes[index];
  16110. }
  16111. }
  16112. return null;
  16113. };
  16114. /**
  16115. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16116. * @param {string} id - the id to search for
  16117. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16118. */
  16119. Scene.prototype.getLastEntryByID = function (id) {
  16120. var index;
  16121. for (index = this.meshes.length - 1; index >= 0; index--) {
  16122. if (this.meshes[index].id === id) {
  16123. return this.meshes[index];
  16124. }
  16125. }
  16126. for (index = this.cameras.length - 1; index >= 0; index--) {
  16127. if (this.cameras[index].id === id) {
  16128. return this.cameras[index];
  16129. }
  16130. }
  16131. for (index = this.lights.length - 1; index >= 0; index--) {
  16132. if (this.lights[index].id === id) {
  16133. return this.lights[index];
  16134. }
  16135. }
  16136. return null;
  16137. };
  16138. Scene.prototype.getNodeByID = function (id) {
  16139. var mesh = this.getMeshByID(id);
  16140. if (mesh) {
  16141. return mesh;
  16142. }
  16143. var light = this.getLightByID(id);
  16144. if (light) {
  16145. return light;
  16146. }
  16147. var camera = this.getCameraByID(id);
  16148. if (camera) {
  16149. return camera;
  16150. }
  16151. var bone = this.getBoneByID(id);
  16152. return bone;
  16153. };
  16154. Scene.prototype.getNodeByName = function (name) {
  16155. var mesh = this.getMeshByName(name);
  16156. if (mesh) {
  16157. return mesh;
  16158. }
  16159. var light = this.getLightByName(name);
  16160. if (light) {
  16161. return light;
  16162. }
  16163. var camera = this.getCameraByName(name);
  16164. if (camera) {
  16165. return camera;
  16166. }
  16167. var bone = this.getBoneByName(name);
  16168. return bone;
  16169. };
  16170. Scene.prototype.getMeshByName = function (name) {
  16171. for (var index = 0; index < this.meshes.length; index++) {
  16172. if (this.meshes[index].name === name) {
  16173. return this.meshes[index];
  16174. }
  16175. }
  16176. return null;
  16177. };
  16178. Scene.prototype.getSoundByName = function (name) {
  16179. var index;
  16180. if (BABYLON.AudioEngine) {
  16181. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  16182. if (this.mainSoundTrack.soundCollection[index].name === name) {
  16183. return this.mainSoundTrack.soundCollection[index];
  16184. }
  16185. }
  16186. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  16187. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  16188. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  16189. return this.soundTracks[sdIndex].soundCollection[index];
  16190. }
  16191. }
  16192. }
  16193. }
  16194. return null;
  16195. };
  16196. Scene.prototype.getLastSkeletonByID = function (id) {
  16197. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  16198. if (this.skeletons[index].id === id) {
  16199. return this.skeletons[index];
  16200. }
  16201. }
  16202. return null;
  16203. };
  16204. Scene.prototype.getSkeletonById = function (id) {
  16205. for (var index = 0; index < this.skeletons.length; index++) {
  16206. if (this.skeletons[index].id === id) {
  16207. return this.skeletons[index];
  16208. }
  16209. }
  16210. return null;
  16211. };
  16212. Scene.prototype.getSkeletonByName = function (name) {
  16213. for (var index = 0; index < this.skeletons.length; index++) {
  16214. if (this.skeletons[index].name === name) {
  16215. return this.skeletons[index];
  16216. }
  16217. }
  16218. return null;
  16219. };
  16220. Scene.prototype.getMorphTargetManagerById = function (id) {
  16221. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  16222. if (this.morphTargetManagers[index].uniqueId === id) {
  16223. return this.morphTargetManagers[index];
  16224. }
  16225. }
  16226. return null;
  16227. };
  16228. Scene.prototype.isActiveMesh = function (mesh) {
  16229. return (this._activeMeshes.indexOf(mesh) !== -1);
  16230. };
  16231. /**
  16232. * Return a the first highlight layer of the scene with a given name.
  16233. * @param name The name of the highlight layer to look for.
  16234. * @return The highlight layer if found otherwise null.
  16235. */
  16236. Scene.prototype.getHighlightLayerByName = function (name) {
  16237. for (var index = 0; index < this.highlightLayers.length; index++) {
  16238. if (this.highlightLayers[index].name === name) {
  16239. return this.highlightLayers[index];
  16240. }
  16241. }
  16242. return null;
  16243. };
  16244. Object.defineProperty(Scene.prototype, "uid", {
  16245. /**
  16246. * Return a unique id as a string which can serve as an identifier for the scene
  16247. */
  16248. get: function () {
  16249. if (!this._uid) {
  16250. this._uid = BABYLON.Tools.RandomId();
  16251. }
  16252. return this._uid;
  16253. },
  16254. enumerable: true,
  16255. configurable: true
  16256. });
  16257. /**
  16258. * Add an externaly attached data from its key.
  16259. * This method call will fail and return false, if such key already exists.
  16260. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16261. * @param key the unique key that identifies the data
  16262. * @param data the data object to associate to the key for this Engine instance
  16263. * @return true if no such key were already present and the data was added successfully, false otherwise
  16264. */
  16265. Scene.prototype.addExternalData = function (key, data) {
  16266. if (!this._externalData) {
  16267. this._externalData = new BABYLON.StringDictionary();
  16268. }
  16269. return this._externalData.add(key, data);
  16270. };
  16271. /**
  16272. * Get an externaly attached data from its key
  16273. * @param key the unique key that identifies the data
  16274. * @return the associated data, if present (can be null), or undefined if not present
  16275. */
  16276. Scene.prototype.getExternalData = function (key) {
  16277. if (!this._externalData) {
  16278. return null;
  16279. }
  16280. return this._externalData.get(key);
  16281. };
  16282. /**
  16283. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16284. * @param key the unique key that identifies the data
  16285. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16286. * @return the associated data, can be null if the factory returned null.
  16287. */
  16288. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16289. if (!this._externalData) {
  16290. this._externalData = new BABYLON.StringDictionary();
  16291. }
  16292. return this._externalData.getOrAddWithFactory(key, factory);
  16293. };
  16294. /**
  16295. * Remove an externaly attached data from the Engine instance
  16296. * @param key the unique key that identifies the data
  16297. * @return true if the data was successfully removed, false if it doesn't exist
  16298. */
  16299. Scene.prototype.removeExternalData = function (key) {
  16300. return this._externalData.remove(key);
  16301. };
  16302. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  16303. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  16304. var material = subMesh.getMaterial();
  16305. if (mesh.showSubMeshesBoundingBox) {
  16306. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  16307. }
  16308. if (material) {
  16309. // Render targets
  16310. if (material.getRenderTargetTextures) {
  16311. if (this._processedMaterials.indexOf(material) === -1) {
  16312. this._processedMaterials.push(material);
  16313. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  16314. }
  16315. }
  16316. // Dispatch
  16317. this._activeIndices.addCount(subMesh.indexCount, false);
  16318. this._renderingManager.dispatch(subMesh);
  16319. }
  16320. }
  16321. };
  16322. Scene.prototype._isInIntermediateRendering = function () {
  16323. return this._intermediateRendering;
  16324. };
  16325. Scene.prototype._evaluateActiveMeshes = function () {
  16326. this.activeCamera._activeMeshes.reset();
  16327. this._activeMeshes.reset();
  16328. this._renderingManager.reset();
  16329. this._processedMaterials.reset();
  16330. this._activeParticleSystems.reset();
  16331. this._activeSkeletons.reset();
  16332. this._softwareSkinnedMeshes.reset();
  16333. if (this._boundingBoxRenderer) {
  16334. this._boundingBoxRenderer.reset();
  16335. }
  16336. this._edgesRenderers.reset();
  16337. // Meshes
  16338. var meshes;
  16339. var len;
  16340. if (this._selectionOctree) {
  16341. var selection = this._selectionOctree.select(this._frustumPlanes);
  16342. meshes = selection.data;
  16343. len = selection.length;
  16344. }
  16345. else {
  16346. len = this.meshes.length;
  16347. meshes = this.meshes;
  16348. }
  16349. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16350. var mesh = meshes[meshIndex];
  16351. if (mesh.isBlocked) {
  16352. continue;
  16353. }
  16354. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  16355. if (!mesh.isReady() || !mesh.isEnabled()) {
  16356. continue;
  16357. }
  16358. mesh.computeWorldMatrix();
  16359. // Intersections
  16360. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  16361. this._meshesForIntersections.pushNoDuplicate(mesh);
  16362. }
  16363. // Switch to current LOD
  16364. var meshLOD = mesh.getLOD(this.activeCamera);
  16365. if (!meshLOD) {
  16366. continue;
  16367. }
  16368. mesh._preActivate();
  16369. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  16370. this._activeMeshes.push(mesh);
  16371. this.activeCamera._activeMeshes.push(mesh);
  16372. mesh._activate(this._renderId);
  16373. this._activeMesh(mesh, meshLOD);
  16374. }
  16375. }
  16376. // Particle systems
  16377. this._particlesDuration.beginMonitoring();
  16378. var beforeParticlesDate = BABYLON.Tools.Now;
  16379. if (this.particlesEnabled) {
  16380. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  16381. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  16382. var particleSystem = this.particleSystems[particleIndex];
  16383. if (!particleSystem.isStarted()) {
  16384. continue;
  16385. }
  16386. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  16387. this._activeParticleSystems.push(particleSystem);
  16388. particleSystem.animate();
  16389. this._renderingManager.dispatchParticles(particleSystem);
  16390. }
  16391. }
  16392. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  16393. }
  16394. this._particlesDuration.endMonitoring(false);
  16395. };
  16396. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  16397. if (mesh.skeleton && this.skeletonsEnabled) {
  16398. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  16399. mesh.skeleton.prepare();
  16400. }
  16401. if (!mesh.computeBonesUsingShaders) {
  16402. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  16403. }
  16404. }
  16405. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  16406. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  16407. }
  16408. if (sourceMesh._edgesRenderer) {
  16409. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  16410. }
  16411. if (mesh && mesh.subMeshes) {
  16412. // Submeshes Octrees
  16413. var len;
  16414. var subMeshes;
  16415. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  16416. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  16417. len = intersections.length;
  16418. subMeshes = intersections.data;
  16419. }
  16420. else {
  16421. subMeshes = mesh.subMeshes;
  16422. len = subMeshes.length;
  16423. }
  16424. for (var subIndex = 0; subIndex < len; subIndex++) {
  16425. var subMesh = subMeshes[subIndex];
  16426. this._evaluateSubMesh(subMesh, mesh);
  16427. }
  16428. }
  16429. };
  16430. Scene.prototype.updateTransformMatrix = function (force) {
  16431. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  16432. };
  16433. Scene.prototype._renderForCamera = function (camera) {
  16434. var engine = this._engine;
  16435. var startTime = BABYLON.Tools.Now;
  16436. this.activeCamera = camera;
  16437. if (!this.activeCamera)
  16438. throw new Error("Active camera not set");
  16439. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16440. // Viewport
  16441. engine.setViewport(this.activeCamera.viewport);
  16442. // Camera
  16443. this.resetCachedMaterial();
  16444. this._renderId++;
  16445. this.updateTransformMatrix();
  16446. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  16447. // Meshes
  16448. this._evaluateActiveMeshesDuration.beginMonitoring();
  16449. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  16450. this._evaluateActiveMeshes();
  16451. this._evaluateActiveMeshesDuration.endMonitoring(false);
  16452. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  16453. // Software skinning
  16454. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  16455. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  16456. mesh.applySkeleton(mesh.skeleton);
  16457. }
  16458. // Render targets
  16459. this._renderTargetsDuration.beginMonitoring();
  16460. var needsRestoreFrameBuffer = false;
  16461. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16462. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  16463. this._intermediateRendering = true;
  16464. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16465. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  16466. var renderTarget = this._renderTargets.data[renderIndex];
  16467. if (renderTarget._shouldRender()) {
  16468. this._renderId++;
  16469. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  16470. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  16471. }
  16472. }
  16473. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16474. this._intermediateRendering = false;
  16475. this._renderId++;
  16476. needsRestoreFrameBuffer = true; // Restore back buffer
  16477. }
  16478. // Render HighlightLayer Texture
  16479. var stencilState = this._engine.getStencilBuffer();
  16480. var renderhighlights = false;
  16481. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  16482. this._intermediateRendering = true;
  16483. for (var i = 0; i < this.highlightLayers.length; i++) {
  16484. var highlightLayer = this.highlightLayers[i];
  16485. if (highlightLayer.shouldRender() &&
  16486. (!highlightLayer.camera ||
  16487. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  16488. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  16489. renderhighlights = true;
  16490. var renderTarget = highlightLayer._mainTexture;
  16491. if (renderTarget._shouldRender()) {
  16492. this._renderId++;
  16493. renderTarget.render(false, false);
  16494. needsRestoreFrameBuffer = true;
  16495. }
  16496. }
  16497. }
  16498. this._intermediateRendering = false;
  16499. this._renderId++;
  16500. }
  16501. if (needsRestoreFrameBuffer) {
  16502. engine.restoreDefaultFramebuffer();
  16503. }
  16504. this._renderTargetsDuration.endMonitoring(false);
  16505. // Prepare Frame
  16506. this.postProcessManager._prepareFrame();
  16507. this._renderDuration.beginMonitoring();
  16508. // Backgrounds
  16509. var layerIndex;
  16510. var layer;
  16511. if (this.layers.length) {
  16512. engine.setDepthBuffer(false);
  16513. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16514. layer = this.layers[layerIndex];
  16515. if (layer.isBackground) {
  16516. layer.render();
  16517. }
  16518. }
  16519. engine.setDepthBuffer(true);
  16520. }
  16521. // Render
  16522. BABYLON.Tools.StartPerformanceCounter("Main render");
  16523. // Activate HighlightLayer stencil
  16524. if (renderhighlights) {
  16525. this._engine.setStencilBuffer(true);
  16526. }
  16527. this._renderingManager.render(null, null, true, true);
  16528. // Restore HighlightLayer stencil
  16529. if (renderhighlights) {
  16530. this._engine.setStencilBuffer(stencilState);
  16531. }
  16532. BABYLON.Tools.EndPerformanceCounter("Main render");
  16533. // Bounding boxes
  16534. if (this._boundingBoxRenderer) {
  16535. this._boundingBoxRenderer.render();
  16536. }
  16537. // Edges
  16538. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16539. this._edgesRenderers.data[edgesRendererIndex].render();
  16540. }
  16541. // Lens flares
  16542. if (this.lensFlaresEnabled) {
  16543. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16544. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  16545. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  16546. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  16547. lensFlareSystem.render();
  16548. }
  16549. }
  16550. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16551. }
  16552. // Foregrounds
  16553. if (this.layers.length) {
  16554. engine.setDepthBuffer(false);
  16555. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16556. layer = this.layers[layerIndex];
  16557. if (!layer.isBackground) {
  16558. layer.render();
  16559. }
  16560. }
  16561. engine.setDepthBuffer(true);
  16562. }
  16563. // Highlight Layer
  16564. if (renderhighlights) {
  16565. engine.setDepthBuffer(false);
  16566. for (var i = 0; i < this.highlightLayers.length; i++) {
  16567. if (this.highlightLayers[i].shouldRender()) {
  16568. this.highlightLayers[i].render();
  16569. }
  16570. }
  16571. engine.setDepthBuffer(true);
  16572. }
  16573. this._renderDuration.endMonitoring(false);
  16574. // Finalize frame
  16575. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16576. // Update camera
  16577. this.activeCamera._updateFromScene();
  16578. // Reset some special arrays
  16579. this._renderTargets.reset();
  16580. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16581. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16582. };
  16583. Scene.prototype._processSubCameras = function (camera) {
  16584. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16585. this._renderForCamera(camera);
  16586. return;
  16587. }
  16588. // rig cameras
  16589. for (var index = 0; index < camera._rigCameras.length; index++) {
  16590. this._renderForCamera(camera._rigCameras[index]);
  16591. }
  16592. this.activeCamera = camera;
  16593. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16594. // Update camera
  16595. this.activeCamera._updateFromScene();
  16596. };
  16597. Scene.prototype._checkIntersections = function () {
  16598. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16599. var sourceMesh = this._meshesForIntersections.data[index];
  16600. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16601. var action = sourceMesh.actionManager.actions[actionIndex];
  16602. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16603. var parameters = action.getTriggerParameter();
  16604. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16605. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16606. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16607. if (areIntersecting && currentIntersectionInProgress === -1) {
  16608. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16609. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16610. sourceMesh._intersectionsInProgress.push(otherMesh);
  16611. }
  16612. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16613. sourceMesh._intersectionsInProgress.push(otherMesh);
  16614. }
  16615. }
  16616. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16617. //They intersected, and now they don't.
  16618. //is this trigger an exit trigger? execute an event.
  16619. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16620. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16621. }
  16622. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16623. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16624. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16625. }
  16626. }
  16627. }
  16628. }
  16629. }
  16630. };
  16631. Scene.prototype.render = function () {
  16632. if (this.isDisposed) {
  16633. return;
  16634. }
  16635. this._lastFrameDuration.beginMonitoring();
  16636. this._particlesDuration.fetchNewFrame();
  16637. this._spritesDuration.fetchNewFrame();
  16638. this._activeParticles.fetchNewFrame();
  16639. this._renderDuration.fetchNewFrame();
  16640. this._renderTargetsDuration.fetchNewFrame();
  16641. this._evaluateActiveMeshesDuration.fetchNewFrame();
  16642. this._totalVertices.fetchNewFrame();
  16643. this._activeIndices.fetchNewFrame();
  16644. this._activeBones.fetchNewFrame();
  16645. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  16646. this._meshesForIntersections.reset();
  16647. this.resetCachedMaterial();
  16648. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16649. // Actions
  16650. if (this.actionManager) {
  16651. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16652. }
  16653. //Simplification Queue
  16654. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16655. this.simplificationQueue.executeNext();
  16656. }
  16657. // Animations
  16658. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16659. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16660. this._animate();
  16661. // Physics
  16662. if (this._physicsEngine) {
  16663. BABYLON.Tools.StartPerformanceCounter("Physics");
  16664. this._physicsEngine._step(deltaTime / 1000.0);
  16665. BABYLON.Tools.EndPerformanceCounter("Physics");
  16666. }
  16667. // Before render
  16668. this.onBeforeRenderObservable.notifyObservers(this);
  16669. // Customs render targets
  16670. this._renderTargetsDuration.beginMonitoring();
  16671. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16672. var engine = this.getEngine();
  16673. var currentActiveCamera = this.activeCamera;
  16674. if (this.renderTargetsEnabled) {
  16675. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16676. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16677. var renderTarget = this.customRenderTargets[customIndex];
  16678. if (renderTarget._shouldRender()) {
  16679. this._renderId++;
  16680. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16681. if (!this.activeCamera)
  16682. throw new Error("Active camera not set");
  16683. // Viewport
  16684. engine.setViewport(this.activeCamera.viewport);
  16685. // Camera
  16686. this.updateTransformMatrix();
  16687. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16688. }
  16689. }
  16690. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16691. this._renderId++;
  16692. }
  16693. if (this.customRenderTargets.length > 0) {
  16694. engine.restoreDefaultFramebuffer();
  16695. }
  16696. this._renderTargetsDuration.endMonitoring();
  16697. this.activeCamera = currentActiveCamera;
  16698. // Procedural textures
  16699. if (this.proceduralTexturesEnabled) {
  16700. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16701. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16702. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16703. if (proceduralTexture._shouldRender()) {
  16704. proceduralTexture.render();
  16705. }
  16706. }
  16707. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16708. }
  16709. // Clear
  16710. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  16711. // Shadows
  16712. if (this.shadowsEnabled) {
  16713. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16714. var light = this.lights[lightIndex];
  16715. var shadowGenerator = light.getShadowGenerator();
  16716. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16717. this._renderTargets.push(shadowGenerator.getShadowMap());
  16718. }
  16719. }
  16720. }
  16721. // Depth renderer
  16722. if (this._depthRenderer) {
  16723. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16724. }
  16725. // RenderPipeline
  16726. if (this._postProcessRenderPipelineManager) {
  16727. this._postProcessRenderPipelineManager.update();
  16728. }
  16729. // Multi-cameras?
  16730. if (this.activeCameras.length > 0) {
  16731. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16732. if (cameraIndex > 0) {
  16733. this._engine.clear(null, false, true, true);
  16734. }
  16735. this._processSubCameras(this.activeCameras[cameraIndex]);
  16736. }
  16737. }
  16738. else {
  16739. if (!this.activeCamera) {
  16740. throw new Error("No camera defined");
  16741. }
  16742. this._processSubCameras(this.activeCamera);
  16743. }
  16744. // Intersection checks
  16745. this._checkIntersections();
  16746. // Update the audio listener attached to the camera
  16747. if (BABYLON.AudioEngine) {
  16748. this._updateAudioParameters();
  16749. }
  16750. // After render
  16751. if (this.afterRender) {
  16752. this.afterRender();
  16753. }
  16754. this.onAfterRenderObservable.notifyObservers(this);
  16755. // Cleaning
  16756. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16757. this._toBeDisposed.data[index].dispose();
  16758. this._toBeDisposed[index] = null;
  16759. }
  16760. this._toBeDisposed.reset();
  16761. if (this.dumpNextRenderTargets) {
  16762. this.dumpNextRenderTargets = false;
  16763. }
  16764. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16765. this._lastFrameDuration.endMonitoring();
  16766. this._totalMeshesCounter.addCount(this.meshes.length, true);
  16767. this._totalLightsCounter.addCount(this.lights.length, true);
  16768. this._totalMaterialsCounter.addCount(this.materials.length, true);
  16769. this._totalTexturesCounter.addCount(this.textures.length, true);
  16770. this._activeBones.addCount(0, true);
  16771. this._activeIndices.addCount(0, true);
  16772. this._activeParticles.addCount(0, true);
  16773. };
  16774. Scene.prototype._updateAudioParameters = function () {
  16775. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16776. return;
  16777. }
  16778. var listeningCamera;
  16779. var audioEngine = BABYLON.Engine.audioEngine;
  16780. if (this.activeCameras.length > 0) {
  16781. listeningCamera = this.activeCameras[0];
  16782. }
  16783. else {
  16784. listeningCamera = this.activeCamera;
  16785. }
  16786. if (listeningCamera && audioEngine.canUseWebAudio) {
  16787. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  16788. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  16789. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  16790. cameraDirection.normalize();
  16791. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  16792. var i;
  16793. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16794. var sound = this.mainSoundTrack.soundCollection[i];
  16795. if (sound.useCustomAttenuation) {
  16796. sound.updateDistanceFromListener();
  16797. }
  16798. }
  16799. for (i = 0; i < this.soundTracks.length; i++) {
  16800. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16801. sound = this.soundTracks[i].soundCollection[j];
  16802. if (sound.useCustomAttenuation) {
  16803. sound.updateDistanceFromListener();
  16804. }
  16805. }
  16806. }
  16807. }
  16808. };
  16809. Object.defineProperty(Scene.prototype, "audioEnabled", {
  16810. // Audio
  16811. get: function () {
  16812. return this._audioEnabled;
  16813. },
  16814. set: function (value) {
  16815. this._audioEnabled = value;
  16816. if (BABYLON.AudioEngine) {
  16817. if (this._audioEnabled) {
  16818. this._enableAudio();
  16819. }
  16820. else {
  16821. this._disableAudio();
  16822. }
  16823. }
  16824. },
  16825. enumerable: true,
  16826. configurable: true
  16827. });
  16828. Scene.prototype._disableAudio = function () {
  16829. var i;
  16830. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16831. this.mainSoundTrack.soundCollection[i].pause();
  16832. }
  16833. for (i = 0; i < this.soundTracks.length; i++) {
  16834. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16835. this.soundTracks[i].soundCollection[j].pause();
  16836. }
  16837. }
  16838. };
  16839. Scene.prototype._enableAudio = function () {
  16840. var i;
  16841. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16842. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  16843. this.mainSoundTrack.soundCollection[i].play();
  16844. }
  16845. }
  16846. for (i = 0; i < this.soundTracks.length; i++) {
  16847. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16848. if (this.soundTracks[i].soundCollection[j].isPaused) {
  16849. this.soundTracks[i].soundCollection[j].play();
  16850. }
  16851. }
  16852. }
  16853. };
  16854. Object.defineProperty(Scene.prototype, "headphone", {
  16855. get: function () {
  16856. return this._headphone;
  16857. },
  16858. set: function (value) {
  16859. this._headphone = value;
  16860. if (BABYLON.AudioEngine) {
  16861. if (this._headphone) {
  16862. this._switchAudioModeForHeadphones();
  16863. }
  16864. else {
  16865. this._switchAudioModeForNormalSpeakers();
  16866. }
  16867. }
  16868. },
  16869. enumerable: true,
  16870. configurable: true
  16871. });
  16872. Scene.prototype._switchAudioModeForHeadphones = function () {
  16873. this.mainSoundTrack.switchPanningModelToHRTF();
  16874. for (var i = 0; i < this.soundTracks.length; i++) {
  16875. this.soundTracks[i].switchPanningModelToHRTF();
  16876. }
  16877. };
  16878. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  16879. this.mainSoundTrack.switchPanningModelToEqualPower();
  16880. for (var i = 0; i < this.soundTracks.length; i++) {
  16881. this.soundTracks[i].switchPanningModelToEqualPower();
  16882. }
  16883. };
  16884. Scene.prototype.enableDepthRenderer = function () {
  16885. if (this._depthRenderer) {
  16886. return this._depthRenderer;
  16887. }
  16888. this._depthRenderer = new BABYLON.DepthRenderer(this);
  16889. return this._depthRenderer;
  16890. };
  16891. Scene.prototype.disableDepthRenderer = function () {
  16892. if (!this._depthRenderer) {
  16893. return;
  16894. }
  16895. this._depthRenderer.dispose();
  16896. this._depthRenderer = null;
  16897. };
  16898. Scene.prototype.freezeMaterials = function () {
  16899. for (var i = 0; i < this.materials.length; i++) {
  16900. this.materials[i].freeze();
  16901. }
  16902. };
  16903. Scene.prototype.unfreezeMaterials = function () {
  16904. for (var i = 0; i < this.materials.length; i++) {
  16905. this.materials[i].unfreeze();
  16906. }
  16907. };
  16908. Scene.prototype.dispose = function () {
  16909. this.beforeRender = null;
  16910. this.afterRender = null;
  16911. this.skeletons = [];
  16912. this.morphTargetManagers = [];
  16913. if (this._depthRenderer) {
  16914. this._depthRenderer.dispose();
  16915. }
  16916. // Smart arrays
  16917. if (this.activeCamera) {
  16918. this.activeCamera._activeMeshes.dispose();
  16919. this.activeCamera = null;
  16920. }
  16921. this._activeMeshes.dispose();
  16922. this._renderingManager.dispose();
  16923. this._processedMaterials.dispose();
  16924. this._activeParticleSystems.dispose();
  16925. this._activeSkeletons.dispose();
  16926. this._softwareSkinnedMeshes.dispose();
  16927. if (this._boundingBoxRenderer) {
  16928. this._boundingBoxRenderer.dispose();
  16929. }
  16930. this._edgesRenderers.dispose();
  16931. this._meshesForIntersections.dispose();
  16932. this._toBeDisposed.dispose();
  16933. // Debug layer
  16934. if (this._debugLayer) {
  16935. this._debugLayer.hide();
  16936. }
  16937. // Events
  16938. this.onDisposeObservable.notifyObservers(this);
  16939. this.onDisposeObservable.clear();
  16940. this.onBeforeRenderObservable.clear();
  16941. this.onAfterRenderObservable.clear();
  16942. this.detachControl();
  16943. // Release sounds & sounds tracks
  16944. if (BABYLON.AudioEngine) {
  16945. this.disposeSounds();
  16946. }
  16947. // Detach cameras
  16948. var canvas = this._engine.getRenderingCanvas();
  16949. var index;
  16950. for (index = 0; index < this.cameras.length; index++) {
  16951. this.cameras[index].detachControl(canvas);
  16952. }
  16953. // Release lights
  16954. while (this.lights.length) {
  16955. this.lights[0].dispose();
  16956. }
  16957. // Release meshes
  16958. while (this.meshes.length) {
  16959. this.meshes[0].dispose(true);
  16960. }
  16961. // Release cameras
  16962. while (this.cameras.length) {
  16963. this.cameras[0].dispose();
  16964. }
  16965. // Release materials
  16966. while (this.materials.length) {
  16967. this.materials[0].dispose();
  16968. }
  16969. // Release particles
  16970. while (this.particleSystems.length) {
  16971. this.particleSystems[0].dispose();
  16972. }
  16973. // Release sprites
  16974. while (this.spriteManagers.length) {
  16975. this.spriteManagers[0].dispose();
  16976. }
  16977. // Release layers
  16978. while (this.layers.length) {
  16979. this.layers[0].dispose();
  16980. }
  16981. while (this.highlightLayers.length) {
  16982. this.highlightLayers[0].dispose();
  16983. }
  16984. // Release textures
  16985. while (this.textures.length) {
  16986. this.textures[0].dispose();
  16987. }
  16988. // Post-processes
  16989. this.postProcessManager.dispose();
  16990. // Physics
  16991. if (this._physicsEngine) {
  16992. this.disablePhysicsEngine();
  16993. }
  16994. // Remove from engine
  16995. index = this._engine.scenes.indexOf(this);
  16996. if (index > -1) {
  16997. this._engine.scenes.splice(index, 1);
  16998. }
  16999. this._engine.wipeCaches();
  17000. this._engine = null;
  17001. };
  17002. Object.defineProperty(Scene.prototype, "isDisposed", {
  17003. get: function () {
  17004. return !this._engine;
  17005. },
  17006. enumerable: true,
  17007. configurable: true
  17008. });
  17009. // Release sounds & sounds tracks
  17010. Scene.prototype.disposeSounds = function () {
  17011. this.mainSoundTrack.dispose();
  17012. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17013. this.soundTracks[scIndex].dispose();
  17014. }
  17015. };
  17016. // Octrees
  17017. Scene.prototype.getWorldExtends = function () {
  17018. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17019. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17020. for (var index = 0; index < this.meshes.length; index++) {
  17021. var mesh = this.meshes[index];
  17022. mesh.computeWorldMatrix(true);
  17023. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17024. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17025. BABYLON.Tools.CheckExtends(minBox, min, max);
  17026. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17027. }
  17028. return {
  17029. min: min,
  17030. max: max
  17031. };
  17032. };
  17033. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17034. if (maxCapacity === void 0) { maxCapacity = 64; }
  17035. if (maxDepth === void 0) { maxDepth = 2; }
  17036. if (!this._selectionOctree) {
  17037. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17038. }
  17039. var worldExtends = this.getWorldExtends();
  17040. // Update octree
  17041. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17042. return this._selectionOctree;
  17043. };
  17044. // Picking
  17045. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17046. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17047. var engine = this._engine;
  17048. if (!camera) {
  17049. if (!this.activeCamera)
  17050. throw new Error("Active camera not set");
  17051. camera = this.activeCamera;
  17052. }
  17053. var cameraViewport = camera.viewport;
  17054. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17055. // Moving coordinates to local viewport world
  17056. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17057. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17058. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17059. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17060. };
  17061. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17062. if (!BABYLON.PickingInfo) {
  17063. return null;
  17064. }
  17065. var engine = this._engine;
  17066. if (!camera) {
  17067. if (!this.activeCamera)
  17068. throw new Error("Active camera not set");
  17069. camera = this.activeCamera;
  17070. }
  17071. var cameraViewport = camera.viewport;
  17072. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17073. var identity = BABYLON.Matrix.Identity();
  17074. // Moving coordinates to local viewport world
  17075. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17076. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17077. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17078. };
  17079. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17080. if (!BABYLON.PickingInfo) {
  17081. return null;
  17082. }
  17083. var pickingInfo = null;
  17084. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17085. var mesh = this.meshes[meshIndex];
  17086. if (predicate) {
  17087. if (!predicate(mesh)) {
  17088. continue;
  17089. }
  17090. }
  17091. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17092. continue;
  17093. }
  17094. var world = mesh.getWorldMatrix();
  17095. var ray = rayFunction(world);
  17096. var result = mesh.intersects(ray, fastCheck);
  17097. if (!result || !result.hit)
  17098. continue;
  17099. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17100. continue;
  17101. pickingInfo = result;
  17102. if (fastCheck) {
  17103. break;
  17104. }
  17105. }
  17106. return pickingInfo || new BABYLON.PickingInfo();
  17107. };
  17108. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  17109. if (!BABYLON.PickingInfo) {
  17110. return null;
  17111. }
  17112. var pickingInfos = new Array();
  17113. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17114. var mesh = this.meshes[meshIndex];
  17115. if (predicate) {
  17116. if (!predicate(mesh)) {
  17117. continue;
  17118. }
  17119. }
  17120. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17121. continue;
  17122. }
  17123. var world = mesh.getWorldMatrix();
  17124. var ray = rayFunction(world);
  17125. var result = mesh.intersects(ray, false);
  17126. if (!result || !result.hit)
  17127. continue;
  17128. pickingInfos.push(result);
  17129. }
  17130. return pickingInfos;
  17131. };
  17132. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17133. if (!BABYLON.PickingInfo) {
  17134. return null;
  17135. }
  17136. var pickingInfo = null;
  17137. camera = camera || this.activeCamera;
  17138. if (this.spriteManagers.length > 0) {
  17139. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17140. var spriteManager = this.spriteManagers[spriteIndex];
  17141. if (!spriteManager.isPickable) {
  17142. continue;
  17143. }
  17144. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17145. if (!result || !result.hit)
  17146. continue;
  17147. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17148. continue;
  17149. pickingInfo = result;
  17150. if (fastCheck) {
  17151. break;
  17152. }
  17153. }
  17154. }
  17155. return pickingInfo || new BABYLON.PickingInfo();
  17156. };
  17157. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17158. /// <param name="x">X position on screen</param>
  17159. /// <param name="y">Y position on screen</param>
  17160. /// <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>
  17161. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17162. /// <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>
  17163. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17164. var _this = this;
  17165. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17166. };
  17167. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17168. /// <param name="x">X position on screen</param>
  17169. /// <param name="y">Y position on screen</param>
  17170. /// <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>
  17171. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17172. /// <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>
  17173. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17174. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17175. };
  17176. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17177. var _this = this;
  17178. return this._internalPick(function (world) {
  17179. if (!_this._pickWithRayInverseMatrix) {
  17180. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17181. }
  17182. world.invertToRef(_this._pickWithRayInverseMatrix);
  17183. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17184. }, predicate, fastCheck);
  17185. };
  17186. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17187. /// <param name="x">X position on screen</param>
  17188. /// <param name="y">Y position on screen</param>
  17189. /// <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>
  17190. /// <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>
  17191. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  17192. var _this = this;
  17193. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  17194. };
  17195. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17196. /// <param name="ray">Ray to use</param>
  17197. /// <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>
  17198. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  17199. var _this = this;
  17200. return this._internalMultiPick(function (world) {
  17201. if (!_this._pickWithRayInverseMatrix) {
  17202. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17203. }
  17204. world.invertToRef(_this._pickWithRayInverseMatrix);
  17205. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17206. }, predicate);
  17207. };
  17208. Scene.prototype.setPointerOverMesh = function (mesh) {
  17209. if (this._pointerOverMesh === mesh) {
  17210. return;
  17211. }
  17212. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17213. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17214. }
  17215. this._pointerOverMesh = mesh;
  17216. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17217. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17218. }
  17219. };
  17220. Scene.prototype.getPointerOverMesh = function () {
  17221. return this._pointerOverMesh;
  17222. };
  17223. Scene.prototype.setPointerOverSprite = function (sprite) {
  17224. if (this._pointerOverSprite === sprite) {
  17225. return;
  17226. }
  17227. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17228. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17229. }
  17230. this._pointerOverSprite = sprite;
  17231. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17232. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17233. }
  17234. };
  17235. Scene.prototype.getPointerOverSprite = function () {
  17236. return this._pointerOverSprite;
  17237. };
  17238. // Physics
  17239. Scene.prototype.getPhysicsEngine = function () {
  17240. return this._physicsEngine;
  17241. };
  17242. /**
  17243. * Enables physics to the current scene
  17244. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17245. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17246. * @return {boolean} was the physics engine initialized
  17247. */
  17248. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17249. if (this._physicsEngine) {
  17250. return true;
  17251. }
  17252. try {
  17253. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17254. return true;
  17255. }
  17256. catch (e) {
  17257. BABYLON.Tools.Error(e.message);
  17258. return false;
  17259. }
  17260. };
  17261. Scene.prototype.disablePhysicsEngine = function () {
  17262. if (!this._physicsEngine) {
  17263. return;
  17264. }
  17265. this._physicsEngine.dispose();
  17266. this._physicsEngine = undefined;
  17267. };
  17268. Scene.prototype.isPhysicsEnabled = function () {
  17269. return this._physicsEngine !== undefined;
  17270. };
  17271. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17272. var mesh = compound.parts[0].mesh;
  17273. mesh.physicsImpostor.dispose();
  17274. mesh.physicsImpostor = null;
  17275. };
  17276. // Misc.
  17277. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  17278. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  17279. // Light
  17280. if (this.lights.length === 0) {
  17281. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17282. }
  17283. // Camera
  17284. if (!this.activeCamera) {
  17285. // Compute position
  17286. var worldExtends = this.getWorldExtends();
  17287. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  17288. var camera;
  17289. if (createArcRotateCamera) {
  17290. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  17291. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  17292. camera.lowerRadiusLimit = 0.5;
  17293. camera.setTarget(worldCenter);
  17294. }
  17295. else {
  17296. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  17297. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  17298. camera.setTarget(worldCenter);
  17299. }
  17300. camera.minZ = 0.1;
  17301. var maxDist = worldExtends.max.subtract(worldExtends.min).length();
  17302. camera.wheelPrecision = 100.0 / maxDist;
  17303. this.activeCamera = camera;
  17304. }
  17305. };
  17306. // Tags
  17307. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17308. if (tagsQuery === undefined) {
  17309. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17310. return list;
  17311. }
  17312. var listByTags = [];
  17313. forEach = forEach || (function (item) { return; });
  17314. for (var i in list) {
  17315. var item = list[i];
  17316. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17317. listByTags.push(item);
  17318. forEach(item);
  17319. }
  17320. }
  17321. return listByTags;
  17322. };
  17323. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17324. return this._getByTags(this.meshes, tagsQuery, forEach);
  17325. };
  17326. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17327. return this._getByTags(this.cameras, tagsQuery, forEach);
  17328. };
  17329. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17330. return this._getByTags(this.lights, tagsQuery, forEach);
  17331. };
  17332. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17333. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17334. };
  17335. /**
  17336. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17337. * This allowed control for front to back rendering or reversly depending of the special needs.
  17338. *
  17339. * @param renderingGroupId The rendering group id corresponding to its index
  17340. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17341. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17342. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17343. */
  17344. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17345. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17346. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17347. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17348. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  17349. };
  17350. /**
  17351. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17352. *
  17353. * @param renderingGroupId The rendering group id corresponding to its index
  17354. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17355. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17356. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17357. */
  17358. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17359. if (depth === void 0) { depth = true; }
  17360. if (stencil === void 0) { stencil = true; }
  17361. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  17362. };
  17363. /**
  17364. * Will flag all materials as dirty to trigger new shader compilation
  17365. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  17366. */
  17367. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  17368. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  17369. var material = _a[_i];
  17370. if (predicate && !predicate(material)) {
  17371. continue;
  17372. }
  17373. material.markAsDirty(flag);
  17374. }
  17375. };
  17376. return Scene;
  17377. }());
  17378. // Statics
  17379. Scene._FOGMODE_NONE = 0;
  17380. Scene._FOGMODE_EXP = 1;
  17381. Scene._FOGMODE_EXP2 = 2;
  17382. Scene._FOGMODE_LINEAR = 3;
  17383. Scene.MinDeltaTime = 1.0;
  17384. Scene.MaxDeltaTime = 1000.0;
  17385. Scene.DragMovementThreshold = 10; // in pixels
  17386. Scene.LongPressDelay = 500; // in milliseconds
  17387. Scene.DoubleClickDelay = 300; // in milliseconds
  17388. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  17389. BABYLON.Scene = Scene;
  17390. })(BABYLON || (BABYLON = {}));
  17391. //# sourceMappingURL=babylon.scene.js.map
  17392. var BABYLON;
  17393. (function (BABYLON) {
  17394. var Buffer = (function () {
  17395. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  17396. if (engine instanceof BABYLON.Mesh) {
  17397. this._engine = engine.getScene().getEngine();
  17398. }
  17399. else {
  17400. this._engine = engine;
  17401. }
  17402. this._updatable = updatable;
  17403. this._data = data;
  17404. this._strideSize = stride;
  17405. if (!postponeInternalCreation) {
  17406. this.create();
  17407. }
  17408. this._instanced = instanced;
  17409. }
  17410. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  17411. // a lot of these parameters are ignored as they are overriden by the buffer
  17412. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  17413. };
  17414. // Properties
  17415. Buffer.prototype.isUpdatable = function () {
  17416. return this._updatable;
  17417. };
  17418. Buffer.prototype.getData = function () {
  17419. return this._data;
  17420. };
  17421. Buffer.prototype.getBuffer = function () {
  17422. return this._buffer;
  17423. };
  17424. Buffer.prototype.getStrideSize = function () {
  17425. return this._strideSize;
  17426. };
  17427. Buffer.prototype.getIsInstanced = function () {
  17428. return this._instanced;
  17429. };
  17430. // Methods
  17431. Buffer.prototype.create = function (data) {
  17432. if (!data && this._buffer) {
  17433. return; // nothing to do
  17434. }
  17435. data = data || this._data;
  17436. if (!this._buffer) {
  17437. if (this._updatable) {
  17438. this._buffer = this._engine.createDynamicVertexBuffer(data);
  17439. this._data = data;
  17440. }
  17441. else {
  17442. this._buffer = this._engine.createVertexBuffer(data);
  17443. }
  17444. }
  17445. else if (this._updatable) {
  17446. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  17447. this._data = data;
  17448. }
  17449. };
  17450. Buffer.prototype.update = function (data) {
  17451. this.create(data);
  17452. };
  17453. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  17454. if (!this._buffer) {
  17455. return;
  17456. }
  17457. if (this._updatable) {
  17458. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  17459. this._data = null;
  17460. }
  17461. };
  17462. Buffer.prototype.dispose = function () {
  17463. if (!this._buffer) {
  17464. return;
  17465. }
  17466. if (this._engine._releaseBuffer(this._buffer)) {
  17467. this._buffer = null;
  17468. }
  17469. };
  17470. return Buffer;
  17471. }());
  17472. BABYLON.Buffer = Buffer;
  17473. })(BABYLON || (BABYLON = {}));
  17474. //# sourceMappingURL=babylon.buffer.js.map
  17475. var BABYLON;
  17476. (function (BABYLON) {
  17477. var VertexBuffer = (function () {
  17478. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  17479. if (!stride) {
  17480. // Deduce stride from kind
  17481. switch (kind) {
  17482. case VertexBuffer.PositionKind:
  17483. stride = 3;
  17484. break;
  17485. case VertexBuffer.NormalKind:
  17486. stride = 3;
  17487. break;
  17488. case VertexBuffer.UVKind:
  17489. case VertexBuffer.UV2Kind:
  17490. case VertexBuffer.UV3Kind:
  17491. case VertexBuffer.UV4Kind:
  17492. case VertexBuffer.UV5Kind:
  17493. case VertexBuffer.UV6Kind:
  17494. stride = 2;
  17495. break;
  17496. case VertexBuffer.TangentKind:
  17497. case VertexBuffer.ColorKind:
  17498. stride = 4;
  17499. break;
  17500. case VertexBuffer.MatricesIndicesKind:
  17501. case VertexBuffer.MatricesIndicesExtraKind:
  17502. stride = 4;
  17503. break;
  17504. case VertexBuffer.MatricesWeightsKind:
  17505. case VertexBuffer.MatricesWeightsExtraKind:
  17506. stride = 4;
  17507. break;
  17508. }
  17509. }
  17510. if (data instanceof BABYLON.Buffer) {
  17511. if (!stride) {
  17512. stride = data.getStrideSize();
  17513. }
  17514. this._buffer = data;
  17515. this._ownsBuffer = false;
  17516. }
  17517. else {
  17518. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  17519. this._ownsBuffer = true;
  17520. }
  17521. this._stride = stride;
  17522. this._offset = offset ? offset : 0;
  17523. this._size = size ? size : stride;
  17524. this._kind = kind;
  17525. }
  17526. /**
  17527. * Returns the kind of the VertexBuffer (string).
  17528. */
  17529. VertexBuffer.prototype.getKind = function () {
  17530. return this._kind;
  17531. };
  17532. // Properties
  17533. /**
  17534. * Boolean : is the VertexBuffer updatable ?
  17535. */
  17536. VertexBuffer.prototype.isUpdatable = function () {
  17537. return this._buffer.isUpdatable();
  17538. };
  17539. /**
  17540. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  17541. */
  17542. VertexBuffer.prototype.getData = function () {
  17543. return this._buffer.getData();
  17544. };
  17545. /**
  17546. * Returns the WebGLBuffer associated to the VertexBuffer.
  17547. */
  17548. VertexBuffer.prototype.getBuffer = function () {
  17549. return this._buffer.getBuffer();
  17550. };
  17551. /**
  17552. * Returns the stride of the VertexBuffer (integer).
  17553. */
  17554. VertexBuffer.prototype.getStrideSize = function () {
  17555. return this._stride;
  17556. };
  17557. /**
  17558. * Returns the offset (integer).
  17559. */
  17560. VertexBuffer.prototype.getOffset = function () {
  17561. return this._offset;
  17562. };
  17563. /**
  17564. * Returns the VertexBuffer total size (integer).
  17565. */
  17566. VertexBuffer.prototype.getSize = function () {
  17567. return this._size;
  17568. };
  17569. /**
  17570. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  17571. */
  17572. VertexBuffer.prototype.getIsInstanced = function () {
  17573. return this._buffer.getIsInstanced();
  17574. };
  17575. // Methods
  17576. /**
  17577. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  17578. * Returns the created WebGLBuffer.
  17579. */
  17580. VertexBuffer.prototype.create = function (data) {
  17581. return this._buffer.create(data);
  17582. };
  17583. /**
  17584. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  17585. * Returns the updated WebGLBuffer.
  17586. */
  17587. VertexBuffer.prototype.update = function (data) {
  17588. return this._buffer.update(data);
  17589. };
  17590. /**
  17591. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  17592. * Returns the directly updated WebGLBuffer.
  17593. */
  17594. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  17595. return this._buffer.updateDirectly(data, offset);
  17596. };
  17597. /**
  17598. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  17599. */
  17600. VertexBuffer.prototype.dispose = function () {
  17601. if (this._ownsBuffer) {
  17602. this._buffer.dispose();
  17603. }
  17604. };
  17605. Object.defineProperty(VertexBuffer, "PositionKind", {
  17606. get: function () {
  17607. return VertexBuffer._PositionKind;
  17608. },
  17609. enumerable: true,
  17610. configurable: true
  17611. });
  17612. Object.defineProperty(VertexBuffer, "NormalKind", {
  17613. get: function () {
  17614. return VertexBuffer._NormalKind;
  17615. },
  17616. enumerable: true,
  17617. configurable: true
  17618. });
  17619. Object.defineProperty(VertexBuffer, "TangentKind", {
  17620. get: function () {
  17621. return VertexBuffer._TangentKind;
  17622. },
  17623. enumerable: true,
  17624. configurable: true
  17625. });
  17626. Object.defineProperty(VertexBuffer, "UVKind", {
  17627. get: function () {
  17628. return VertexBuffer._UVKind;
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. Object.defineProperty(VertexBuffer, "UV2Kind", {
  17634. get: function () {
  17635. return VertexBuffer._UV2Kind;
  17636. },
  17637. enumerable: true,
  17638. configurable: true
  17639. });
  17640. Object.defineProperty(VertexBuffer, "UV3Kind", {
  17641. get: function () {
  17642. return VertexBuffer._UV3Kind;
  17643. },
  17644. enumerable: true,
  17645. configurable: true
  17646. });
  17647. Object.defineProperty(VertexBuffer, "UV4Kind", {
  17648. get: function () {
  17649. return VertexBuffer._UV4Kind;
  17650. },
  17651. enumerable: true,
  17652. configurable: true
  17653. });
  17654. Object.defineProperty(VertexBuffer, "UV5Kind", {
  17655. get: function () {
  17656. return VertexBuffer._UV5Kind;
  17657. },
  17658. enumerable: true,
  17659. configurable: true
  17660. });
  17661. Object.defineProperty(VertexBuffer, "UV6Kind", {
  17662. get: function () {
  17663. return VertexBuffer._UV6Kind;
  17664. },
  17665. enumerable: true,
  17666. configurable: true
  17667. });
  17668. Object.defineProperty(VertexBuffer, "ColorKind", {
  17669. get: function () {
  17670. return VertexBuffer._ColorKind;
  17671. },
  17672. enumerable: true,
  17673. configurable: true
  17674. });
  17675. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  17676. get: function () {
  17677. return VertexBuffer._MatricesIndicesKind;
  17678. },
  17679. enumerable: true,
  17680. configurable: true
  17681. });
  17682. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  17683. get: function () {
  17684. return VertexBuffer._MatricesWeightsKind;
  17685. },
  17686. enumerable: true,
  17687. configurable: true
  17688. });
  17689. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  17690. get: function () {
  17691. return VertexBuffer._MatricesIndicesExtraKind;
  17692. },
  17693. enumerable: true,
  17694. configurable: true
  17695. });
  17696. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  17697. get: function () {
  17698. return VertexBuffer._MatricesWeightsExtraKind;
  17699. },
  17700. enumerable: true,
  17701. configurable: true
  17702. });
  17703. return VertexBuffer;
  17704. }());
  17705. // Enums
  17706. VertexBuffer._PositionKind = "position";
  17707. VertexBuffer._NormalKind = "normal";
  17708. VertexBuffer._TangentKind = "tangent";
  17709. VertexBuffer._UVKind = "uv";
  17710. VertexBuffer._UV2Kind = "uv2";
  17711. VertexBuffer._UV3Kind = "uv3";
  17712. VertexBuffer._UV4Kind = "uv4";
  17713. VertexBuffer._UV5Kind = "uv5";
  17714. VertexBuffer._UV6Kind = "uv6";
  17715. VertexBuffer._ColorKind = "color";
  17716. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  17717. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  17718. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  17719. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  17720. BABYLON.VertexBuffer = VertexBuffer;
  17721. })(BABYLON || (BABYLON = {}));
  17722. //# sourceMappingURL=babylon.vertexBuffer.js.map
  17723. var BABYLON;
  17724. (function (BABYLON) {
  17725. var BaseTexture = (function () {
  17726. function BaseTexture(scene) {
  17727. this._hasAlpha = false;
  17728. this.getAlphaFromRGB = false;
  17729. this.level = 1;
  17730. this.coordinatesIndex = 0;
  17731. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17732. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17733. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17734. this.anisotropicFilteringLevel = 4;
  17735. this.isCube = false;
  17736. this.isRenderTarget = false;
  17737. this.animations = new Array();
  17738. /**
  17739. * An event triggered when the texture is disposed.
  17740. * @type {BABYLON.Observable}
  17741. */
  17742. this.onDisposeObservable = new BABYLON.Observable();
  17743. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17744. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  17745. this._scene.textures.push(this);
  17746. this._uid = null;
  17747. }
  17748. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  17749. get: function () {
  17750. return this._hasAlpha;
  17751. },
  17752. set: function (value) {
  17753. if (this._hasAlpha === value) {
  17754. return;
  17755. }
  17756. this._hasAlpha = value;
  17757. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17758. },
  17759. enumerable: true,
  17760. configurable: true
  17761. });
  17762. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  17763. get: function () {
  17764. return this._coordinatesMode;
  17765. },
  17766. set: function (value) {
  17767. if (this._coordinatesMode === value) {
  17768. return;
  17769. }
  17770. this._coordinatesMode = value;
  17771. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17772. },
  17773. enumerable: true,
  17774. configurable: true
  17775. });
  17776. Object.defineProperty(BaseTexture.prototype, "uid", {
  17777. get: function () {
  17778. if (!this._uid) {
  17779. this._uid = BABYLON.Tools.RandomId();
  17780. }
  17781. return this._uid;
  17782. },
  17783. enumerable: true,
  17784. configurable: true
  17785. });
  17786. BaseTexture.prototype.toString = function () {
  17787. return this.name;
  17788. };
  17789. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  17790. set: function (callback) {
  17791. if (this._onDisposeObserver) {
  17792. this.onDisposeObservable.remove(this._onDisposeObserver);
  17793. }
  17794. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17795. },
  17796. enumerable: true,
  17797. configurable: true
  17798. });
  17799. BaseTexture.prototype.getScene = function () {
  17800. return this._scene;
  17801. };
  17802. BaseTexture.prototype.getTextureMatrix = function () {
  17803. return null;
  17804. };
  17805. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17806. return null;
  17807. };
  17808. BaseTexture.prototype.getInternalTexture = function () {
  17809. return this._texture;
  17810. };
  17811. BaseTexture.prototype.isReady = function () {
  17812. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17813. return true;
  17814. }
  17815. if (this._texture) {
  17816. return this._texture.isReady;
  17817. }
  17818. return false;
  17819. };
  17820. BaseTexture.prototype.getSize = function () {
  17821. if (this._texture._width) {
  17822. return new BABYLON.Size(this._texture._width, this._texture._height);
  17823. }
  17824. if (this._texture._size) {
  17825. return new BABYLON.Size(this._texture._size, this._texture._size);
  17826. }
  17827. return BABYLON.Size.Zero();
  17828. };
  17829. BaseTexture.prototype.getBaseSize = function () {
  17830. if (!this.isReady() || !this._texture)
  17831. return BABYLON.Size.Zero();
  17832. if (this._texture._size) {
  17833. return new BABYLON.Size(this._texture._size, this._texture._size);
  17834. }
  17835. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  17836. };
  17837. BaseTexture.prototype.scale = function (ratio) {
  17838. };
  17839. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17840. get: function () {
  17841. return false;
  17842. },
  17843. enumerable: true,
  17844. configurable: true
  17845. });
  17846. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17847. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17848. for (var index = 0; index < texturesCache.length; index++) {
  17849. var texturesCacheEntry = texturesCache[index];
  17850. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17851. texturesCache.splice(index, 1);
  17852. return;
  17853. }
  17854. }
  17855. };
  17856. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17857. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17858. for (var index = 0; index < texturesCache.length; index++) {
  17859. var texturesCacheEntry = texturesCache[index];
  17860. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17861. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17862. texturesCacheEntry.references++;
  17863. return texturesCacheEntry;
  17864. }
  17865. }
  17866. }
  17867. return null;
  17868. };
  17869. BaseTexture.prototype.delayLoad = function () {
  17870. };
  17871. BaseTexture.prototype.clone = function () {
  17872. return null;
  17873. };
  17874. BaseTexture.prototype.releaseInternalTexture = function () {
  17875. if (this._texture) {
  17876. this._scene.getEngine().releaseInternalTexture(this._texture);
  17877. delete this._texture;
  17878. }
  17879. };
  17880. BaseTexture.prototype.dispose = function () {
  17881. // Animations
  17882. this.getScene().stopAnimation(this);
  17883. // Remove from scene
  17884. this._scene._removePendingData(this);
  17885. var index = this._scene.textures.indexOf(this);
  17886. if (index >= 0) {
  17887. this._scene.textures.splice(index, 1);
  17888. }
  17889. if (this._texture === undefined) {
  17890. return;
  17891. }
  17892. // Release
  17893. this.releaseInternalTexture();
  17894. // Callback
  17895. this.onDisposeObservable.notifyObservers(this);
  17896. this.onDisposeObservable.clear();
  17897. };
  17898. BaseTexture.prototype.serialize = function () {
  17899. if (!this.name) {
  17900. return null;
  17901. }
  17902. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17903. // Animations
  17904. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17905. return serializationObject;
  17906. };
  17907. return BaseTexture;
  17908. }());
  17909. __decorate([
  17910. BABYLON.serialize()
  17911. ], BaseTexture.prototype, "name", void 0);
  17912. __decorate([
  17913. BABYLON.serialize("hasAlpha")
  17914. ], BaseTexture.prototype, "_hasAlpha", void 0);
  17915. __decorate([
  17916. BABYLON.serialize()
  17917. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  17918. __decorate([
  17919. BABYLON.serialize()
  17920. ], BaseTexture.prototype, "level", void 0);
  17921. __decorate([
  17922. BABYLON.serialize()
  17923. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  17924. __decorate([
  17925. BABYLON.serialize("coordinatesMode")
  17926. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  17927. __decorate([
  17928. BABYLON.serialize()
  17929. ], BaseTexture.prototype, "wrapU", void 0);
  17930. __decorate([
  17931. BABYLON.serialize()
  17932. ], BaseTexture.prototype, "wrapV", void 0);
  17933. __decorate([
  17934. BABYLON.serialize()
  17935. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  17936. __decorate([
  17937. BABYLON.serialize()
  17938. ], BaseTexture.prototype, "isCube", void 0);
  17939. __decorate([
  17940. BABYLON.serialize()
  17941. ], BaseTexture.prototype, "isRenderTarget", void 0);
  17942. BABYLON.BaseTexture = BaseTexture;
  17943. })(BABYLON || (BABYLON = {}));
  17944. //# sourceMappingURL=babylon.baseTexture.js.map
  17945. var BABYLON;
  17946. (function (BABYLON) {
  17947. var Texture = (function (_super) {
  17948. __extends(Texture, _super);
  17949. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  17950. if (noMipmap === void 0) { noMipmap = false; }
  17951. if (invertY === void 0) { invertY = true; }
  17952. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17953. if (onLoad === void 0) { onLoad = null; }
  17954. if (onError === void 0) { onError = null; }
  17955. if (buffer === void 0) { buffer = null; }
  17956. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17957. var _this = _super.call(this, scene) || this;
  17958. _this.uOffset = 0;
  17959. _this.vOffset = 0;
  17960. _this.uScale = 1.0;
  17961. _this.vScale = 1.0;
  17962. _this.uAng = 0;
  17963. _this.vAng = 0;
  17964. _this.wAng = 0;
  17965. _this.name = url;
  17966. _this.url = url;
  17967. _this._noMipmap = noMipmap;
  17968. _this._invertY = invertY;
  17969. _this._samplingMode = samplingMode;
  17970. _this._buffer = buffer;
  17971. _this._deleteBuffer = deleteBuffer;
  17972. _this._format = format;
  17973. if (!url) {
  17974. return _this;
  17975. }
  17976. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  17977. var load = function () {
  17978. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  17979. _this.onLoadObservable.notifyObservers(true);
  17980. }
  17981. if (onLoad) {
  17982. onLoad();
  17983. }
  17984. };
  17985. if (!_this._texture) {
  17986. if (!scene.useDelayedTextureLoading) {
  17987. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  17988. if (deleteBuffer) {
  17989. delete _this._buffer;
  17990. }
  17991. }
  17992. else {
  17993. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17994. _this._delayedOnLoad = load;
  17995. _this._delayedOnError = onError;
  17996. }
  17997. }
  17998. else {
  17999. if (_this._texture.isReady) {
  18000. BABYLON.Tools.SetImmediate(function () { return load(); });
  18001. }
  18002. else {
  18003. _this._texture.onLoadedCallbacks.push(load);
  18004. }
  18005. }
  18006. return _this;
  18007. }
  18008. Object.defineProperty(Texture.prototype, "noMipmap", {
  18009. get: function () {
  18010. return this._noMipmap;
  18011. },
  18012. enumerable: true,
  18013. configurable: true
  18014. });
  18015. Texture.prototype.delayLoad = function () {
  18016. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18017. return;
  18018. }
  18019. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18020. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  18021. if (!this._texture) {
  18022. 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);
  18023. if (this._deleteBuffer) {
  18024. delete this._buffer;
  18025. }
  18026. }
  18027. };
  18028. Texture.prototype.updateSamplingMode = function (samplingMode) {
  18029. if (!this._texture) {
  18030. return;
  18031. }
  18032. this._samplingMode = samplingMode;
  18033. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  18034. };
  18035. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  18036. x *= this.uScale;
  18037. y *= this.vScale;
  18038. x -= 0.5 * this.uScale;
  18039. y -= 0.5 * this.vScale;
  18040. z -= 0.5;
  18041. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  18042. t.x += 0.5 * this.uScale + this.uOffset;
  18043. t.y += 0.5 * this.vScale + this.vOffset;
  18044. t.z += 0.5;
  18045. };
  18046. Texture.prototype.getTextureMatrix = function () {
  18047. if (this.uOffset === this._cachedUOffset &&
  18048. this.vOffset === this._cachedVOffset &&
  18049. this.uScale === this._cachedUScale &&
  18050. this.vScale === this._cachedVScale &&
  18051. this.uAng === this._cachedUAng &&
  18052. this.vAng === this._cachedVAng &&
  18053. this.wAng === this._cachedWAng) {
  18054. return this._cachedTextureMatrix;
  18055. }
  18056. this._cachedUOffset = this.uOffset;
  18057. this._cachedVOffset = this.vOffset;
  18058. this._cachedUScale = this.uScale;
  18059. this._cachedVScale = this.vScale;
  18060. this._cachedUAng = this.uAng;
  18061. this._cachedVAng = this.vAng;
  18062. this._cachedWAng = this.wAng;
  18063. if (!this._cachedTextureMatrix) {
  18064. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  18065. this._rowGenerationMatrix = new BABYLON.Matrix();
  18066. this._t0 = BABYLON.Vector3.Zero();
  18067. this._t1 = BABYLON.Vector3.Zero();
  18068. this._t2 = BABYLON.Vector3.Zero();
  18069. }
  18070. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  18071. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  18072. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  18073. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  18074. this._t1.subtractInPlace(this._t0);
  18075. this._t2.subtractInPlace(this._t0);
  18076. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18077. this._cachedTextureMatrix.m[0] = this._t1.x;
  18078. this._cachedTextureMatrix.m[1] = this._t1.y;
  18079. this._cachedTextureMatrix.m[2] = this._t1.z;
  18080. this._cachedTextureMatrix.m[4] = this._t2.x;
  18081. this._cachedTextureMatrix.m[5] = this._t2.y;
  18082. this._cachedTextureMatrix.m[6] = this._t2.z;
  18083. this._cachedTextureMatrix.m[8] = this._t0.x;
  18084. this._cachedTextureMatrix.m[9] = this._t0.y;
  18085. this._cachedTextureMatrix.m[10] = this._t0.z;
  18086. return this._cachedTextureMatrix;
  18087. };
  18088. Texture.prototype.getReflectionTextureMatrix = function () {
  18089. if (this.uOffset === this._cachedUOffset &&
  18090. this.vOffset === this._cachedVOffset &&
  18091. this.uScale === this._cachedUScale &&
  18092. this.vScale === this._cachedVScale &&
  18093. this.coordinatesMode === this._cachedCoordinatesMode) {
  18094. return this._cachedTextureMatrix;
  18095. }
  18096. if (!this._cachedTextureMatrix) {
  18097. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  18098. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  18099. }
  18100. this._cachedCoordinatesMode = this.coordinatesMode;
  18101. switch (this.coordinatesMode) {
  18102. case Texture.PLANAR_MODE:
  18103. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18104. this._cachedTextureMatrix[0] = this.uScale;
  18105. this._cachedTextureMatrix[5] = this.vScale;
  18106. this._cachedTextureMatrix[12] = this.uOffset;
  18107. this._cachedTextureMatrix[13] = this.vOffset;
  18108. break;
  18109. case Texture.PROJECTION_MODE:
  18110. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  18111. this._projectionModeMatrix.m[0] = 0.5;
  18112. this._projectionModeMatrix.m[5] = -0.5;
  18113. this._projectionModeMatrix.m[10] = 0.0;
  18114. this._projectionModeMatrix.m[12] = 0.5;
  18115. this._projectionModeMatrix.m[13] = 0.5;
  18116. this._projectionModeMatrix.m[14] = 1.0;
  18117. this._projectionModeMatrix.m[15] = 1.0;
  18118. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  18119. break;
  18120. default:
  18121. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18122. break;
  18123. }
  18124. return this._cachedTextureMatrix;
  18125. };
  18126. Texture.prototype.clone = function () {
  18127. var _this = this;
  18128. return BABYLON.SerializationHelper.Clone(function () {
  18129. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  18130. }, this);
  18131. };
  18132. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  18133. get: function () {
  18134. if (!this._onLoadObservarble) {
  18135. this._onLoadObservarble = new BABYLON.Observable();
  18136. }
  18137. return this._onLoadObservarble;
  18138. },
  18139. enumerable: true,
  18140. configurable: true
  18141. });
  18142. // Statics
  18143. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  18144. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18145. if (onLoad === void 0) { onLoad = null; }
  18146. if (onError === void 0) { onError = null; }
  18147. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  18148. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  18149. };
  18150. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  18151. if (parsedTexture.customType) {
  18152. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  18153. // Update Sampling Mode
  18154. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  18155. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  18156. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  18157. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  18158. }
  18159. }
  18160. return parsedCustomTexture;
  18161. }
  18162. if (parsedTexture.isCube) {
  18163. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  18164. }
  18165. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18166. return null;
  18167. }
  18168. var texture = BABYLON.SerializationHelper.Parse(function () {
  18169. if (parsedTexture.mirrorPlane) {
  18170. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18171. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  18172. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18173. return mirrorTexture;
  18174. }
  18175. else if (parsedTexture.isRenderTarget) {
  18176. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18177. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  18178. return renderTargetTexture;
  18179. }
  18180. else {
  18181. var texture;
  18182. if (parsedTexture.base64String) {
  18183. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  18184. }
  18185. else {
  18186. texture = new Texture(rootUrl + parsedTexture.name, scene);
  18187. }
  18188. return texture;
  18189. }
  18190. }, parsedTexture, scene);
  18191. // Update Sampling Mode
  18192. if (parsedTexture.samplingMode) {
  18193. var sampling = parsedTexture.samplingMode;
  18194. if (texture._samplingMode !== sampling) {
  18195. texture.updateSamplingMode(sampling);
  18196. }
  18197. }
  18198. // Animations
  18199. if (parsedTexture.animations) {
  18200. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18201. var parsedAnimation = parsedTexture.animations[animationIndex];
  18202. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18203. }
  18204. }
  18205. return texture;
  18206. };
  18207. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  18208. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18209. if (noMipmap === void 0) { noMipmap = false; }
  18210. if (invertY === void 0) { invertY = true; }
  18211. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18212. if (onLoad === void 0) { onLoad = null; }
  18213. if (onError === void 0) { onError = null; }
  18214. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  18215. if (name.substr(0, 5) !== "data:") {
  18216. name = "data:" + name;
  18217. }
  18218. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  18219. };
  18220. return Texture;
  18221. }(BABYLON.BaseTexture));
  18222. // Constants
  18223. Texture.NEAREST_SAMPLINGMODE = 1;
  18224. Texture.BILINEAR_SAMPLINGMODE = 2;
  18225. Texture.TRILINEAR_SAMPLINGMODE = 3;
  18226. Texture.EXPLICIT_MODE = 0;
  18227. Texture.SPHERICAL_MODE = 1;
  18228. Texture.PLANAR_MODE = 2;
  18229. Texture.CUBIC_MODE = 3;
  18230. Texture.PROJECTION_MODE = 4;
  18231. Texture.SKYBOX_MODE = 5;
  18232. Texture.INVCUBIC_MODE = 6;
  18233. Texture.EQUIRECTANGULAR_MODE = 7;
  18234. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  18235. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18236. Texture.CLAMP_ADDRESSMODE = 0;
  18237. Texture.WRAP_ADDRESSMODE = 1;
  18238. Texture.MIRROR_ADDRESSMODE = 2;
  18239. __decorate([
  18240. BABYLON.serialize()
  18241. ], Texture.prototype, "url", void 0);
  18242. __decorate([
  18243. BABYLON.serialize()
  18244. ], Texture.prototype, "uOffset", void 0);
  18245. __decorate([
  18246. BABYLON.serialize()
  18247. ], Texture.prototype, "vOffset", void 0);
  18248. __decorate([
  18249. BABYLON.serialize()
  18250. ], Texture.prototype, "uScale", void 0);
  18251. __decorate([
  18252. BABYLON.serialize()
  18253. ], Texture.prototype, "vScale", void 0);
  18254. __decorate([
  18255. BABYLON.serialize()
  18256. ], Texture.prototype, "uAng", void 0);
  18257. __decorate([
  18258. BABYLON.serialize()
  18259. ], Texture.prototype, "vAng", void 0);
  18260. __decorate([
  18261. BABYLON.serialize()
  18262. ], Texture.prototype, "wAng", void 0);
  18263. BABYLON.Texture = Texture;
  18264. })(BABYLON || (BABYLON = {}));
  18265. //# sourceMappingURL=babylon.texture.js.map
  18266. var BABYLON;
  18267. (function (BABYLON) {
  18268. var _InstancesBatch = (function () {
  18269. function _InstancesBatch() {
  18270. this.mustReturn = false;
  18271. this.visibleInstances = new Array();
  18272. this.renderSelf = new Array();
  18273. }
  18274. return _InstancesBatch;
  18275. }());
  18276. BABYLON._InstancesBatch = _InstancesBatch;
  18277. var Mesh = (function (_super) {
  18278. __extends(Mesh, _super);
  18279. /**
  18280. * @constructor
  18281. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18282. * @param {Scene} scene The scene to add this mesh to.
  18283. * @param {Node} parent The parent of this mesh, if it has one
  18284. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18285. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18286. * When false, achieved by calling a clone(), also passing False.
  18287. * This will make creation of children, recursive.
  18288. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  18289. */
  18290. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18291. if (parent === void 0) { parent = null; }
  18292. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18293. var _this = _super.call(this, name, scene) || this;
  18294. // Events
  18295. /**
  18296. * An event triggered before rendering the mesh
  18297. * @type {BABYLON.Observable}
  18298. */
  18299. _this.onBeforeRenderObservable = new BABYLON.Observable();
  18300. /**
  18301. * An event triggered after rendering the mesh
  18302. * @type {BABYLON.Observable}
  18303. */
  18304. _this.onAfterRenderObservable = new BABYLON.Observable();
  18305. /**
  18306. * An event triggered before drawing the mesh
  18307. * @type {BABYLON.Observable}
  18308. */
  18309. _this.onBeforeDrawObservable = new BABYLON.Observable();
  18310. // Members
  18311. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18312. _this.instances = new Array();
  18313. _this._LODLevels = new Array();
  18314. _this._visibleInstances = {};
  18315. _this._renderIdForInstances = new Array();
  18316. _this._batchCache = new _InstancesBatch();
  18317. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18318. _this._sideOrientation = Mesh._DEFAULTSIDE;
  18319. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18320. // Will be used to save a source mesh reference, If any
  18321. _this._source = null;
  18322. if (source) {
  18323. // Source mesh
  18324. _this._source = source;
  18325. // Geometry
  18326. if (source._geometry) {
  18327. source._geometry.applyToMesh(_this);
  18328. }
  18329. // Deep copy
  18330. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  18331. // Parent
  18332. _this.parent = source.parent;
  18333. // Pivot
  18334. _this.setPivotMatrix(source.getPivotMatrix());
  18335. _this.id = name + "." + source.id;
  18336. // Material
  18337. _this.material = source.material;
  18338. var index;
  18339. if (!doNotCloneChildren) {
  18340. // Children
  18341. for (index = 0; index < scene.meshes.length; index++) {
  18342. var mesh = scene.meshes[index];
  18343. if (mesh.parent === source) {
  18344. // doNotCloneChildren is always going to be False
  18345. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  18346. }
  18347. }
  18348. }
  18349. // Physics clone
  18350. var physicsEngine = _this.getScene().getPhysicsEngine();
  18351. if (clonePhysicsImpostor && physicsEngine) {
  18352. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  18353. if (impostor) {
  18354. _this.physicsImpostor = impostor.clone(_this);
  18355. }
  18356. }
  18357. // Particles
  18358. for (index = 0; index < scene.particleSystems.length; index++) {
  18359. var system = scene.particleSystems[index];
  18360. if (system.emitter === source) {
  18361. system.clone(system.name, _this);
  18362. }
  18363. }
  18364. _this.computeWorldMatrix(true);
  18365. }
  18366. // Parent
  18367. if (parent !== null) {
  18368. _this.parent = parent;
  18369. }
  18370. return _this;
  18371. }
  18372. Object.defineProperty(Mesh, "FRONTSIDE", {
  18373. /**
  18374. * Mesh side orientation : usually the external or front surface
  18375. */
  18376. get: function () {
  18377. return Mesh._FRONTSIDE;
  18378. },
  18379. enumerable: true,
  18380. configurable: true
  18381. });
  18382. Object.defineProperty(Mesh, "BACKSIDE", {
  18383. /**
  18384. * Mesh side orientation : usually the internal or back surface
  18385. */
  18386. get: function () {
  18387. return Mesh._BACKSIDE;
  18388. },
  18389. enumerable: true,
  18390. configurable: true
  18391. });
  18392. Object.defineProperty(Mesh, "DOUBLESIDE", {
  18393. /**
  18394. * Mesh side orientation : both internal and external or front and back surfaces
  18395. */
  18396. get: function () {
  18397. return Mesh._DOUBLESIDE;
  18398. },
  18399. enumerable: true,
  18400. configurable: true
  18401. });
  18402. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  18403. /**
  18404. * Mesh side orientation : by default, `FRONTSIDE`
  18405. */
  18406. get: function () {
  18407. return Mesh._DEFAULTSIDE;
  18408. },
  18409. enumerable: true,
  18410. configurable: true
  18411. });
  18412. Object.defineProperty(Mesh, "NO_CAP", {
  18413. /**
  18414. * Mesh cap setting : no cap
  18415. */
  18416. get: function () {
  18417. return Mesh._NO_CAP;
  18418. },
  18419. enumerable: true,
  18420. configurable: true
  18421. });
  18422. Object.defineProperty(Mesh, "CAP_START", {
  18423. /**
  18424. * Mesh cap setting : one cap at the beginning of the mesh
  18425. */
  18426. get: function () {
  18427. return Mesh._CAP_START;
  18428. },
  18429. enumerable: true,
  18430. configurable: true
  18431. });
  18432. Object.defineProperty(Mesh, "CAP_END", {
  18433. /**
  18434. * Mesh cap setting : one cap at the end of the mesh
  18435. */
  18436. get: function () {
  18437. return Mesh._CAP_END;
  18438. },
  18439. enumerable: true,
  18440. configurable: true
  18441. });
  18442. Object.defineProperty(Mesh, "CAP_ALL", {
  18443. /**
  18444. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18445. */
  18446. get: function () {
  18447. return Mesh._CAP_ALL;
  18448. },
  18449. enumerable: true,
  18450. configurable: true
  18451. });
  18452. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18453. set: function (callback) {
  18454. if (this._onBeforeDrawObserver) {
  18455. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18456. }
  18457. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18458. },
  18459. enumerable: true,
  18460. configurable: true
  18461. });
  18462. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  18463. get: function () {
  18464. return this._morphTargetManager;
  18465. },
  18466. set: function (value) {
  18467. if (this._morphTargetManager === value) {
  18468. return;
  18469. }
  18470. this._morphTargetManager = value;
  18471. this._syncGeometryWithMorphTargetManager();
  18472. },
  18473. enumerable: true,
  18474. configurable: true
  18475. });
  18476. Object.defineProperty(Mesh.prototype, "source", {
  18477. get: function () {
  18478. return this._source;
  18479. },
  18480. enumerable: true,
  18481. configurable: true
  18482. });
  18483. // Methods
  18484. /**
  18485. * Returns the string "Mesh".
  18486. */
  18487. Mesh.prototype.getClassName = function () {
  18488. return "Mesh";
  18489. };
  18490. /**
  18491. * Returns a string.
  18492. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18493. */
  18494. Mesh.prototype.toString = function (fullDetails) {
  18495. var ret = _super.prototype.toString.call(this, fullDetails);
  18496. ret += ", n vertices: " + this.getTotalVertices();
  18497. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18498. if (this.animations) {
  18499. for (var i = 0; i < this.animations.length; i++) {
  18500. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18501. }
  18502. }
  18503. if (fullDetails) {
  18504. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18505. }
  18506. return ret;
  18507. };
  18508. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18509. /**
  18510. * True if the mesh has some Levels Of Details (LOD).
  18511. * Returns a boolean.
  18512. */
  18513. get: function () {
  18514. return this._LODLevels.length > 0;
  18515. },
  18516. enumerable: true,
  18517. configurable: true
  18518. });
  18519. Mesh.prototype._sortLODLevels = function () {
  18520. this._LODLevels.sort(function (a, b) {
  18521. if (a.distance < b.distance) {
  18522. return 1;
  18523. }
  18524. if (a.distance > b.distance) {
  18525. return -1;
  18526. }
  18527. return 0;
  18528. });
  18529. };
  18530. /**
  18531. * Add a mesh as LOD level triggered at the given distance.
  18532. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18533. * @param {number} distance The distance from the center of the object to show this level
  18534. * @param {Mesh} mesh The mesh to be added as LOD level
  18535. * @return {Mesh} This mesh (for chaining)
  18536. */
  18537. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18538. if (mesh && mesh._masterMesh) {
  18539. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18540. return this;
  18541. }
  18542. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18543. this._LODLevels.push(level);
  18544. if (mesh) {
  18545. mesh._masterMesh = this;
  18546. }
  18547. this._sortLODLevels();
  18548. return this;
  18549. };
  18550. /**
  18551. * Returns the LOD level mesh at the passed distance or null if not found.
  18552. * It is related to the method `addLODLevel(distance, mesh)`.
  18553. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18554. * Returns an object Mesh or `null`.
  18555. */
  18556. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18557. for (var index = 0; index < this._LODLevels.length; index++) {
  18558. var level = this._LODLevels[index];
  18559. if (level.distance === distance) {
  18560. return level.mesh;
  18561. }
  18562. }
  18563. return null;
  18564. };
  18565. /**
  18566. * Remove a mesh from the LOD array
  18567. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18568. * @param {Mesh} mesh The mesh to be removed.
  18569. * @return {Mesh} This mesh (for chaining)
  18570. */
  18571. Mesh.prototype.removeLODLevel = function (mesh) {
  18572. for (var index = 0; index < this._LODLevels.length; index++) {
  18573. if (this._LODLevels[index].mesh === mesh) {
  18574. this._LODLevels.splice(index, 1);
  18575. if (mesh) {
  18576. mesh._masterMesh = null;
  18577. }
  18578. }
  18579. }
  18580. this._sortLODLevels();
  18581. return this;
  18582. };
  18583. /**
  18584. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18585. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18586. */
  18587. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18588. if (!this._LODLevels || this._LODLevels.length === 0) {
  18589. return this;
  18590. }
  18591. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18592. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18593. if (this.onLODLevelSelection) {
  18594. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18595. }
  18596. return this;
  18597. }
  18598. for (var index = 0; index < this._LODLevels.length; index++) {
  18599. var level = this._LODLevels[index];
  18600. if (level.distance < distanceToCamera) {
  18601. if (level.mesh) {
  18602. level.mesh._preActivate();
  18603. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18604. }
  18605. if (this.onLODLevelSelection) {
  18606. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18607. }
  18608. return level.mesh;
  18609. }
  18610. }
  18611. if (this.onLODLevelSelection) {
  18612. this.onLODLevelSelection(distanceToCamera, this, this);
  18613. }
  18614. return this;
  18615. };
  18616. Object.defineProperty(Mesh.prototype, "geometry", {
  18617. /**
  18618. * Returns the mesh internal Geometry object.
  18619. */
  18620. get: function () {
  18621. return this._geometry;
  18622. },
  18623. enumerable: true,
  18624. configurable: true
  18625. });
  18626. /**
  18627. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18628. */
  18629. Mesh.prototype.getTotalVertices = function () {
  18630. if (!this._geometry) {
  18631. return 0;
  18632. }
  18633. return this._geometry.getTotalVertices();
  18634. };
  18635. /**
  18636. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18637. * 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.
  18638. * Returns null if the mesh has no geometry or no vertex buffer.
  18639. * Possible `kind` values :
  18640. * - BABYLON.VertexBuffer.PositionKind
  18641. * - BABYLON.VertexBuffer.UVKind
  18642. * - BABYLON.VertexBuffer.UV2Kind
  18643. * - BABYLON.VertexBuffer.UV3Kind
  18644. * - BABYLON.VertexBuffer.UV4Kind
  18645. * - BABYLON.VertexBuffer.UV5Kind
  18646. * - BABYLON.VertexBuffer.UV6Kind
  18647. * - BABYLON.VertexBuffer.ColorKind
  18648. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18649. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18650. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18651. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18652. */
  18653. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18654. if (!this._geometry) {
  18655. return null;
  18656. }
  18657. return this._geometry.getVerticesData(kind, copyWhenShared);
  18658. };
  18659. /**
  18660. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18661. * Returns `undefined` if the mesh has no geometry.
  18662. * Possible `kind` values :
  18663. * - BABYLON.VertexBuffer.PositionKind
  18664. * - BABYLON.VertexBuffer.UVKind
  18665. * - BABYLON.VertexBuffer.UV2Kind
  18666. * - BABYLON.VertexBuffer.UV3Kind
  18667. * - BABYLON.VertexBuffer.UV4Kind
  18668. * - BABYLON.VertexBuffer.UV5Kind
  18669. * - BABYLON.VertexBuffer.UV6Kind
  18670. * - BABYLON.VertexBuffer.ColorKind
  18671. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18672. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18673. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18674. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18675. */
  18676. Mesh.prototype.getVertexBuffer = function (kind) {
  18677. if (!this._geometry) {
  18678. return undefined;
  18679. }
  18680. return this._geometry.getVertexBuffer(kind);
  18681. };
  18682. /**
  18683. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18684. * Possible `kind` values :
  18685. * - BABYLON.VertexBuffer.PositionKind
  18686. * - BABYLON.VertexBuffer.UVKind
  18687. * - BABYLON.VertexBuffer.UV2Kind
  18688. * - BABYLON.VertexBuffer.UV3Kind
  18689. * - BABYLON.VertexBuffer.UV4Kind
  18690. * - BABYLON.VertexBuffer.UV5Kind
  18691. * - BABYLON.VertexBuffer.UV6Kind
  18692. * - BABYLON.VertexBuffer.ColorKind
  18693. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18694. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18695. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18696. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18697. */
  18698. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18699. if (!this._geometry) {
  18700. if (this._delayInfo) {
  18701. return this._delayInfo.indexOf(kind) !== -1;
  18702. }
  18703. return false;
  18704. }
  18705. return this._geometry.isVerticesDataPresent(kind);
  18706. };
  18707. /**
  18708. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18709. * Possible `kind` values :
  18710. * - BABYLON.VertexBuffer.PositionKind
  18711. * - BABYLON.VertexBuffer.UVKind
  18712. * - BABYLON.VertexBuffer.UV2Kind
  18713. * - BABYLON.VertexBuffer.UV3Kind
  18714. * - BABYLON.VertexBuffer.UV4Kind
  18715. * - BABYLON.VertexBuffer.UV5Kind
  18716. * - BABYLON.VertexBuffer.UV6Kind
  18717. * - BABYLON.VertexBuffer.ColorKind
  18718. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18719. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18720. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18721. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18722. */
  18723. Mesh.prototype.getVerticesDataKinds = function () {
  18724. if (!this._geometry) {
  18725. var result = [];
  18726. if (this._delayInfo) {
  18727. this._delayInfo.forEach(function (kind, index, array) {
  18728. result.push(kind);
  18729. });
  18730. }
  18731. return result;
  18732. }
  18733. return this._geometry.getVerticesDataKinds();
  18734. };
  18735. /**
  18736. * Returns a positive integer : the total number of indices in this mesh geometry.
  18737. * Returns zero if the mesh has no geometry.
  18738. */
  18739. Mesh.prototype.getTotalIndices = function () {
  18740. if (!this._geometry) {
  18741. return 0;
  18742. }
  18743. return this._geometry.getTotalIndices();
  18744. };
  18745. /**
  18746. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  18747. * 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.
  18748. * Returns an empty array if the mesh has no geometry.
  18749. */
  18750. Mesh.prototype.getIndices = function (copyWhenShared) {
  18751. if (!this._geometry) {
  18752. return [];
  18753. }
  18754. return this._geometry.getIndices(copyWhenShared);
  18755. };
  18756. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18757. get: function () {
  18758. return this._masterMesh !== null && this._masterMesh !== undefined;
  18759. },
  18760. enumerable: true,
  18761. configurable: true
  18762. });
  18763. /**
  18764. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18765. */
  18766. Mesh.prototype.isReady = function () {
  18767. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18768. return false;
  18769. }
  18770. return _super.prototype.isReady.call(this);
  18771. };
  18772. /**
  18773. * Boolean : true if the mesh has been disposed.
  18774. */
  18775. Mesh.prototype.isDisposed = function () {
  18776. return this._isDisposed;
  18777. };
  18778. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  18779. get: function () {
  18780. return this._sideOrientation;
  18781. },
  18782. /**
  18783. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  18784. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  18785. */
  18786. set: function (sideO) {
  18787. this._sideOrientation = sideO;
  18788. },
  18789. enumerable: true,
  18790. configurable: true
  18791. });
  18792. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  18793. /**
  18794. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  18795. * This property is pertinent only for updatable parametric shapes.
  18796. */
  18797. get: function () {
  18798. return this._areNormalsFrozen;
  18799. },
  18800. enumerable: true,
  18801. configurable: true
  18802. });
  18803. /**
  18804. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18805. * It has no effect at all on other shapes.
  18806. * It prevents the mesh normals from being recomputed on next `positions` array update.
  18807. * Returns the Mesh.
  18808. */
  18809. Mesh.prototype.freezeNormals = function () {
  18810. this._areNormalsFrozen = true;
  18811. return this;
  18812. };
  18813. /**
  18814. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18815. * It has no effect at all on other shapes.
  18816. * It reactivates the mesh normals computation if it was previously frozen.
  18817. * Returns the Mesh.
  18818. */
  18819. Mesh.prototype.unfreezeNormals = function () {
  18820. this._areNormalsFrozen = false;
  18821. return this;
  18822. };
  18823. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  18824. /**
  18825. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  18826. */
  18827. set: function (count) {
  18828. this._overridenInstanceCount = count;
  18829. },
  18830. enumerable: true,
  18831. configurable: true
  18832. });
  18833. // Methods
  18834. Mesh.prototype._preActivate = function () {
  18835. var sceneRenderId = this.getScene().getRenderId();
  18836. if (this._preActivateId === sceneRenderId) {
  18837. return this;
  18838. }
  18839. this._preActivateId = sceneRenderId;
  18840. this._visibleInstances = null;
  18841. return this;
  18842. };
  18843. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18844. if (this._visibleInstances) {
  18845. this._visibleInstances.intermediateDefaultRenderId = renderId;
  18846. }
  18847. return this;
  18848. };
  18849. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  18850. if (!this._visibleInstances) {
  18851. this._visibleInstances = {};
  18852. this._visibleInstances.defaultRenderId = renderId;
  18853. this._visibleInstances.selfDefaultRenderId = this._renderId;
  18854. }
  18855. if (!this._visibleInstances[renderId]) {
  18856. this._visibleInstances[renderId] = new Array();
  18857. }
  18858. this._visibleInstances[renderId].push(instance);
  18859. return this;
  18860. };
  18861. /**
  18862. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  18863. * This means the mesh underlying bounding box and sphere are recomputed.
  18864. * Returns the Mesh.
  18865. */
  18866. Mesh.prototype.refreshBoundingInfo = function () {
  18867. if (this._boundingInfo.isLocked) {
  18868. return;
  18869. }
  18870. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18871. if (data) {
  18872. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  18873. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18874. }
  18875. if (this.subMeshes) {
  18876. for (var index = 0; index < this.subMeshes.length; index++) {
  18877. this.subMeshes[index].refreshBoundingInfo();
  18878. }
  18879. }
  18880. this._updateBoundingInfo();
  18881. return this;
  18882. };
  18883. Mesh.prototype._createGlobalSubMesh = function () {
  18884. var totalVertices = this.getTotalVertices();
  18885. if (!totalVertices || !this.getIndices()) {
  18886. return null;
  18887. }
  18888. this.releaseSubMeshes();
  18889. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  18890. };
  18891. Mesh.prototype.subdivide = function (count) {
  18892. if (count < 1) {
  18893. return;
  18894. }
  18895. var totalIndices = this.getTotalIndices();
  18896. var subdivisionSize = (totalIndices / count) | 0;
  18897. var offset = 0;
  18898. // Ensure that subdivisionSize is a multiple of 3
  18899. while (subdivisionSize % 3 !== 0) {
  18900. subdivisionSize++;
  18901. }
  18902. this.releaseSubMeshes();
  18903. for (var index = 0; index < count; index++) {
  18904. if (offset >= totalIndices) {
  18905. break;
  18906. }
  18907. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  18908. offset += subdivisionSize;
  18909. }
  18910. this.synchronizeInstances();
  18911. };
  18912. /**
  18913. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18914. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18915. * The `data` are either a numeric array either a Float32Array.
  18916. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18917. * 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).
  18918. * Note that a new underlying VertexBuffer object is created each call.
  18919. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18920. *
  18921. * Possible `kind` values :
  18922. * - BABYLON.VertexBuffer.PositionKind
  18923. * - BABYLON.VertexBuffer.UVKind
  18924. * - BABYLON.VertexBuffer.UV2Kind
  18925. * - BABYLON.VertexBuffer.UV3Kind
  18926. * - BABYLON.VertexBuffer.UV4Kind
  18927. * - BABYLON.VertexBuffer.UV5Kind
  18928. * - BABYLON.VertexBuffer.UV6Kind
  18929. * - BABYLON.VertexBuffer.ColorKind
  18930. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18931. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18932. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18933. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18934. *
  18935. * Returns the Mesh.
  18936. */
  18937. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18938. if (!this._geometry) {
  18939. var vertexData = new BABYLON.VertexData();
  18940. vertexData.set(data, kind);
  18941. var scene = this.getScene();
  18942. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  18943. }
  18944. else {
  18945. this._geometry.setVerticesData(kind, data, updatable, stride);
  18946. }
  18947. return this;
  18948. };
  18949. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  18950. if (updatable === void 0) { updatable = true; }
  18951. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  18952. return;
  18953. }
  18954. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  18955. };
  18956. /**
  18957. * Sets the mesh VertexBuffer.
  18958. * Returns the Mesh.
  18959. */
  18960. Mesh.prototype.setVerticesBuffer = function (buffer) {
  18961. if (!this._geometry) {
  18962. var scene = this.getScene();
  18963. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  18964. }
  18965. this._geometry.setVerticesBuffer(buffer);
  18966. return this;
  18967. };
  18968. /**
  18969. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18970. * If the mesh has no geometry, it is simply returned as it is.
  18971. * The `data` are either a numeric array either a Float32Array.
  18972. * No new underlying VertexBuffer object is created.
  18973. * 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.
  18974. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18975. *
  18976. * Possible `kind` values :
  18977. * - BABYLON.VertexBuffer.PositionKind
  18978. * - BABYLON.VertexBuffer.UVKind
  18979. * - BABYLON.VertexBuffer.UV2Kind
  18980. * - BABYLON.VertexBuffer.UV3Kind
  18981. * - BABYLON.VertexBuffer.UV4Kind
  18982. * - BABYLON.VertexBuffer.UV5Kind
  18983. * - BABYLON.VertexBuffer.UV6Kind
  18984. * - BABYLON.VertexBuffer.ColorKind
  18985. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18986. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18987. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18988. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18989. *
  18990. * Returns the Mesh.
  18991. */
  18992. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18993. if (!this._geometry) {
  18994. return;
  18995. }
  18996. if (!makeItUnique) {
  18997. this._geometry.updateVerticesData(kind, data, updateExtends);
  18998. }
  18999. else {
  19000. this.makeGeometryUnique();
  19001. this.updateVerticesData(kind, data, updateExtends, false);
  19002. }
  19003. return this;
  19004. };
  19005. /**
  19006. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19007. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19008. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19009. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19010. * Returns the Mesh.
  19011. */
  19012. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19013. if (computeNormals === void 0) { computeNormals = true; }
  19014. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19015. positionFunction(positions);
  19016. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19017. if (computeNormals) {
  19018. var indices = this.getIndices();
  19019. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19020. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19021. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19022. }
  19023. return this;
  19024. };
  19025. /**
  19026. * Creates a un-shared specific occurence of the geometry for the mesh.
  19027. * Returns the Mesh.
  19028. */
  19029. Mesh.prototype.makeGeometryUnique = function () {
  19030. if (!this._geometry) {
  19031. return;
  19032. }
  19033. var oldGeometry = this._geometry;
  19034. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19035. oldGeometry.releaseForMesh(this, true);
  19036. geometry.applyToMesh(this);
  19037. return this;
  19038. };
  19039. /**
  19040. * Sets the mesh indices.
  19041. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19042. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19043. * This method creates a new index buffer each call.
  19044. * Returns the Mesh.
  19045. */
  19046. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19047. if (!this._geometry) {
  19048. var vertexData = new BABYLON.VertexData();
  19049. vertexData.indices = indices;
  19050. var scene = this.getScene();
  19051. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19052. }
  19053. else {
  19054. this._geometry.setIndices(indices, totalVertices);
  19055. }
  19056. return this;
  19057. };
  19058. /**
  19059. * Invert the geometry to move from a right handed system to a left handed one.
  19060. * Returns the Mesh.
  19061. */
  19062. Mesh.prototype.toLeftHanded = function () {
  19063. if (!this._geometry) {
  19064. return;
  19065. }
  19066. this._geometry.toLeftHanded();
  19067. return this;
  19068. };
  19069. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19070. var engine = this.getScene().getEngine();
  19071. // Wireframe
  19072. var indexToBind;
  19073. if (this._unIndexed) {
  19074. indexToBind = null;
  19075. }
  19076. else {
  19077. switch (fillMode) {
  19078. case BABYLON.Material.PointFillMode:
  19079. indexToBind = null;
  19080. break;
  19081. case BABYLON.Material.WireFrameFillMode:
  19082. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19083. break;
  19084. default:
  19085. case BABYLON.Material.TriangleFillMode:
  19086. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19087. break;
  19088. }
  19089. }
  19090. // VBOs
  19091. this._geometry._bind(effect, indexToBind);
  19092. return this;
  19093. };
  19094. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19095. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19096. return this;
  19097. }
  19098. this.onBeforeDrawObservable.notifyObservers(this);
  19099. var engine = this.getScene().getEngine();
  19100. // Draw order
  19101. switch (fillMode) {
  19102. case BABYLON.Material.PointFillMode:
  19103. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19104. break;
  19105. case BABYLON.Material.WireFrameFillMode:
  19106. if (this._unIndexed) {
  19107. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19108. }
  19109. else {
  19110. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19111. }
  19112. break;
  19113. default:
  19114. if (this._unIndexed) {
  19115. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19116. }
  19117. else {
  19118. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19119. }
  19120. }
  19121. return this;
  19122. };
  19123. /**
  19124. * Registers for this mesh a javascript function called just before the rendering process.
  19125. * This function is passed the current mesh.
  19126. * Return the Mesh.
  19127. */
  19128. Mesh.prototype.registerBeforeRender = function (func) {
  19129. this.onBeforeRenderObservable.add(func);
  19130. return this;
  19131. };
  19132. /**
  19133. * Disposes a previously registered javascript function called before the rendering.
  19134. * This function is passed the current mesh.
  19135. * Returns the Mesh.
  19136. */
  19137. Mesh.prototype.unregisterBeforeRender = function (func) {
  19138. this.onBeforeRenderObservable.removeCallback(func);
  19139. return this;
  19140. };
  19141. /**
  19142. * Registers for this mesh a javascript function called just after the rendering is complete.
  19143. * This function is passed the current mesh.
  19144. * Returns the Mesh.
  19145. */
  19146. Mesh.prototype.registerAfterRender = function (func) {
  19147. this.onAfterRenderObservable.add(func);
  19148. return this;
  19149. };
  19150. /**
  19151. * Disposes a previously registered javascript function called after the rendering.
  19152. * This function is passed the current mesh.
  19153. * Return the Mesh.
  19154. */
  19155. Mesh.prototype.unregisterAfterRender = function (func) {
  19156. this.onAfterRenderObservable.removeCallback(func);
  19157. return this;
  19158. };
  19159. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19160. var scene = this.getScene();
  19161. this._batchCache.mustReturn = false;
  19162. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19163. this._batchCache.visibleInstances[subMeshId] = null;
  19164. if (this._visibleInstances) {
  19165. var currentRenderId = scene.getRenderId();
  19166. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19167. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19168. var selfRenderId = this._renderId;
  19169. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19170. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19171. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19172. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19173. }
  19174. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19175. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19176. this._batchCache.mustReturn = true;
  19177. return this._batchCache;
  19178. }
  19179. if (currentRenderId !== selfRenderId) {
  19180. this._batchCache.renderSelf[subMeshId] = false;
  19181. }
  19182. }
  19183. this._renderIdForInstances[subMeshId] = currentRenderId;
  19184. }
  19185. return this._batchCache;
  19186. };
  19187. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19188. var visibleInstances = batch.visibleInstances[subMesh._id];
  19189. var matricesCount = visibleInstances.length + 1;
  19190. var bufferSize = matricesCount * 16 * 4;
  19191. var currentInstancesBufferSize = this._instancesBufferSize;
  19192. var instancesBuffer = this._instancesBuffer;
  19193. while (this._instancesBufferSize < bufferSize) {
  19194. this._instancesBufferSize *= 2;
  19195. }
  19196. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19197. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19198. }
  19199. var offset = 0;
  19200. var instancesCount = 0;
  19201. var world = this.getWorldMatrix();
  19202. if (batch.renderSelf[subMesh._id]) {
  19203. world.copyToArray(this._instancesData, offset);
  19204. offset += 16;
  19205. instancesCount++;
  19206. }
  19207. if (visibleInstances) {
  19208. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19209. var instance = visibleInstances[instanceIndex];
  19210. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19211. offset += 16;
  19212. instancesCount++;
  19213. }
  19214. }
  19215. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19216. if (instancesBuffer) {
  19217. instancesBuffer.dispose();
  19218. }
  19219. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19220. this._instancesBuffer = instancesBuffer;
  19221. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19222. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19223. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19224. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19225. }
  19226. else {
  19227. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19228. }
  19229. this.geometry._bind(effect);
  19230. this._draw(subMesh, fillMode, instancesCount);
  19231. engine.unbindInstanceAttributes();
  19232. return this;
  19233. };
  19234. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19235. var scene = this.getScene();
  19236. var engine = scene.getEngine();
  19237. if (hardwareInstancedRendering) {
  19238. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19239. }
  19240. else {
  19241. if (batch.renderSelf[subMesh._id]) {
  19242. // Draw
  19243. if (onBeforeDraw) {
  19244. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19245. }
  19246. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19247. }
  19248. if (batch.visibleInstances[subMesh._id]) {
  19249. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19250. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19251. // World
  19252. var world = instance.getWorldMatrix();
  19253. if (onBeforeDraw) {
  19254. onBeforeDraw(true, world, effectiveMaterial);
  19255. }
  19256. // Draw
  19257. this._draw(subMesh, fillMode);
  19258. }
  19259. }
  19260. }
  19261. return this;
  19262. };
  19263. /**
  19264. * Triggers the draw call for the mesh.
  19265. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19266. * Returns the Mesh.
  19267. */
  19268. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19269. var scene = this.getScene();
  19270. // Managing instances
  19271. var batch = this._getInstancesRenderList(subMesh._id);
  19272. if (batch.mustReturn) {
  19273. return this;
  19274. }
  19275. // Checking geometry state
  19276. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19277. return this;
  19278. }
  19279. var callbackIndex;
  19280. this.onBeforeRenderObservable.notifyObservers(this);
  19281. var engine = scene.getEngine();
  19282. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19283. // Material
  19284. var effectiveMaterial = subMesh.getMaterial();
  19285. if (!effectiveMaterial) {
  19286. return this;
  19287. }
  19288. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19289. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  19290. return this;
  19291. }
  19292. }
  19293. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19294. return this;
  19295. }
  19296. // Outline - step 1
  19297. var savedDepthWrite = engine.getDepthWrite();
  19298. if (this.renderOutline) {
  19299. engine.setDepthWrite(false);
  19300. scene.getOutlineRenderer().render(subMesh, batch);
  19301. engine.setDepthWrite(savedDepthWrite);
  19302. }
  19303. var effect;
  19304. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19305. effect = subMesh.effect;
  19306. }
  19307. else {
  19308. effect = effectiveMaterial.getEffect();
  19309. }
  19310. effectiveMaterial._preBind(effect);
  19311. // Bind
  19312. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19313. this._bind(subMesh, effect, fillMode);
  19314. var world = this.getWorldMatrix();
  19315. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19316. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  19317. }
  19318. else {
  19319. effectiveMaterial.bind(world, this);
  19320. }
  19321. // Alpha mode
  19322. if (enableAlphaMode) {
  19323. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19324. }
  19325. // Draw
  19326. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  19327. // Unbind
  19328. effectiveMaterial.unbind();
  19329. // Outline - step 2
  19330. if (this.renderOutline && savedDepthWrite) {
  19331. engine.setDepthWrite(true);
  19332. engine.setColorWrite(false);
  19333. scene.getOutlineRenderer().render(subMesh, batch);
  19334. engine.setColorWrite(true);
  19335. }
  19336. // Overlay
  19337. if (this.renderOverlay) {
  19338. var currentMode = engine.getAlphaMode();
  19339. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19340. scene.getOutlineRenderer().render(subMesh, batch, true);
  19341. engine.setAlphaMode(currentMode);
  19342. }
  19343. this.onAfterRenderObservable.notifyObservers(this);
  19344. return this;
  19345. };
  19346. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19347. if (isInstance) {
  19348. effectiveMaterial.bindOnlyWorldMatrix(world);
  19349. }
  19350. return this;
  19351. };
  19352. /**
  19353. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19354. */
  19355. Mesh.prototype.getEmittedParticleSystems = function () {
  19356. var results = new Array();
  19357. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19358. var particleSystem = this.getScene().particleSystems[index];
  19359. if (particleSystem.emitter === this) {
  19360. results.push(particleSystem);
  19361. }
  19362. }
  19363. return results;
  19364. };
  19365. /**
  19366. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19367. */
  19368. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19369. var results = new Array();
  19370. var descendants = this.getDescendants();
  19371. descendants.push(this);
  19372. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19373. var particleSystem = this.getScene().particleSystems[index];
  19374. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19375. results.push(particleSystem);
  19376. }
  19377. }
  19378. return results;
  19379. };
  19380. Mesh.prototype._checkDelayState = function () {
  19381. var scene = this.getScene();
  19382. if (this._geometry) {
  19383. this._geometry.load(scene);
  19384. }
  19385. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19386. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19387. this._queueLoad(this, scene);
  19388. }
  19389. return this;
  19390. };
  19391. Mesh.prototype._queueLoad = function (mesh, scene) {
  19392. var _this = this;
  19393. scene._addPendingData(mesh);
  19394. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19395. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19396. if (data instanceof ArrayBuffer) {
  19397. _this._delayLoadingFunction(data, _this);
  19398. }
  19399. else {
  19400. _this._delayLoadingFunction(JSON.parse(data), _this);
  19401. }
  19402. _this.instances.forEach(function (instance) {
  19403. instance._syncSubMeshes();
  19404. });
  19405. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19406. scene._removePendingData(_this);
  19407. }, function () { }, scene.database, getBinaryData);
  19408. return this;
  19409. };
  19410. /**
  19411. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19412. */
  19413. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19414. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19415. return false;
  19416. }
  19417. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19418. return false;
  19419. }
  19420. this._checkDelayState();
  19421. return true;
  19422. };
  19423. /**
  19424. * Sets the mesh material by the material or multiMaterial `id` property.
  19425. * The material `id` is a string identifying the material or the multiMaterial.
  19426. * This method returns the Mesh.
  19427. */
  19428. Mesh.prototype.setMaterialByID = function (id) {
  19429. var materials = this.getScene().materials;
  19430. var index;
  19431. for (index = 0; index < materials.length; index++) {
  19432. if (materials[index].id === id) {
  19433. this.material = materials[index];
  19434. return this;
  19435. }
  19436. }
  19437. // Multi
  19438. var multiMaterials = this.getScene().multiMaterials;
  19439. for (index = 0; index < multiMaterials.length; index++) {
  19440. if (multiMaterials[index].id === id) {
  19441. this.material = multiMaterials[index];
  19442. return this;
  19443. }
  19444. }
  19445. return this;
  19446. };
  19447. /**
  19448. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  19449. */
  19450. Mesh.prototype.getAnimatables = function () {
  19451. var results = [];
  19452. if (this.material) {
  19453. results.push(this.material);
  19454. }
  19455. if (this.skeleton) {
  19456. results.push(this.skeleton);
  19457. }
  19458. return results;
  19459. };
  19460. /**
  19461. * Modifies the mesh geometry according to the passed transformation matrix.
  19462. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  19463. * The mesh normals are modified accordingly the same transformation.
  19464. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19465. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19466. * Returns the Mesh.
  19467. */
  19468. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  19469. // Position
  19470. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19471. return this;
  19472. }
  19473. var submeshes = this.subMeshes.splice(0);
  19474. this._resetPointsArrayCache();
  19475. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19476. var temp = [];
  19477. var index;
  19478. for (index = 0; index < data.length; index += 3) {
  19479. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  19480. }
  19481. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  19482. // Normals
  19483. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19484. return this;
  19485. }
  19486. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19487. temp = [];
  19488. for (index = 0; index < data.length; index += 3) {
  19489. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  19490. }
  19491. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  19492. // flip faces?
  19493. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  19494. this.flipFaces();
  19495. }
  19496. // Restore submeshes
  19497. this.releaseSubMeshes();
  19498. this.subMeshes = submeshes;
  19499. return this;
  19500. };
  19501. /**
  19502. * Modifies the mesh geometry according to its own current World Matrix.
  19503. * The mesh World Matrix is then reset.
  19504. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  19505. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19506. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19507. * Returns the Mesh.
  19508. */
  19509. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  19510. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  19511. this.scaling.copyFromFloats(1, 1, 1);
  19512. this.position.copyFromFloats(0, 0, 0);
  19513. this.rotation.copyFromFloats(0, 0, 0);
  19514. //only if quaternion is already set
  19515. if (this.rotationQuaternion) {
  19516. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  19517. }
  19518. this._worldMatrix = BABYLON.Matrix.Identity();
  19519. return this;
  19520. };
  19521. // Cache
  19522. Mesh.prototype._resetPointsArrayCache = function () {
  19523. this._positions = null;
  19524. return this;
  19525. };
  19526. Mesh.prototype._generatePointsArray = function () {
  19527. if (this._positions)
  19528. return true;
  19529. this._positions = [];
  19530. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19531. if (!data) {
  19532. return false;
  19533. }
  19534. for (var index = 0; index < data.length; index += 3) {
  19535. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  19536. }
  19537. return true;
  19538. };
  19539. /**
  19540. * Returns a new Mesh object generated from the current mesh properties.
  19541. * This method must not get confused with createInstance().
  19542. * The parameter `name` is a string, the name given to the new mesh.
  19543. * The optional parameter `newParent` can be any Node object (default `null`).
  19544. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19545. * 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.
  19546. */
  19547. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19548. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19549. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19550. };
  19551. /**
  19552. * Disposes the mesh.
  19553. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19554. */
  19555. Mesh.prototype.dispose = function (doNotRecurse) {
  19556. var _this = this;
  19557. this.morphTargetManager = undefined;
  19558. if (this._geometry) {
  19559. this._geometry.releaseForMesh(this, true);
  19560. }
  19561. // Sources
  19562. var meshes = this.getScene().meshes;
  19563. meshes.forEach(function (mesh) {
  19564. if (mesh._source && mesh._source === _this) {
  19565. mesh._source = null;
  19566. }
  19567. });
  19568. this._source = null;
  19569. // Instances
  19570. if (this._instancesBuffer) {
  19571. this._instancesBuffer.dispose();
  19572. this._instancesBuffer = null;
  19573. }
  19574. while (this.instances.length) {
  19575. this.instances[0].dispose();
  19576. }
  19577. // Highlight layers.
  19578. var highlightLayers = this.getScene().highlightLayers;
  19579. for (var i = 0; i < highlightLayers.length; i++) {
  19580. var highlightLayer = highlightLayers[i];
  19581. if (highlightLayer) {
  19582. highlightLayer.removeMesh(this);
  19583. highlightLayer.removeExcludedMesh(this);
  19584. }
  19585. }
  19586. _super.prototype.dispose.call(this, doNotRecurse);
  19587. };
  19588. /**
  19589. * Modifies the mesh geometry according to a displacement map.
  19590. * 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.
  19591. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19592. * This method returns nothing.
  19593. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19594. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19595. * 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.
  19596. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  19597. * The parameter `uvScale` is an optional vector2 used to scale UV.
  19598. *
  19599. * Returns the Mesh.
  19600. */
  19601. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  19602. var _this = this;
  19603. var scene = this.getScene();
  19604. var onload = function (img) {
  19605. // Getting height map data
  19606. var canvas = document.createElement("canvas");
  19607. var context = canvas.getContext("2d");
  19608. var heightMapWidth = img.width;
  19609. var heightMapHeight = img.height;
  19610. canvas.width = heightMapWidth;
  19611. canvas.height = heightMapHeight;
  19612. context.drawImage(img, 0, 0);
  19613. // Create VertexData from map data
  19614. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19615. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19616. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  19617. //execute success callback, if set
  19618. if (onSuccess) {
  19619. onSuccess(_this);
  19620. }
  19621. };
  19622. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19623. return this;
  19624. };
  19625. /**
  19626. * Modifies the mesh geometry according to a displacementMap buffer.
  19627. * 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.
  19628. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19629. * This method returns nothing.
  19630. * 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.
  19631. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19632. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19633. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  19634. * The parameter `uvScale` is an optional vector2 used to scale UV.
  19635. *
  19636. * Returns the Mesh.
  19637. */
  19638. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  19639. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19640. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19641. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19642. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19643. return this;
  19644. }
  19645. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19646. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19647. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19648. var position = BABYLON.Vector3.Zero();
  19649. var normal = BABYLON.Vector3.Zero();
  19650. var uv = BABYLON.Vector2.Zero();
  19651. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  19652. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  19653. for (var index = 0; index < positions.length; index += 3) {
  19654. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19655. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19656. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19657. // Compute height
  19658. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  19659. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  19660. var pos = (u + v * heightMapWidth) * 4;
  19661. var r = buffer[pos] / 255.0;
  19662. var g = buffer[pos + 1] / 255.0;
  19663. var b = buffer[pos + 2] / 255.0;
  19664. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19665. normal.normalize();
  19666. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19667. position = position.add(normal);
  19668. position.toArray(positions, index);
  19669. }
  19670. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19671. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19672. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19673. return this;
  19674. };
  19675. /**
  19676. * Modify the mesh to get a flat shading rendering.
  19677. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19678. * This method returns the Mesh.
  19679. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19680. */
  19681. Mesh.prototype.convertToFlatShadedMesh = function () {
  19682. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19683. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19684. var kinds = this.getVerticesDataKinds();
  19685. var vbs = [];
  19686. var data = [];
  19687. var newdata = [];
  19688. var updatableNormals = false;
  19689. var kindIndex;
  19690. var kind;
  19691. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19692. kind = kinds[kindIndex];
  19693. var vertexBuffer = this.getVertexBuffer(kind);
  19694. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19695. updatableNormals = vertexBuffer.isUpdatable();
  19696. kinds.splice(kindIndex, 1);
  19697. kindIndex--;
  19698. continue;
  19699. }
  19700. vbs[kind] = vertexBuffer;
  19701. data[kind] = vbs[kind].getData();
  19702. newdata[kind] = [];
  19703. }
  19704. // Save previous submeshes
  19705. var previousSubmeshes = this.subMeshes.slice(0);
  19706. var indices = this.getIndices();
  19707. var totalIndices = this.getTotalIndices();
  19708. // Generating unique vertices per face
  19709. var index;
  19710. for (index = 0; index < totalIndices; index++) {
  19711. var vertexIndex = indices[index];
  19712. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19713. kind = kinds[kindIndex];
  19714. var stride = vbs[kind].getStrideSize();
  19715. for (var offset = 0; offset < stride; offset++) {
  19716. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19717. }
  19718. }
  19719. }
  19720. // Updating faces & normal
  19721. var normals = [];
  19722. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19723. for (index = 0; index < totalIndices; index += 3) {
  19724. indices[index] = index;
  19725. indices[index + 1] = index + 1;
  19726. indices[index + 2] = index + 2;
  19727. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19728. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19729. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19730. var p1p2 = p1.subtract(p2);
  19731. var p3p2 = p3.subtract(p2);
  19732. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19733. // Store same normals for every vertex
  19734. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19735. normals.push(normal.x);
  19736. normals.push(normal.y);
  19737. normals.push(normal.z);
  19738. }
  19739. }
  19740. this.setIndices(indices);
  19741. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19742. // Updating vertex buffers
  19743. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19744. kind = kinds[kindIndex];
  19745. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19746. }
  19747. // Updating submeshes
  19748. this.releaseSubMeshes();
  19749. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19750. var previousOne = previousSubmeshes[submeshIndex];
  19751. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19752. }
  19753. this.synchronizeInstances();
  19754. return this;
  19755. };
  19756. /**
  19757. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19758. * In other words, more vertices, no more indices and a single bigger VBO.
  19759. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19760. * Returns the Mesh.
  19761. */
  19762. Mesh.prototype.convertToUnIndexedMesh = function () {
  19763. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19764. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19765. var kinds = this.getVerticesDataKinds();
  19766. var vbs = [];
  19767. var data = [];
  19768. var newdata = [];
  19769. var updatableNormals = false;
  19770. var kindIndex;
  19771. var kind;
  19772. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19773. kind = kinds[kindIndex];
  19774. var vertexBuffer = this.getVertexBuffer(kind);
  19775. vbs[kind] = vertexBuffer;
  19776. data[kind] = vbs[kind].getData();
  19777. newdata[kind] = [];
  19778. }
  19779. // Save previous submeshes
  19780. var previousSubmeshes = this.subMeshes.slice(0);
  19781. var indices = this.getIndices();
  19782. var totalIndices = this.getTotalIndices();
  19783. // Generating unique vertices per face
  19784. var index;
  19785. for (index = 0; index < totalIndices; index++) {
  19786. var vertexIndex = indices[index];
  19787. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19788. kind = kinds[kindIndex];
  19789. var stride = vbs[kind].getStrideSize();
  19790. for (var offset = 0; offset < stride; offset++) {
  19791. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19792. }
  19793. }
  19794. }
  19795. // Updating indices
  19796. for (index = 0; index < totalIndices; index += 3) {
  19797. indices[index] = index;
  19798. indices[index + 1] = index + 1;
  19799. indices[index + 2] = index + 2;
  19800. }
  19801. this.setIndices(indices);
  19802. // Updating vertex buffers
  19803. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19804. kind = kinds[kindIndex];
  19805. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19806. }
  19807. // Updating submeshes
  19808. this.releaseSubMeshes();
  19809. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19810. var previousOne = previousSubmeshes[submeshIndex];
  19811. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19812. }
  19813. this._unIndexed = true;
  19814. this.synchronizeInstances();
  19815. return this;
  19816. };
  19817. /**
  19818. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  19819. * This method returns the Mesh.
  19820. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  19821. */
  19822. Mesh.prototype.flipFaces = function (flipNormals) {
  19823. if (flipNormals === void 0) { flipNormals = false; }
  19824. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  19825. var i;
  19826. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19827. for (i = 0; i < vertex_data.normals.length; i++) {
  19828. vertex_data.normals[i] *= -1;
  19829. }
  19830. }
  19831. var temp;
  19832. for (i = 0; i < vertex_data.indices.length; i += 3) {
  19833. // reassign indices
  19834. temp = vertex_data.indices[i + 1];
  19835. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  19836. vertex_data.indices[i + 2] = temp;
  19837. }
  19838. vertex_data.applyToMesh(this);
  19839. return this;
  19840. };
  19841. // Instances
  19842. /**
  19843. * Creates a new InstancedMesh object from the mesh model.
  19844. * An instance shares the same properties and the same material than its model.
  19845. * Only these properties of each instance can then be set individually :
  19846. * - position
  19847. * - rotation
  19848. * - rotationQuaternion
  19849. * - setPivotMatrix
  19850. * - scaling
  19851. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  19852. * Warning : this method is not supported for Line mesh and LineSystem
  19853. */
  19854. Mesh.prototype.createInstance = function (name) {
  19855. return new BABYLON.InstancedMesh(name, this);
  19856. };
  19857. /**
  19858. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  19859. * After this call, all the mesh instances have the same submeshes than the current mesh.
  19860. * This method returns the Mesh.
  19861. */
  19862. Mesh.prototype.synchronizeInstances = function () {
  19863. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  19864. var instance = this.instances[instanceIndex];
  19865. instance._syncSubMeshes();
  19866. }
  19867. return this;
  19868. };
  19869. /**
  19870. * Simplify the mesh according to the given array of settings.
  19871. * Function will return immediately and will simplify async. It returns the Mesh.
  19872. * @param settings a collection of simplification settings.
  19873. * @param parallelProcessing should all levels calculate parallel or one after the other.
  19874. * @param type the type of simplification to run.
  19875. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  19876. */
  19877. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  19878. if (parallelProcessing === void 0) { parallelProcessing = true; }
  19879. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  19880. this.getScene().simplificationQueue.addTask({
  19881. settings: settings,
  19882. parallelProcessing: parallelProcessing,
  19883. mesh: this,
  19884. simplificationType: simplificationType,
  19885. successCallback: successCallback
  19886. });
  19887. return this;
  19888. };
  19889. /**
  19890. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  19891. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  19892. * This should be used together with the simplification to avoid disappearing triangles.
  19893. * Returns the Mesh.
  19894. * @param successCallback an optional success callback to be called after the optimization finished.
  19895. */
  19896. Mesh.prototype.optimizeIndices = function (successCallback) {
  19897. var _this = this;
  19898. var indices = this.getIndices();
  19899. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19900. var vectorPositions = [];
  19901. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  19902. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  19903. }
  19904. var dupes = [];
  19905. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  19906. var realPos = vectorPositions.length - 1 - iteration;
  19907. var testedPosition = vectorPositions[realPos];
  19908. for (var j = 0; j < realPos; ++j) {
  19909. var againstPosition = vectorPositions[j];
  19910. if (testedPosition.equals(againstPosition)) {
  19911. dupes[realPos] = j;
  19912. break;
  19913. }
  19914. }
  19915. }, function () {
  19916. for (var i = 0; i < indices.length; ++i) {
  19917. indices[i] = dupes[indices[i]] || indices[i];
  19918. }
  19919. //indices are now reordered
  19920. var originalSubMeshes = _this.subMeshes.slice(0);
  19921. _this.setIndices(indices);
  19922. _this.subMeshes = originalSubMeshes;
  19923. if (successCallback) {
  19924. successCallback(_this);
  19925. }
  19926. });
  19927. return this;
  19928. };
  19929. Mesh.prototype.serialize = function (serializationObject) {
  19930. serializationObject.name = this.name;
  19931. serializationObject.id = this.id;
  19932. serializationObject.type = this.getClassName();
  19933. if (BABYLON.Tags.HasTags(this)) {
  19934. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19935. }
  19936. serializationObject.position = this.position.asArray();
  19937. if (this.rotationQuaternion) {
  19938. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  19939. }
  19940. else if (this.rotation) {
  19941. serializationObject.rotation = this.rotation.asArray();
  19942. }
  19943. serializationObject.scaling = this.scaling.asArray();
  19944. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19945. serializationObject.isEnabled = this.isEnabled();
  19946. serializationObject.isVisible = this.isVisible;
  19947. serializationObject.infiniteDistance = this.infiniteDistance;
  19948. serializationObject.pickable = this.isPickable;
  19949. serializationObject.receiveShadows = this.receiveShadows;
  19950. serializationObject.billboardMode = this.billboardMode;
  19951. serializationObject.visibility = this.visibility;
  19952. serializationObject.checkCollisions = this.checkCollisions;
  19953. serializationObject.isBlocker = this.isBlocker;
  19954. // Parent
  19955. if (this.parent) {
  19956. serializationObject.parentId = this.parent.id;
  19957. }
  19958. // Geometry
  19959. var geometry = this._geometry;
  19960. if (geometry) {
  19961. var geometryId = geometry.id;
  19962. serializationObject.geometryId = geometryId;
  19963. // SubMeshes
  19964. serializationObject.subMeshes = [];
  19965. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  19966. var subMesh = this.subMeshes[subIndex];
  19967. serializationObject.subMeshes.push({
  19968. materialIndex: subMesh.materialIndex,
  19969. verticesStart: subMesh.verticesStart,
  19970. verticesCount: subMesh.verticesCount,
  19971. indexStart: subMesh.indexStart,
  19972. indexCount: subMesh.indexCount
  19973. });
  19974. }
  19975. }
  19976. // Material
  19977. if (this.material) {
  19978. serializationObject.materialId = this.material.id;
  19979. }
  19980. else {
  19981. this.material = null;
  19982. }
  19983. // Morph targets
  19984. if (this.morphTargetManager) {
  19985. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  19986. }
  19987. // Skeleton
  19988. if (this.skeleton) {
  19989. serializationObject.skeletonId = this.skeleton.id;
  19990. }
  19991. // Physics
  19992. //TODO implement correct serialization for physics impostors.
  19993. if (this.getPhysicsImpostor()) {
  19994. var impostor = this.getPhysicsImpostor();
  19995. serializationObject.physicsMass = impostor.getParam("mass");
  19996. serializationObject.physicsFriction = impostor.getParam("friction");
  19997. serializationObject.physicsRestitution = impostor.getParam("mass");
  19998. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  19999. }
  20000. // Metadata
  20001. if (this.metadata) {
  20002. serializationObject.metadata = this.metadata;
  20003. }
  20004. // Instances
  20005. serializationObject.instances = [];
  20006. for (var index = 0; index < this.instances.length; index++) {
  20007. var instance = this.instances[index];
  20008. var serializationInstance = {
  20009. name: instance.name,
  20010. position: instance.position.asArray(),
  20011. scaling: instance.scaling.asArray()
  20012. };
  20013. if (instance.rotationQuaternion) {
  20014. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  20015. }
  20016. else if (instance.rotation) {
  20017. serializationInstance.rotation = instance.rotation.asArray();
  20018. }
  20019. serializationObject.instances.push(serializationInstance);
  20020. // Animations
  20021. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  20022. serializationInstance.ranges = instance.serializeAnimationRanges();
  20023. }
  20024. //
  20025. // Animations
  20026. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20027. serializationObject.ranges = this.serializeAnimationRanges();
  20028. // Layer mask
  20029. serializationObject.layerMask = this.layerMask;
  20030. // Alpha
  20031. serializationObject.alphaIndex = this.alphaIndex;
  20032. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  20033. // Overlay
  20034. serializationObject.overlayAlpha = this.overlayAlpha;
  20035. serializationObject.overlayColor = this.overlayColor.asArray();
  20036. serializationObject.renderOverlay = this.renderOverlay;
  20037. // Fog
  20038. serializationObject.applyFog = this.applyFog;
  20039. // Action Manager
  20040. if (this.actionManager) {
  20041. serializationObject.actions = this.actionManager.serialize(this.name);
  20042. }
  20043. };
  20044. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  20045. if (!this.geometry) {
  20046. return;
  20047. }
  20048. this._markSubMeshesAsAttributesDirty();
  20049. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  20050. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  20051. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  20052. this.morphTargetManager = undefined;
  20053. return;
  20054. }
  20055. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  20056. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  20057. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  20058. if (morphTarget.hasNormals) {
  20059. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  20060. }
  20061. }
  20062. }
  20063. else {
  20064. var index = 0;
  20065. // Positions
  20066. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  20067. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  20068. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  20069. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  20070. }
  20071. index++;
  20072. }
  20073. }
  20074. };
  20075. // Statics
  20076. /**
  20077. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20078. * The parameter `parsedMesh` is the mesh to be copied.
  20079. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20080. */
  20081. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20082. var mesh;
  20083. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  20084. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  20085. }
  20086. else {
  20087. mesh = new Mesh(parsedMesh.name, scene);
  20088. }
  20089. mesh.id = parsedMesh.id;
  20090. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20091. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20092. if (parsedMesh.metadata !== undefined) {
  20093. mesh.metadata = parsedMesh.metadata;
  20094. }
  20095. if (parsedMesh.rotationQuaternion) {
  20096. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20097. }
  20098. else if (parsedMesh.rotation) {
  20099. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20100. }
  20101. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20102. if (parsedMesh.localMatrix) {
  20103. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20104. }
  20105. else if (parsedMesh.pivotMatrix) {
  20106. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20107. }
  20108. mesh.setEnabled(parsedMesh.isEnabled);
  20109. mesh.isVisible = parsedMesh.isVisible;
  20110. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20111. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20112. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20113. if (parsedMesh.applyFog !== undefined) {
  20114. mesh.applyFog = parsedMesh.applyFog;
  20115. }
  20116. if (parsedMesh.pickable !== undefined) {
  20117. mesh.isPickable = parsedMesh.pickable;
  20118. }
  20119. if (parsedMesh.alphaIndex !== undefined) {
  20120. mesh.alphaIndex = parsedMesh.alphaIndex;
  20121. }
  20122. mesh.receiveShadows = parsedMesh.receiveShadows;
  20123. mesh.billboardMode = parsedMesh.billboardMode;
  20124. if (parsedMesh.visibility !== undefined) {
  20125. mesh.visibility = parsedMesh.visibility;
  20126. }
  20127. mesh.checkCollisions = parsedMesh.checkCollisions;
  20128. if (parsedMesh.isBlocker !== undefined) {
  20129. mesh.isBlocker = parsedMesh.isBlocker;
  20130. }
  20131. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20132. // freezeWorldMatrix
  20133. if (parsedMesh.freezeWorldMatrix) {
  20134. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20135. }
  20136. // Parent
  20137. if (parsedMesh.parentId) {
  20138. mesh._waitingParentId = parsedMesh.parentId;
  20139. }
  20140. // Actions
  20141. if (parsedMesh.actions !== undefined) {
  20142. mesh._waitingActions = parsedMesh.actions;
  20143. }
  20144. // Overlay
  20145. if (parsedMesh.overlayAlpha !== undefined) {
  20146. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  20147. }
  20148. if (parsedMesh.overlayColor !== undefined) {
  20149. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  20150. }
  20151. if (parsedMesh.renderOverlay !== undefined) {
  20152. mesh.renderOverlay = parsedMesh.renderOverlay;
  20153. }
  20154. // Geometry
  20155. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20156. if (parsedMesh.delayLoadingFile) {
  20157. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20158. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20159. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20160. if (parsedMesh._binaryInfo) {
  20161. mesh._binaryInfo = parsedMesh._binaryInfo;
  20162. }
  20163. mesh._delayInfo = [];
  20164. if (parsedMesh.hasUVs) {
  20165. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20166. }
  20167. if (parsedMesh.hasUVs2) {
  20168. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20169. }
  20170. if (parsedMesh.hasUVs3) {
  20171. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20172. }
  20173. if (parsedMesh.hasUVs4) {
  20174. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20175. }
  20176. if (parsedMesh.hasUVs5) {
  20177. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20178. }
  20179. if (parsedMesh.hasUVs6) {
  20180. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20181. }
  20182. if (parsedMesh.hasColors) {
  20183. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20184. }
  20185. if (parsedMesh.hasMatricesIndices) {
  20186. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20187. }
  20188. if (parsedMesh.hasMatricesWeights) {
  20189. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20190. }
  20191. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20192. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20193. mesh._checkDelayState();
  20194. }
  20195. }
  20196. else {
  20197. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20198. }
  20199. // Material
  20200. if (parsedMesh.materialId) {
  20201. mesh.setMaterialByID(parsedMesh.materialId);
  20202. }
  20203. else {
  20204. mesh.material = null;
  20205. }
  20206. // Morph targets
  20207. if (parsedMesh.morphTargetManagerId > -1) {
  20208. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  20209. }
  20210. // Skeleton
  20211. if (parsedMesh.skeletonId > -1) {
  20212. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20213. if (parsedMesh.numBoneInfluencers) {
  20214. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20215. }
  20216. }
  20217. // Animations
  20218. if (parsedMesh.animations) {
  20219. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20220. var parsedAnimation = parsedMesh.animations[animationIndex];
  20221. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20222. }
  20223. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20224. }
  20225. if (parsedMesh.autoAnimate) {
  20226. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20227. }
  20228. // Layer Mask
  20229. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20230. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20231. }
  20232. else {
  20233. mesh.layerMask = 0x0FFFFFFF;
  20234. }
  20235. // Physics
  20236. if (parsedMesh.physicsImpostor) {
  20237. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20238. mass: parsedMesh.physicsMass,
  20239. friction: parsedMesh.physicsFriction,
  20240. restitution: parsedMesh.physicsRestitution
  20241. }, scene);
  20242. }
  20243. // Instances
  20244. if (parsedMesh.instances) {
  20245. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20246. var parsedInstance = parsedMesh.instances[index];
  20247. var instance = mesh.createInstance(parsedInstance.name);
  20248. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20249. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20250. if (parsedInstance.parentId) {
  20251. instance._waitingParentId = parsedInstance.parentId;
  20252. }
  20253. if (parsedInstance.rotationQuaternion) {
  20254. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20255. }
  20256. else if (parsedInstance.rotation) {
  20257. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20258. }
  20259. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20260. instance.checkCollisions = mesh.checkCollisions;
  20261. if (parsedMesh.animations) {
  20262. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20263. parsedAnimation = parsedMesh.animations[animationIndex];
  20264. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20265. }
  20266. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20267. }
  20268. }
  20269. }
  20270. return mesh;
  20271. };
  20272. /**
  20273. * Creates a ribbon mesh.
  20274. * Please consider using the same method from the MeshBuilder class instead.
  20275. * 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.
  20276. *
  20277. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20278. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20279. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20280. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20281. * 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.
  20282. * 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.
  20283. * 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
  20284. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20285. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20286. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20287. */
  20288. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20289. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20290. pathArray: pathArray,
  20291. closeArray: closeArray,
  20292. closePath: closePath,
  20293. offset: offset,
  20294. updatable: updatable,
  20295. sideOrientation: sideOrientation,
  20296. instance: instance
  20297. }, scene);
  20298. };
  20299. /**
  20300. * Creates a plane polygonal mesh. By default, this is a disc.
  20301. * Please consider using the same method from the MeshBuilder class instead.
  20302. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20303. * 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.
  20304. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20305. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20306. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20307. */
  20308. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20309. var options = {
  20310. radius: radius,
  20311. tessellation: tessellation,
  20312. sideOrientation: sideOrientation,
  20313. updatable: updatable
  20314. };
  20315. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20316. };
  20317. /**
  20318. * Creates a box mesh.
  20319. * Please consider using the same method from the MeshBuilder class instead.
  20320. * The parameter `size` sets the size (float) of each box side (default 1).
  20321. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20322. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20323. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20324. */
  20325. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20326. var options = {
  20327. size: size,
  20328. sideOrientation: sideOrientation,
  20329. updatable: updatable
  20330. };
  20331. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20332. };
  20333. /**
  20334. * Creates a sphere mesh.
  20335. * Please consider using the same method from the MeshBuilder class instead.
  20336. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20337. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20338. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20339. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20341. */
  20342. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20343. var options = {
  20344. segments: segments,
  20345. diameterX: diameter,
  20346. diameterY: diameter,
  20347. diameterZ: diameter,
  20348. sideOrientation: sideOrientation,
  20349. updatable: updatable
  20350. };
  20351. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20352. };
  20353. /**
  20354. * Creates a cylinder or a cone mesh.
  20355. * Please consider using the same method from the MeshBuilder class instead.
  20356. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20357. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20358. * 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.
  20359. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20360. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20361. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20362. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20363. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20364. */
  20365. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20366. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20367. if (scene !== undefined) {
  20368. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20369. updatable = scene;
  20370. }
  20371. scene = subdivisions;
  20372. subdivisions = 1;
  20373. }
  20374. var options = {
  20375. height: height,
  20376. diameterTop: diameterTop,
  20377. diameterBottom: diameterBottom,
  20378. tessellation: tessellation,
  20379. subdivisions: subdivisions,
  20380. sideOrientation: sideOrientation,
  20381. updatable: updatable
  20382. };
  20383. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20384. };
  20385. // Torus (Code from SharpDX.org)
  20386. /**
  20387. * Creates a torus mesh.
  20388. * Please consider using the same method from the MeshBuilder class instead.
  20389. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20390. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20391. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20392. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20393. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20394. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20395. */
  20396. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20397. var options = {
  20398. diameter: diameter,
  20399. thickness: thickness,
  20400. tessellation: tessellation,
  20401. sideOrientation: sideOrientation,
  20402. updatable: updatable
  20403. };
  20404. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20405. };
  20406. /**
  20407. * Creates a torus knot mesh.
  20408. * Please consider using the same method from the MeshBuilder class instead.
  20409. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20410. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20411. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20412. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20413. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20414. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20415. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20416. */
  20417. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20418. var options = {
  20419. radius: radius,
  20420. tube: tube,
  20421. radialSegments: radialSegments,
  20422. tubularSegments: tubularSegments,
  20423. p: p,
  20424. q: q,
  20425. sideOrientation: sideOrientation,
  20426. updatable: updatable
  20427. };
  20428. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20429. };
  20430. /**
  20431. * Creates a line mesh.
  20432. * Please consider using the same method from the MeshBuilder class instead.
  20433. * 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.
  20434. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20435. * The parameter `points` is an array successive Vector3.
  20436. * 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
  20437. * When updating an instance, remember that only point positions can change, not the number of points.
  20438. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20439. */
  20440. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20441. var options = {
  20442. points: points,
  20443. updatable: updatable,
  20444. instance: instance
  20445. };
  20446. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20447. };
  20448. /**
  20449. * Creates a dashed line mesh.
  20450. * Please consider using the same method from the MeshBuilder class instead.
  20451. * 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.
  20452. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20453. * The parameter `points` is an array successive Vector3.
  20454. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20455. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20456. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20457. * 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
  20458. * When updating an instance, remember that only point positions can change, not the number of points.
  20459. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20460. */
  20461. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20462. var options = {
  20463. points: points,
  20464. dashSize: dashSize,
  20465. gapSize: gapSize,
  20466. dashNb: dashNb,
  20467. updatable: updatable,
  20468. instance: instance
  20469. };
  20470. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20471. };
  20472. /**
  20473. * Creates an extruded shape mesh.
  20474. * 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.
  20475. * Please consider using the same method from the MeshBuilder class instead.
  20476. *
  20477. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20478. * 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
  20479. * extruded along the Z axis.
  20480. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20481. * 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.
  20482. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20483. * 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
  20484. * 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
  20485. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20486. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20487. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20488. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20489. */
  20490. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20491. var options = {
  20492. shape: shape,
  20493. path: path,
  20494. scale: scale,
  20495. rotation: rotation,
  20496. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20497. sideOrientation: sideOrientation,
  20498. instance: instance,
  20499. updatable: updatable
  20500. };
  20501. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20502. };
  20503. /**
  20504. * Creates an custom extruded shape mesh.
  20505. * 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.
  20506. * Please consider using the same method from the MeshBuilder class instead.
  20507. *
  20508. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20509. * 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
  20510. * extruded along the Z axis.
  20511. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20512. * 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
  20513. * and the distance of this point from the begining of the path :
  20514. * ```javascript
  20515. * var rotationFunction = function(i, distance) {
  20516. * // do things
  20517. * return rotationValue; }
  20518. * ```
  20519. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20520. * 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
  20521. * and the distance of this point from the begining of the path :
  20522. * ```javascript
  20523. * var scaleFunction = function(i, distance) {
  20524. * // do things
  20525. * return scaleValue;}
  20526. * ```
  20527. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20528. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20529. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20530. * 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
  20531. * 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
  20532. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20533. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20534. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20535. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20536. */
  20537. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20538. var options = {
  20539. shape: shape,
  20540. path: path,
  20541. scaleFunction: scaleFunction,
  20542. rotationFunction: rotationFunction,
  20543. ribbonCloseArray: ribbonCloseArray,
  20544. ribbonClosePath: ribbonClosePath,
  20545. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20546. sideOrientation: sideOrientation,
  20547. instance: instance,
  20548. updatable: updatable
  20549. };
  20550. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20551. };
  20552. /**
  20553. * Creates lathe mesh.
  20554. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20555. * Please consider using the same method from the MeshBuilder class instead.
  20556. * 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
  20557. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20558. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20559. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20560. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20561. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20562. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20563. */
  20564. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20565. var options = {
  20566. shape: shape,
  20567. radius: radius,
  20568. tessellation: tessellation,
  20569. sideOrientation: sideOrientation,
  20570. updatable: updatable
  20571. };
  20572. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20573. };
  20574. /**
  20575. * Creates a plane mesh.
  20576. * Please consider using the same method from the MeshBuilder class instead.
  20577. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20578. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20579. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20580. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20581. */
  20582. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20583. var options = {
  20584. size: size,
  20585. width: size,
  20586. height: size,
  20587. sideOrientation: sideOrientation,
  20588. updatable: updatable
  20589. };
  20590. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20591. };
  20592. /**
  20593. * Creates a ground mesh.
  20594. * Please consider using the same method from the MeshBuilder class instead.
  20595. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20596. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20597. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20598. */
  20599. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20600. var options = {
  20601. width: width,
  20602. height: height,
  20603. subdivisions: subdivisions,
  20604. updatable: updatable
  20605. };
  20606. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20607. };
  20608. /**
  20609. * Creates a tiled ground mesh.
  20610. * Please consider using the same method from the MeshBuilder class instead.
  20611. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20612. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20613. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20614. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20615. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20616. * numbers of subdivisions on the ground width and height of each tile.
  20617. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20618. */
  20619. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20620. var options = {
  20621. xmin: xmin,
  20622. zmin: zmin,
  20623. xmax: xmax,
  20624. zmax: zmax,
  20625. subdivisions: subdivisions,
  20626. precision: precision,
  20627. updatable: updatable
  20628. };
  20629. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20630. };
  20631. /**
  20632. * Creates a ground mesh from a height map.
  20633. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20634. * Please consider using the same method from the MeshBuilder class instead.
  20635. * The parameter `url` sets the URL of the height map image resource.
  20636. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20637. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20638. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20639. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20640. * 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).
  20641. * This function is passed the newly built mesh :
  20642. * ```javascript
  20643. * function(mesh) { // do things
  20644. * return; }
  20645. * ```
  20646. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20647. */
  20648. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  20649. var options = {
  20650. width: width,
  20651. height: height,
  20652. subdivisions: subdivisions,
  20653. minHeight: minHeight,
  20654. maxHeight: maxHeight,
  20655. updatable: updatable,
  20656. onReady: onReady
  20657. };
  20658. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  20659. };
  20660. /**
  20661. * Creates a tube mesh.
  20662. * 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.
  20663. * Please consider using the same method from the MeshBuilder class instead.
  20664. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20665. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20666. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20667. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20668. * 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.
  20669. * It must return a radius value (positive float) :
  20670. * ```javascript
  20671. * var radiusFunction = function(i, distance) {
  20672. * // do things
  20673. * return radius; }
  20674. * ```
  20675. * 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
  20676. * 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
  20677. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20678. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20679. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20680. */
  20681. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  20682. var options = {
  20683. path: path,
  20684. radius: radius,
  20685. tessellation: tessellation,
  20686. radiusFunction: radiusFunction,
  20687. arc: 1,
  20688. cap: cap,
  20689. updatable: updatable,
  20690. sideOrientation: sideOrientation,
  20691. instance: instance
  20692. };
  20693. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  20694. };
  20695. /**
  20696. * Creates a polyhedron mesh.
  20697. * Please consider using the same method from the MeshBuilder class instead.
  20698. * 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
  20699. * to choose the wanted type.
  20700. * The parameter `size` (positive float, default 1) sets the polygon size.
  20701. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20702. * 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`.
  20703. * 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
  20704. * 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)`).
  20705. * 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
  20706. * 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.
  20707. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20708. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20709. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20710. */
  20711. Mesh.CreatePolyhedron = function (name, options, scene) {
  20712. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  20713. };
  20714. /**
  20715. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20716. * Please consider using the same method from the MeshBuilder class instead.
  20717. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20718. * 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`).
  20719. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20720. * 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.
  20721. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20722. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20723. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20724. */
  20725. Mesh.CreateIcoSphere = function (name, options, scene) {
  20726. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  20727. };
  20728. /**
  20729. * Creates a decal mesh.
  20730. * Please consider using the same method from the MeshBuilder class instead.
  20731. * 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.
  20732. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20733. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20734. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  20735. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20736. */
  20737. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  20738. var options = {
  20739. position: position,
  20740. normal: normal,
  20741. size: size,
  20742. angle: angle
  20743. };
  20744. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  20745. };
  20746. // Skeletons
  20747. /**
  20748. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20749. */
  20750. Mesh.prototype.setPositionsForCPUSkinning = function () {
  20751. var source;
  20752. if (!this._sourcePositions) {
  20753. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20754. this._sourcePositions = new Float32Array(source);
  20755. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  20756. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  20757. }
  20758. }
  20759. return this._sourcePositions;
  20760. };
  20761. /**
  20762. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20763. */
  20764. Mesh.prototype.setNormalsForCPUSkinning = function () {
  20765. var source;
  20766. if (!this._sourceNormals) {
  20767. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20768. this._sourceNormals = new Float32Array(source);
  20769. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20770. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  20771. }
  20772. }
  20773. return this._sourceNormals;
  20774. };
  20775. /**
  20776. * Updates the vertex buffer by applying transformation from the bones.
  20777. * Returns the Mesh.
  20778. *
  20779. * @param {skeleton} skeleton to apply
  20780. */
  20781. Mesh.prototype.applySkeleton = function (skeleton) {
  20782. if (!this.geometry) {
  20783. return this;
  20784. }
  20785. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  20786. return this;
  20787. }
  20788. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  20789. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20790. return this;
  20791. }
  20792. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20793. return this;
  20794. }
  20795. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20796. return this;
  20797. }
  20798. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20799. return this;
  20800. }
  20801. if (!this._sourcePositions) {
  20802. var submeshes = this.subMeshes.slice();
  20803. this.setPositionsForCPUSkinning();
  20804. this.subMeshes = submeshes;
  20805. }
  20806. if (!this._sourceNormals) {
  20807. this.setNormalsForCPUSkinning();
  20808. }
  20809. // positionsData checks for not being Float32Array will only pass at most once
  20810. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20811. if (!(positionsData instanceof Float32Array)) {
  20812. positionsData = new Float32Array(positionsData);
  20813. }
  20814. // normalsData checks for not being Float32Array will only pass at most once
  20815. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20816. if (!(normalsData instanceof Float32Array)) {
  20817. normalsData = new Float32Array(normalsData);
  20818. }
  20819. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20820. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20821. var needExtras = this.numBoneInfluencers > 4;
  20822. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  20823. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  20824. var skeletonMatrices = skeleton.getTransformMatrices(this);
  20825. var tempVector3 = BABYLON.Vector3.Zero();
  20826. var finalMatrix = new BABYLON.Matrix();
  20827. var tempMatrix = new BABYLON.Matrix();
  20828. var matWeightIdx = 0;
  20829. var inf;
  20830. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  20831. var weight;
  20832. for (inf = 0; inf < 4; inf++) {
  20833. weight = matricesWeightsData[matWeightIdx + inf];
  20834. if (weight > 0) {
  20835. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20836. finalMatrix.addToSelf(tempMatrix);
  20837. }
  20838. else
  20839. break;
  20840. }
  20841. if (needExtras) {
  20842. for (inf = 0; inf < 4; inf++) {
  20843. weight = matricesWeightsExtraData[matWeightIdx + inf];
  20844. if (weight > 0) {
  20845. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20846. finalMatrix.addToSelf(tempMatrix);
  20847. }
  20848. else
  20849. break;
  20850. }
  20851. }
  20852. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  20853. tempVector3.toArray(positionsData, index);
  20854. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  20855. tempVector3.toArray(normalsData, index);
  20856. finalMatrix.reset();
  20857. }
  20858. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  20859. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  20860. return this;
  20861. };
  20862. // Tools
  20863. /**
  20864. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  20865. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  20866. */
  20867. Mesh.MinMax = function (meshes) {
  20868. var minVector = null;
  20869. var maxVector = null;
  20870. meshes.forEach(function (mesh, index, array) {
  20871. var boundingBox = mesh.getBoundingInfo().boundingBox;
  20872. if (!minVector) {
  20873. minVector = boundingBox.minimumWorld;
  20874. maxVector = boundingBox.maximumWorld;
  20875. }
  20876. else {
  20877. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  20878. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  20879. }
  20880. });
  20881. return {
  20882. min: minVector,
  20883. max: maxVector
  20884. };
  20885. };
  20886. /**
  20887. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  20888. */
  20889. Mesh.Center = function (meshesOrMinMaxVector) {
  20890. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  20891. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  20892. };
  20893. /**
  20894. * Merge the array of meshes into a single mesh for performance reasons.
  20895. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  20896. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  20897. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  20898. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  20899. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  20900. */
  20901. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  20902. if (disposeSource === void 0) { disposeSource = true; }
  20903. var index;
  20904. if (!allow32BitsIndices) {
  20905. var totalVertices = 0;
  20906. // Counting vertices
  20907. for (index = 0; index < meshes.length; index++) {
  20908. if (meshes[index]) {
  20909. totalVertices += meshes[index].getTotalVertices();
  20910. if (totalVertices > 65536) {
  20911. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  20912. return null;
  20913. }
  20914. }
  20915. }
  20916. }
  20917. // Merge
  20918. var vertexData;
  20919. var otherVertexData;
  20920. var indiceArray = new Array();
  20921. var source;
  20922. for (index = 0; index < meshes.length; index++) {
  20923. if (meshes[index]) {
  20924. meshes[index].computeWorldMatrix(true);
  20925. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  20926. otherVertexData.transform(meshes[index].getWorldMatrix());
  20927. if (vertexData) {
  20928. vertexData.merge(otherVertexData);
  20929. }
  20930. else {
  20931. vertexData = otherVertexData;
  20932. source = meshes[index];
  20933. }
  20934. if (subdivideWithSubMeshes) {
  20935. indiceArray.push(meshes[index].getTotalIndices());
  20936. }
  20937. }
  20938. }
  20939. if (!meshSubclass) {
  20940. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  20941. }
  20942. vertexData.applyToMesh(meshSubclass);
  20943. // Setting properties
  20944. meshSubclass.material = source.material;
  20945. meshSubclass.checkCollisions = source.checkCollisions;
  20946. // Cleaning
  20947. if (disposeSource) {
  20948. for (index = 0; index < meshes.length; index++) {
  20949. if (meshes[index]) {
  20950. meshes[index].dispose();
  20951. }
  20952. }
  20953. }
  20954. // Subdivide
  20955. if (subdivideWithSubMeshes) {
  20956. //-- Suppresions du submesh global
  20957. meshSubclass.releaseSubMeshes();
  20958. index = 0;
  20959. var offset = 0;
  20960. //-- aplique la subdivision en fonction du tableau d'indices
  20961. while (index < indiceArray.length) {
  20962. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  20963. offset += indiceArray[index];
  20964. index++;
  20965. }
  20966. }
  20967. return meshSubclass;
  20968. };
  20969. return Mesh;
  20970. }(BABYLON.AbstractMesh));
  20971. // Consts
  20972. Mesh._FRONTSIDE = 0;
  20973. Mesh._BACKSIDE = 1;
  20974. Mesh._DOUBLESIDE = 2;
  20975. Mesh._DEFAULTSIDE = 0;
  20976. Mesh._NO_CAP = 0;
  20977. Mesh._CAP_START = 1;
  20978. Mesh._CAP_END = 2;
  20979. Mesh._CAP_ALL = 3;
  20980. BABYLON.Mesh = Mesh;
  20981. })(BABYLON || (BABYLON = {}));
  20982. //# sourceMappingURL=babylon.mesh.js.map
  20983. var BABYLON;
  20984. (function (BABYLON) {
  20985. var SubMesh = (function () {
  20986. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  20987. if (createBoundingBox === void 0) { createBoundingBox = true; }
  20988. this.materialIndex = materialIndex;
  20989. this.verticesStart = verticesStart;
  20990. this.verticesCount = verticesCount;
  20991. this.indexStart = indexStart;
  20992. this.indexCount = indexCount;
  20993. this._renderId = 0;
  20994. this._mesh = mesh;
  20995. this._renderingMesh = renderingMesh || mesh;
  20996. mesh.subMeshes.push(this);
  20997. this._trianglePlanes = [];
  20998. this._id = mesh.subMeshes.length - 1;
  20999. if (createBoundingBox) {
  21000. this.refreshBoundingInfo();
  21001. mesh.computeWorldMatrix(true);
  21002. }
  21003. }
  21004. Object.defineProperty(SubMesh.prototype, "effect", {
  21005. get: function () {
  21006. return this._materialEffect;
  21007. },
  21008. enumerable: true,
  21009. configurable: true
  21010. });
  21011. SubMesh.prototype.setEffect = function (effect, defines) {
  21012. if (this._materialEffect === effect) {
  21013. return;
  21014. }
  21015. this._materialDefines = defines;
  21016. this._materialEffect = effect;
  21017. };
  21018. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21019. get: function () {
  21020. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21021. },
  21022. enumerable: true,
  21023. configurable: true
  21024. });
  21025. /**
  21026. * Returns the submesh BoudingInfo object.
  21027. */
  21028. SubMesh.prototype.getBoundingInfo = function () {
  21029. if (this.IsGlobal) {
  21030. return this._mesh.getBoundingInfo();
  21031. }
  21032. return this._boundingInfo;
  21033. };
  21034. /**
  21035. * Sets the submesh BoundingInfo.
  21036. * Return the SubMesh.
  21037. */
  21038. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21039. this._boundingInfo = boundingInfo;
  21040. return this;
  21041. };
  21042. /**
  21043. * Returns the mesh of the current submesh.
  21044. */
  21045. SubMesh.prototype.getMesh = function () {
  21046. return this._mesh;
  21047. };
  21048. /**
  21049. * Returns the rendering mesh of the submesh.
  21050. */
  21051. SubMesh.prototype.getRenderingMesh = function () {
  21052. return this._renderingMesh;
  21053. };
  21054. /**
  21055. * Returns the submesh material.
  21056. */
  21057. SubMesh.prototype.getMaterial = function () {
  21058. var rootMaterial = this._renderingMesh.material;
  21059. if (rootMaterial && rootMaterial.getSubMaterial) {
  21060. var multiMaterial = rootMaterial;
  21061. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  21062. if (this._currentMaterial !== effectiveMaterial) {
  21063. this._currentMaterial = effectiveMaterial;
  21064. if (this._materialDefines) {
  21065. this._materialDefines.markAllAsDirty();
  21066. }
  21067. }
  21068. return effectiveMaterial;
  21069. }
  21070. if (!rootMaterial) {
  21071. return this._mesh.getScene().defaultMaterial;
  21072. }
  21073. return rootMaterial;
  21074. };
  21075. // Methods
  21076. /**
  21077. * Sets a new updated BoundingInfo object to the submesh.
  21078. * Returns the SubMesh.
  21079. */
  21080. SubMesh.prototype.refreshBoundingInfo = function () {
  21081. this._lastColliderWorldVertices = null;
  21082. if (this.IsGlobal) {
  21083. return;
  21084. }
  21085. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21086. if (!data) {
  21087. this._boundingInfo = this._mesh._boundingInfo;
  21088. return;
  21089. }
  21090. var indices = this._renderingMesh.getIndices();
  21091. var extend;
  21092. //is this the only submesh?
  21093. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21094. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21095. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21096. }
  21097. else {
  21098. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21099. }
  21100. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21101. return this;
  21102. };
  21103. SubMesh.prototype._checkCollision = function (collider) {
  21104. return this.getBoundingInfo()._checkCollision(collider);
  21105. };
  21106. /**
  21107. * Updates the submesh BoundingInfo.
  21108. * Returns the Submesh.
  21109. */
  21110. SubMesh.prototype.updateBoundingInfo = function (world) {
  21111. if (!this.getBoundingInfo()) {
  21112. this.refreshBoundingInfo();
  21113. }
  21114. this.getBoundingInfo().update(world);
  21115. return this;
  21116. };
  21117. /**
  21118. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  21119. * Boolean returned.
  21120. */
  21121. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21122. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21123. };
  21124. /**
  21125. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  21126. * Boolean returned.
  21127. */
  21128. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21129. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21130. };
  21131. /**
  21132. * Renders the submesh.
  21133. * Returns it.
  21134. */
  21135. SubMesh.prototype.render = function (enableAlphaMode) {
  21136. this._renderingMesh.render(this, enableAlphaMode);
  21137. return this;
  21138. };
  21139. /**
  21140. * Returns a new Index Buffer.
  21141. * Type returned : WebGLBuffer.
  21142. */
  21143. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21144. if (!this._linesIndexBuffer) {
  21145. var linesIndices = [];
  21146. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21147. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21148. }
  21149. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21150. this.linesIndexCount = linesIndices.length;
  21151. }
  21152. return this._linesIndexBuffer;
  21153. };
  21154. /**
  21155. * True is the passed Ray intersects the submesh bounding box.
  21156. * Boolean returned.
  21157. */
  21158. SubMesh.prototype.canIntersects = function (ray) {
  21159. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21160. };
  21161. /**
  21162. * Returns an object IntersectionInfo.
  21163. */
  21164. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21165. var intersectInfo = null;
  21166. // LineMesh first as it's also a Mesh...
  21167. if (this._mesh instanceof BABYLON.LinesMesh) {
  21168. var lineMesh = this._mesh;
  21169. // Line test
  21170. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21171. var p0 = positions[indices[index]];
  21172. var p1 = positions[indices[index + 1]];
  21173. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21174. if (length < 0) {
  21175. continue;
  21176. }
  21177. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21178. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21179. if (fastCheck) {
  21180. break;
  21181. }
  21182. }
  21183. }
  21184. }
  21185. else {
  21186. // Triangles test
  21187. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21188. var p0 = positions[indices[index]];
  21189. var p1 = positions[indices[index + 1]];
  21190. var p2 = positions[indices[index + 2]];
  21191. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21192. if (currentIntersectInfo) {
  21193. if (currentIntersectInfo.distance < 0) {
  21194. continue;
  21195. }
  21196. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21197. intersectInfo = currentIntersectInfo;
  21198. intersectInfo.faceId = index / 3;
  21199. if (fastCheck) {
  21200. break;
  21201. }
  21202. }
  21203. }
  21204. }
  21205. }
  21206. return intersectInfo;
  21207. };
  21208. // Clone
  21209. /**
  21210. * Creates a new Submesh from the passed Mesh.
  21211. */
  21212. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21213. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21214. if (!this.IsGlobal) {
  21215. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21216. }
  21217. return result;
  21218. };
  21219. // Dispose
  21220. /**
  21221. * Disposes the Submesh.
  21222. * Returns nothing.
  21223. */
  21224. SubMesh.prototype.dispose = function () {
  21225. if (this._linesIndexBuffer) {
  21226. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21227. this._linesIndexBuffer = null;
  21228. }
  21229. // Remove from mesh
  21230. var index = this._mesh.subMeshes.indexOf(this);
  21231. this._mesh.subMeshes.splice(index, 1);
  21232. };
  21233. // Statics
  21234. /**
  21235. * Creates a new Submesh from the passed parameters :
  21236. * - materialIndex (integer) : the index of the main mesh material.
  21237. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  21238. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  21239. * - mesh (Mesh) : the main mesh to create the submesh from.
  21240. * - renderingMesh (optional Mesh) : rendering mesh.
  21241. */
  21242. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21243. var minVertexIndex = Number.MAX_VALUE;
  21244. var maxVertexIndex = -Number.MAX_VALUE;
  21245. renderingMesh = renderingMesh || mesh;
  21246. var indices = renderingMesh.getIndices();
  21247. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21248. var vertexIndex = indices[index];
  21249. if (vertexIndex < minVertexIndex)
  21250. minVertexIndex = vertexIndex;
  21251. if (vertexIndex > maxVertexIndex)
  21252. maxVertexIndex = vertexIndex;
  21253. }
  21254. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21255. };
  21256. return SubMesh;
  21257. }());
  21258. BABYLON.SubMesh = SubMesh;
  21259. })(BABYLON || (BABYLON = {}));
  21260. //# sourceMappingURL=babylon.subMesh.js.map
  21261. var BABYLON;
  21262. (function (BABYLON) {
  21263. var EffectFallbacks = (function () {
  21264. function EffectFallbacks() {
  21265. this._defines = {};
  21266. this._currentRank = 32;
  21267. this._maxRank = -1;
  21268. }
  21269. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21270. if (!this._defines[rank]) {
  21271. if (rank < this._currentRank) {
  21272. this._currentRank = rank;
  21273. }
  21274. if (rank > this._maxRank) {
  21275. this._maxRank = rank;
  21276. }
  21277. this._defines[rank] = new Array();
  21278. }
  21279. this._defines[rank].push(define);
  21280. };
  21281. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21282. this._meshRank = rank;
  21283. this._mesh = mesh;
  21284. if (rank < this._currentRank) {
  21285. this._currentRank = rank;
  21286. }
  21287. if (rank > this._maxRank) {
  21288. this._maxRank = rank;
  21289. }
  21290. };
  21291. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21292. get: function () {
  21293. return this._currentRank <= this._maxRank;
  21294. },
  21295. enumerable: true,
  21296. configurable: true
  21297. });
  21298. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21299. // First we try to switch to CPU skinning
  21300. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  21301. this._mesh.computeBonesUsingShaders = false;
  21302. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21303. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21304. var scene = this._mesh.getScene();
  21305. for (var index = 0; index < scene.meshes.length; index++) {
  21306. var otherMesh = scene.meshes[index];
  21307. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  21308. otherMesh.computeBonesUsingShaders = false;
  21309. }
  21310. }
  21311. }
  21312. else {
  21313. var currentFallbacks = this._defines[this._currentRank];
  21314. if (currentFallbacks) {
  21315. for (var index = 0; index < currentFallbacks.length; index++) {
  21316. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21317. }
  21318. }
  21319. this._currentRank++;
  21320. }
  21321. return currentDefines;
  21322. };
  21323. return EffectFallbacks;
  21324. }());
  21325. BABYLON.EffectFallbacks = EffectFallbacks;
  21326. var EffectCreationOptions = (function () {
  21327. function EffectCreationOptions() {
  21328. }
  21329. return EffectCreationOptions;
  21330. }());
  21331. BABYLON.EffectCreationOptions = EffectCreationOptions;
  21332. var Effect = (function () {
  21333. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  21334. var _this = this;
  21335. this.uniqueId = 0;
  21336. this._isReady = false;
  21337. this._compilationError = "";
  21338. this._valueCache = {};
  21339. this.name = baseName;
  21340. if (attributesNamesOrOptions.attributes) {
  21341. var options = attributesNamesOrOptions;
  21342. this._engine = uniformsNamesOrEngine;
  21343. this._attributesNames = options.attributes;
  21344. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  21345. this._samplers = options.samplers;
  21346. this.defines = options.defines;
  21347. this.onError = options.onError;
  21348. this.onCompiled = options.onCompiled;
  21349. this._fallbacks = options.fallbacks;
  21350. this._indexParameters = options.indexParameters;
  21351. }
  21352. else {
  21353. this._engine = engine;
  21354. this.defines = defines;
  21355. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  21356. this._samplers = samplers;
  21357. this._attributesNames = attributesNamesOrOptions;
  21358. this.onError = onError;
  21359. this.onCompiled = onCompiled;
  21360. this._indexParameters = indexParameters;
  21361. this._fallbacks = fallbacks;
  21362. }
  21363. this.uniqueId = Effect._uniqueIdSeed++;
  21364. var vertexSource;
  21365. var fragmentSource;
  21366. if (baseName.vertexElement) {
  21367. vertexSource = document.getElementById(baseName.vertexElement);
  21368. if (!vertexSource) {
  21369. vertexSource = baseName.vertexElement;
  21370. }
  21371. }
  21372. else {
  21373. vertexSource = baseName.vertex || baseName;
  21374. }
  21375. if (baseName.fragmentElement) {
  21376. fragmentSource = document.getElementById(baseName.fragmentElement);
  21377. if (!fragmentSource) {
  21378. fragmentSource = baseName.fragmentElement;
  21379. }
  21380. }
  21381. else {
  21382. fragmentSource = baseName.fragment || baseName;
  21383. }
  21384. this._loadVertexShader(vertexSource, function (vertexCode) {
  21385. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21386. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  21387. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21388. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21389. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  21390. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  21391. });
  21392. });
  21393. });
  21394. });
  21395. });
  21396. });
  21397. }
  21398. Object.defineProperty(Effect.prototype, "key", {
  21399. get: function () {
  21400. return this._key;
  21401. },
  21402. enumerable: true,
  21403. configurable: true
  21404. });
  21405. // Properties
  21406. Effect.prototype.isReady = function () {
  21407. return this._isReady;
  21408. };
  21409. Effect.prototype.getProgram = function () {
  21410. return this._program;
  21411. };
  21412. Effect.prototype.getAttributesNames = function () {
  21413. return this._attributesNames;
  21414. };
  21415. Effect.prototype.getAttributeLocation = function (index) {
  21416. return this._attributes[index];
  21417. };
  21418. Effect.prototype.getAttributeLocationByName = function (name) {
  21419. var index = this._attributesNames.indexOf(name);
  21420. return this._attributes[index];
  21421. };
  21422. Effect.prototype.getAttributesCount = function () {
  21423. return this._attributes.length;
  21424. };
  21425. Effect.prototype.getUniformIndex = function (uniformName) {
  21426. return this._uniformsNames.indexOf(uniformName);
  21427. };
  21428. Effect.prototype.getUniform = function (uniformName) {
  21429. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21430. };
  21431. Effect.prototype.getSamplers = function () {
  21432. return this._samplers;
  21433. };
  21434. Effect.prototype.getCompilationError = function () {
  21435. return this._compilationError;
  21436. };
  21437. Effect.prototype.getVertexShaderSource = function () {
  21438. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  21439. };
  21440. Effect.prototype.getFragmentShaderSource = function () {
  21441. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  21442. };
  21443. // Methods
  21444. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21445. // DOM element ?
  21446. if (vertex instanceof HTMLElement) {
  21447. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21448. callback(vertexCode);
  21449. return;
  21450. }
  21451. // Base64 encoded ?
  21452. if (vertex.substr(0, 7) === "base64:") {
  21453. var vertexBinary = window.atob(vertex.substr(7));
  21454. callback(vertexBinary);
  21455. return;
  21456. }
  21457. // Is in local store ?
  21458. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21459. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21460. return;
  21461. }
  21462. var vertexShaderUrl;
  21463. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21464. vertexShaderUrl = vertex;
  21465. }
  21466. else {
  21467. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21468. }
  21469. // Vertex shader
  21470. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21471. };
  21472. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21473. // DOM element ?
  21474. if (fragment instanceof HTMLElement) {
  21475. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21476. callback(fragmentCode);
  21477. return;
  21478. }
  21479. // Base64 encoded ?
  21480. if (fragment.substr(0, 7) === "base64:") {
  21481. var fragmentBinary = window.atob(fragment.substr(7));
  21482. callback(fragmentBinary);
  21483. return;
  21484. }
  21485. // Is in local store ?
  21486. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21487. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21488. return;
  21489. }
  21490. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21491. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21492. return;
  21493. }
  21494. var fragmentShaderUrl;
  21495. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21496. fragmentShaderUrl = fragment;
  21497. }
  21498. else {
  21499. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21500. }
  21501. // Fragment shader
  21502. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21503. };
  21504. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  21505. // Rebuild shaders source code
  21506. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  21507. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  21508. vertexCode = prefix + vertexCode;
  21509. fragmentCode = prefix + fragmentCode;
  21510. // Number lines of shaders source code
  21511. var i = 2;
  21512. var regex = /\n/gm;
  21513. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  21514. i = 2;
  21515. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  21516. // Dump shaders name and formatted source code
  21517. if (this.name.vertexElement) {
  21518. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  21519. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  21520. }
  21521. else if (this.name.vertex) {
  21522. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  21523. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  21524. }
  21525. else {
  21526. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  21527. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  21528. }
  21529. };
  21530. ;
  21531. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  21532. var preparedSourceCode = this._processPrecision(sourceCode);
  21533. if (this._engine.webGLVersion == 1) {
  21534. callback(preparedSourceCode);
  21535. return;
  21536. }
  21537. // Already converted
  21538. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  21539. callback(preparedSourceCode);
  21540. return;
  21541. }
  21542. // Remove extensions
  21543. // #extension GL_OES_standard_derivatives : enable
  21544. // #extension GL_EXT_shader_texture_lod : enable
  21545. // #extension GL_EXT_frag_depth : enable
  21546. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  21547. var result = preparedSourceCode.replace(regex, "");
  21548. // Migrate to GLSL v300
  21549. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  21550. result = result.replace(/attribute[ \t]/g, "in ");
  21551. result = result.replace(/[ \t]attribute/g, " in");
  21552. if (isFragment) {
  21553. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  21554. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  21555. result = result.replace(/texture2D\(/g, "texture(");
  21556. result = result.replace(/textureCube\(/g, "texture(");
  21557. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  21558. result = result.replace(/gl_FragColor/g, "glFragColor");
  21559. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  21560. }
  21561. callback(result);
  21562. };
  21563. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21564. var _this = this;
  21565. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21566. var match = regex.exec(sourceCode);
  21567. var returnValue = new String(sourceCode);
  21568. while (match != null) {
  21569. var includeFile = match[1];
  21570. if (Effect.IncludesShadersStore[includeFile]) {
  21571. // Substitution
  21572. var includeContent = Effect.IncludesShadersStore[includeFile];
  21573. if (match[2]) {
  21574. var splits = match[3].split(",");
  21575. for (var index = 0; index < splits.length; index += 2) {
  21576. var source = new RegExp(splits[index], "g");
  21577. var dest = splits[index + 1];
  21578. includeContent = includeContent.replace(source, dest);
  21579. }
  21580. }
  21581. if (match[4]) {
  21582. var indexString = match[5];
  21583. if (indexString.indexOf("..") !== -1) {
  21584. var indexSplits = indexString.split("..");
  21585. var minIndex = parseInt(indexSplits[0]);
  21586. var maxIndex = parseInt(indexSplits[1]);
  21587. var sourceIncludeContent = includeContent.slice(0);
  21588. includeContent = "";
  21589. if (isNaN(maxIndex)) {
  21590. maxIndex = this._indexParameters[indexSplits[1]];
  21591. }
  21592. for (var i = minIndex; i < maxIndex; i++) {
  21593. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  21594. }
  21595. }
  21596. else {
  21597. includeContent = includeContent.replace(/\{X\}/g, indexString);
  21598. }
  21599. }
  21600. // Replace
  21601. returnValue = returnValue.replace(match[0], includeContent);
  21602. }
  21603. else {
  21604. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21605. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21606. Effect.IncludesShadersStore[includeFile] = fileContent;
  21607. _this._processIncludes(returnValue, callback);
  21608. });
  21609. return;
  21610. }
  21611. match = regex.exec(sourceCode);
  21612. }
  21613. callback(returnValue);
  21614. };
  21615. Effect.prototype._processPrecision = function (source) {
  21616. if (source.indexOf("precision highp float") === -1) {
  21617. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21618. source = "precision mediump float;\n" + source;
  21619. }
  21620. else {
  21621. source = "precision highp float;\n" + source;
  21622. }
  21623. }
  21624. else {
  21625. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21626. source = source.replace("precision highp float", "precision mediump float");
  21627. }
  21628. }
  21629. return source;
  21630. };
  21631. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21632. try {
  21633. var engine = this._engine;
  21634. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21635. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21636. this._attributes = engine.getAttributes(this._program, attributesNames);
  21637. var index;
  21638. for (index = 0; index < this._samplers.length; index++) {
  21639. var sampler = this.getUniform(this._samplers[index]);
  21640. if (sampler == null) {
  21641. this._samplers.splice(index, 1);
  21642. index--;
  21643. }
  21644. }
  21645. engine.bindSamplers(this);
  21646. this._compilationError = "";
  21647. this._isReady = true;
  21648. if (this.onCompiled) {
  21649. this.onCompiled(this);
  21650. }
  21651. }
  21652. catch (e) {
  21653. this._compilationError = e.message;
  21654. // Let's go through fallbacks then
  21655. BABYLON.Tools.Error("Unable to compile effect:");
  21656. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  21657. return " " + uniform;
  21658. }));
  21659. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  21660. return " " + attribute;
  21661. }));
  21662. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  21663. BABYLON.Tools.Error("Error: " + this._compilationError);
  21664. if (fallbacks && fallbacks.isMoreFallbacks) {
  21665. BABYLON.Tools.Error("Trying next fallback.");
  21666. defines = fallbacks.reduce(defines);
  21667. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21668. }
  21669. else {
  21670. if (this.onError) {
  21671. this.onError(this, this._compilationError);
  21672. }
  21673. }
  21674. }
  21675. };
  21676. Object.defineProperty(Effect.prototype, "isSupported", {
  21677. get: function () {
  21678. return this._compilationError === "";
  21679. },
  21680. enumerable: true,
  21681. configurable: true
  21682. });
  21683. Effect.prototype._bindTexture = function (channel, texture) {
  21684. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  21685. };
  21686. Effect.prototype.setTexture = function (channel, texture) {
  21687. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  21688. };
  21689. Effect.prototype.setTextureArray = function (channel, textures) {
  21690. if (this._samplers.indexOf(channel + "Ex") === -1) {
  21691. var initialPos = this._samplers.indexOf(channel);
  21692. for (var index = 1; index < textures.length; index++) {
  21693. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  21694. }
  21695. }
  21696. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  21697. };
  21698. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  21699. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  21700. };
  21701. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  21702. var cache = this._valueCache[uniformName];
  21703. var flag = matrix.updateFlag;
  21704. if (cache !== undefined && cache === flag) {
  21705. return false;
  21706. }
  21707. this._valueCache[uniformName] = flag;
  21708. return true;
  21709. };
  21710. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  21711. var cache = this._valueCache[uniformName];
  21712. if (!cache) {
  21713. cache = [x, y];
  21714. this._valueCache[uniformName] = cache;
  21715. return true;
  21716. }
  21717. var changed = false;
  21718. if (cache[0] !== x) {
  21719. cache[0] = x;
  21720. changed = true;
  21721. }
  21722. if (cache[1] !== y) {
  21723. cache[1] = y;
  21724. changed = true;
  21725. }
  21726. return changed;
  21727. };
  21728. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  21729. var cache = this._valueCache[uniformName];
  21730. if (!cache) {
  21731. cache = [x, y, z];
  21732. this._valueCache[uniformName] = cache;
  21733. return true;
  21734. }
  21735. var changed = false;
  21736. if (cache[0] !== x) {
  21737. cache[0] = x;
  21738. changed = true;
  21739. }
  21740. if (cache[1] !== y) {
  21741. cache[1] = y;
  21742. changed = true;
  21743. }
  21744. if (cache[2] !== z) {
  21745. cache[2] = z;
  21746. changed = true;
  21747. }
  21748. return changed;
  21749. };
  21750. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  21751. var cache = this._valueCache[uniformName];
  21752. if (!cache) {
  21753. cache = [x, y, z, w];
  21754. this._valueCache[uniformName] = cache;
  21755. return true;
  21756. }
  21757. var changed = false;
  21758. if (cache[0] !== x) {
  21759. cache[0] = x;
  21760. changed = true;
  21761. }
  21762. if (cache[1] !== y) {
  21763. cache[1] = y;
  21764. changed = true;
  21765. }
  21766. if (cache[2] !== z) {
  21767. cache[2] = z;
  21768. changed = true;
  21769. }
  21770. if (cache[3] !== w) {
  21771. cache[3] = w;
  21772. changed = true;
  21773. }
  21774. return changed;
  21775. };
  21776. Effect.prototype.setIntArray = function (uniformName, array) {
  21777. this._valueCache[uniformName] = null;
  21778. this._engine.setIntArray(this.getUniform(uniformName), array);
  21779. return this;
  21780. };
  21781. Effect.prototype.setIntArray2 = function (uniformName, array) {
  21782. this._valueCache[uniformName] = null;
  21783. this._engine.setIntArray2(this.getUniform(uniformName), array);
  21784. return this;
  21785. };
  21786. Effect.prototype.setIntArray3 = function (uniformName, array) {
  21787. this._valueCache[uniformName] = null;
  21788. this._engine.setIntArray3(this.getUniform(uniformName), array);
  21789. return this;
  21790. };
  21791. Effect.prototype.setIntArray4 = function (uniformName, array) {
  21792. this._valueCache[uniformName] = null;
  21793. this._engine.setIntArray4(this.getUniform(uniformName), array);
  21794. return this;
  21795. };
  21796. Effect.prototype.setFloatArray = function (uniformName, array) {
  21797. this._valueCache[uniformName] = null;
  21798. this._engine.setFloatArray(this.getUniform(uniformName), array);
  21799. return this;
  21800. };
  21801. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  21802. this._valueCache[uniformName] = null;
  21803. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  21804. return this;
  21805. };
  21806. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  21807. this._valueCache[uniformName] = null;
  21808. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  21809. return this;
  21810. };
  21811. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  21812. this._valueCache[uniformName] = null;
  21813. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  21814. return this;
  21815. };
  21816. Effect.prototype.setArray = function (uniformName, array) {
  21817. this._valueCache[uniformName] = null;
  21818. this._engine.setArray(this.getUniform(uniformName), array);
  21819. return this;
  21820. };
  21821. Effect.prototype.setArray2 = function (uniformName, array) {
  21822. this._valueCache[uniformName] = null;
  21823. this._engine.setArray2(this.getUniform(uniformName), array);
  21824. return this;
  21825. };
  21826. Effect.prototype.setArray3 = function (uniformName, array) {
  21827. this._valueCache[uniformName] = null;
  21828. this._engine.setArray3(this.getUniform(uniformName), array);
  21829. return this;
  21830. };
  21831. Effect.prototype.setArray4 = function (uniformName, array) {
  21832. this._valueCache[uniformName] = null;
  21833. this._engine.setArray4(this.getUniform(uniformName), array);
  21834. return this;
  21835. };
  21836. Effect.prototype.setMatrices = function (uniformName, matrices) {
  21837. this._valueCache[uniformName] = null;
  21838. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  21839. return this;
  21840. };
  21841. Effect.prototype.setMatrix = function (uniformName, matrix) {
  21842. if (this._cacheMatrix(uniformName, matrix)) {
  21843. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  21844. }
  21845. return this;
  21846. };
  21847. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  21848. this._valueCache[uniformName] = null;
  21849. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  21850. return this;
  21851. };
  21852. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  21853. this._valueCache[uniformName] = null;
  21854. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  21855. return this;
  21856. };
  21857. Effect.prototype.setFloat = function (uniformName, value) {
  21858. var cache = this._valueCache[uniformName];
  21859. if (cache !== undefined && cache === value)
  21860. return this;
  21861. this._valueCache[uniformName] = value;
  21862. this._engine.setFloat(this.getUniform(uniformName), value);
  21863. return this;
  21864. };
  21865. Effect.prototype.setBool = function (uniformName, bool) {
  21866. var cache = this._valueCache[uniformName];
  21867. if (cache !== undefined && cache === bool)
  21868. return this;
  21869. this._valueCache[uniformName] = bool;
  21870. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  21871. return this;
  21872. };
  21873. Effect.prototype.setVector2 = function (uniformName, vector2) {
  21874. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  21875. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  21876. }
  21877. return this;
  21878. };
  21879. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  21880. if (this._cacheFloat2(uniformName, x, y)) {
  21881. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  21882. }
  21883. return this;
  21884. };
  21885. Effect.prototype.setVector3 = function (uniformName, vector3) {
  21886. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  21887. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  21888. }
  21889. return this;
  21890. };
  21891. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  21892. if (this._cacheFloat3(uniformName, x, y, z)) {
  21893. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  21894. }
  21895. return this;
  21896. };
  21897. Effect.prototype.setVector4 = function (uniformName, vector4) {
  21898. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  21899. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  21900. }
  21901. return this;
  21902. };
  21903. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  21904. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  21905. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  21906. }
  21907. return this;
  21908. };
  21909. Effect.prototype.setColor3 = function (uniformName, color3) {
  21910. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  21911. this._engine.setColor3(this.getUniform(uniformName), color3);
  21912. }
  21913. return this;
  21914. };
  21915. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  21916. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  21917. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  21918. }
  21919. return this;
  21920. };
  21921. Effect.prototype._recombineShader = function (node) {
  21922. if (node.define) {
  21923. if (node.condition) {
  21924. var defineIndex = this.defines.indexOf("#define " + node.define);
  21925. if (defineIndex === -1) {
  21926. return null;
  21927. }
  21928. var nextComma = this.defines.indexOf("\n", defineIndex);
  21929. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  21930. var condition = defineValue + node.condition;
  21931. if (!eval(condition)) {
  21932. return null;
  21933. }
  21934. }
  21935. else if (node.ndef) {
  21936. if (this.defines.indexOf("#define " + node.define) !== -1) {
  21937. return null;
  21938. }
  21939. }
  21940. else if (this.defines.indexOf("#define " + node.define) === -1) {
  21941. return null;
  21942. }
  21943. }
  21944. var result = "";
  21945. for (var index = 0; index < node.children.length; index++) {
  21946. var line = node.children[index];
  21947. if (line.children) {
  21948. var combined = this._recombineShader(line);
  21949. if (combined !== null) {
  21950. result += combined + "\r\n";
  21951. }
  21952. continue;
  21953. }
  21954. if (line.length > 0) {
  21955. result += line + "\r\n";
  21956. }
  21957. }
  21958. return result;
  21959. };
  21960. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  21961. var root = {
  21962. children: []
  21963. };
  21964. var currentNode = root;
  21965. var lines = shaderString.split("\n");
  21966. for (var index = 0; index < lines.length; index++) {
  21967. var line = lines[index].trim();
  21968. // #ifdef
  21969. var pos = line.indexOf("#ifdef ");
  21970. if (pos !== -1) {
  21971. var define = line.substr(pos + 7);
  21972. var newNode = {
  21973. condition: null,
  21974. ndef: false,
  21975. define: define,
  21976. children: [],
  21977. parent: currentNode
  21978. };
  21979. currentNode.children.push(newNode);
  21980. currentNode = newNode;
  21981. continue;
  21982. }
  21983. // #ifndef
  21984. var pos = line.indexOf("#ifndef ");
  21985. if (pos !== -1) {
  21986. var define = line.substr(pos + 8);
  21987. newNode = {
  21988. condition: null,
  21989. define: define,
  21990. ndef: true,
  21991. children: [],
  21992. parent: currentNode
  21993. };
  21994. currentNode.children.push(newNode);
  21995. currentNode = newNode;
  21996. continue;
  21997. }
  21998. // #if
  21999. var pos = line.indexOf("#if ");
  22000. if (pos !== -1) {
  22001. var define = line.substr(pos + 4).trim();
  22002. var conditionPos = define.indexOf(" ");
  22003. newNode = {
  22004. condition: define.substr(conditionPos + 1),
  22005. define: define.substr(0, conditionPos),
  22006. ndef: false,
  22007. children: [],
  22008. parent: currentNode
  22009. };
  22010. currentNode.children.push(newNode);
  22011. currentNode = newNode;
  22012. continue;
  22013. }
  22014. // #endif
  22015. pos = line.indexOf("#endif");
  22016. if (pos !== -1) {
  22017. currentNode = currentNode.parent;
  22018. continue;
  22019. }
  22020. currentNode.children.push(line);
  22021. }
  22022. // Recombine
  22023. return this._recombineShader(root);
  22024. };
  22025. return Effect;
  22026. }());
  22027. Effect._uniqueIdSeed = 0;
  22028. // Statics
  22029. Effect.ShadersStore = {};
  22030. Effect.IncludesShadersStore = {};
  22031. BABYLON.Effect = Effect;
  22032. })(BABYLON || (BABYLON = {}));
  22033. //# sourceMappingURL=babylon.effect.js.map
  22034. var BABYLON;
  22035. (function (BABYLON) {
  22036. var MaterialHelper = (function () {
  22037. function MaterialHelper() {
  22038. }
  22039. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  22040. if (defines._areMiscDirty) {
  22041. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  22042. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  22043. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  22044. }
  22045. };
  22046. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  22047. var changed = false;
  22048. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  22049. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  22050. changed = true;
  22051. }
  22052. if (defines["ALPHATEST"] !== engine.getAlphaTesting()) {
  22053. defines["ALPHATEST"] = !defines["ALPHATEST"];
  22054. changed = true;
  22055. }
  22056. if (defines["INSTANCES"] !== useInstances) {
  22057. defines["INSTANCES"] = useInstances;
  22058. changed = true;
  22059. }
  22060. if (changed) {
  22061. defines.markAsUnprocessed();
  22062. }
  22063. };
  22064. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  22065. if (useMorphTargets === void 0) { useMorphTargets = false; }
  22066. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  22067. return;
  22068. }
  22069. defines._normals = defines._needNormals;
  22070. defines._uvs = defines._needUVs;
  22071. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  22072. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  22073. defines["TANGENT"] = true;
  22074. }
  22075. if (defines._needUVs) {
  22076. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  22077. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  22078. }
  22079. else {
  22080. defines["UV1"] = false;
  22081. defines["UV2"] = false;
  22082. }
  22083. if (useVertexColor) {
  22084. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  22085. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  22086. }
  22087. if (useBones) {
  22088. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  22089. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  22090. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  22091. }
  22092. else {
  22093. defines["NUM_BONE_INFLUENCERS"] = 0;
  22094. defines["BonesPerMesh"] = 0;
  22095. }
  22096. }
  22097. if (useMorphTargets) {
  22098. if (mesh.morphTargetManager) {
  22099. var manager = mesh.morphTargetManager;
  22100. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  22101. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  22102. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  22103. }
  22104. else {
  22105. defines["MORPHTARGETS_NORMAL"] = false;
  22106. defines["MORPHTARGETS"] = false;
  22107. defines["NUM_MORPH_INFLUENCERS"] = 0;
  22108. }
  22109. }
  22110. };
  22111. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  22112. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22113. if (disableLighting === void 0) { disableLighting = false; }
  22114. if (!defines._areLightsDirty) {
  22115. return defines._needNormals;
  22116. }
  22117. var lightIndex = 0;
  22118. var needNormals = false;
  22119. var needRebuild = false;
  22120. var lightmapMode = false;
  22121. var shadowEnabled = false;
  22122. var specularEnabled = false;
  22123. if (scene.lightsEnabled && !disableLighting) {
  22124. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  22125. var light = _a[_i];
  22126. needNormals = true;
  22127. if (defines["LIGHT" + lightIndex] === undefined) {
  22128. needRebuild = true;
  22129. }
  22130. defines["LIGHT" + lightIndex] = true;
  22131. defines["SPOTLIGHT" + lightIndex] = false;
  22132. defines["HEMILIGHT" + lightIndex] = false;
  22133. defines["POINTLIGHT" + lightIndex] = false;
  22134. defines["DIRLIGHT" + lightIndex] = false;
  22135. var type;
  22136. if (light.getTypeID() === 2) {
  22137. type = "SPOTLIGHT" + lightIndex;
  22138. }
  22139. else if (light.getTypeID() === 3) {
  22140. type = "HEMILIGHT" + lightIndex;
  22141. }
  22142. else if (light.getTypeID() === 0) {
  22143. type = "POINTLIGHT" + lightIndex;
  22144. }
  22145. else {
  22146. type = "DIRLIGHT" + lightIndex;
  22147. }
  22148. defines[type] = true;
  22149. // Specular
  22150. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  22151. specularEnabled = true;
  22152. }
  22153. // Shadows
  22154. defines["SHADOW" + lightIndex] = false;
  22155. if (scene.shadowsEnabled) {
  22156. var shadowGenerator = light.getShadowGenerator();
  22157. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22158. defines["SHADOW" + lightIndex] = true;
  22159. shadowEnabled = true;
  22160. defines["SHADOWPCF" + lightIndex] = false;
  22161. defines["SHADOWESM" + lightIndex] = false;
  22162. if (shadowGenerator.usePoissonSampling) {
  22163. defines["SHADOWPCF" + lightIndex] = true;
  22164. }
  22165. else if (shadowGenerator.useExponentialShadowMap || shadowGenerator.useBlurExponentialShadowMap) {
  22166. defines["SHADOWESM" + lightIndex] = true;
  22167. }
  22168. }
  22169. }
  22170. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  22171. lightmapMode = true;
  22172. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  22173. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  22174. }
  22175. else {
  22176. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  22177. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  22178. }
  22179. lightIndex++;
  22180. if (lightIndex === maxSimultaneousLights)
  22181. break;
  22182. }
  22183. }
  22184. defines["SPECULARTERM"] = specularEnabled;
  22185. defines["SHADOWS"] = shadowEnabled;
  22186. // Resetting all other lights if any
  22187. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  22188. if (defines["LIGHT" + index] !== undefined) {
  22189. defines["LIGHT" + index] = false;
  22190. }
  22191. }
  22192. var caps = scene.getEngine().getCaps();
  22193. if (defines["SHADOWFULLFLOAT"] === undefined) {
  22194. needRebuild = true;
  22195. }
  22196. defines["SHADOWFULLFLOAT"] = (shadowEnabled && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender);
  22197. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  22198. if (needRebuild) {
  22199. defines.rebuild();
  22200. }
  22201. return needNormals;
  22202. };
  22203. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  22204. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22205. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22206. if (!defines["LIGHT" + lightIndex]) {
  22207. break;
  22208. }
  22209. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  22210. samplersList.push("shadowSampler" + lightIndex);
  22211. }
  22212. if (defines["NUM_MORPH_INFLUENCERS"]) {
  22213. uniformsList.push("morphTargetInfluences");
  22214. }
  22215. };
  22216. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  22217. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22218. if (!defines["SHADOWS"]) {
  22219. return;
  22220. }
  22221. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22222. if (!defines["LIGHT" + lightIndex]) {
  22223. break;
  22224. }
  22225. if (lightIndex > 0) {
  22226. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22227. }
  22228. if (defines["SHADOW" + lightIndex]) {
  22229. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22230. }
  22231. if (defines["SHADOWPCF" + lightIndex]) {
  22232. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22233. }
  22234. if (defines["SHADOWESM" + lightIndex]) {
  22235. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  22236. }
  22237. }
  22238. };
  22239. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  22240. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  22241. if (influencers > 0) {
  22242. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  22243. var manager = mesh.morphTargetManager;
  22244. var normal = manager.supportsNormals && defines["NORMAL"];
  22245. for (var index = 0; index < influencers; index++) {
  22246. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  22247. if (normal) {
  22248. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  22249. }
  22250. if (attribs.length > maxAttributesCount) {
  22251. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  22252. }
  22253. }
  22254. }
  22255. };
  22256. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22257. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22258. fallbacks.addCPUSkinningFallback(0, mesh);
  22259. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22260. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22261. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22262. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22263. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22264. }
  22265. }
  22266. };
  22267. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22268. if (defines["INSTANCES"]) {
  22269. attribs.push("world0");
  22270. attribs.push("world1");
  22271. attribs.push("world2");
  22272. attribs.push("world3");
  22273. }
  22274. };
  22275. // Bindings
  22276. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22277. var shadowGenerator = light.getShadowGenerator();
  22278. if (mesh.receiveShadows && shadowGenerator) {
  22279. if (!light.needCube()) {
  22280. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22281. }
  22282. else {
  22283. if (!depthValuesAlreadySet) {
  22284. depthValuesAlreadySet = true;
  22285. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22286. }
  22287. }
  22288. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22289. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.depthScale);
  22290. }
  22291. return depthValuesAlreadySet;
  22292. };
  22293. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22294. if (light.getTypeID() === 0) {
  22295. // Point Light
  22296. light.transferToEffect(effect, "vLightData" + lightIndex);
  22297. }
  22298. else if (light.getTypeID() === 1) {
  22299. // Directional Light
  22300. light.transferToEffect(effect, "vLightData" + lightIndex);
  22301. }
  22302. else if (light.getTypeID() === 2) {
  22303. // Spot Light
  22304. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  22305. }
  22306. else if (light.getTypeID() === 3) {
  22307. // Hemispheric Light
  22308. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  22309. }
  22310. };
  22311. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  22312. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22313. var lightIndex = 0;
  22314. var depthValuesAlreadySet = false;
  22315. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  22316. var light = _a[_i];
  22317. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22318. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22319. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  22320. if (defines["SPECULARTERM"]) {
  22321. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22322. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  22323. }
  22324. // Shadows
  22325. if (scene.shadowsEnabled) {
  22326. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  22327. }
  22328. lightIndex++;
  22329. if (lightIndex === maxSimultaneousLights)
  22330. break;
  22331. }
  22332. };
  22333. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22334. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22335. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22336. effect.setColor3("vFogColor", scene.fogColor);
  22337. }
  22338. };
  22339. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22340. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22341. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  22342. if (matrices) {
  22343. effect.setMatrices("mBones", matrices);
  22344. }
  22345. }
  22346. };
  22347. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  22348. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  22349. return;
  22350. }
  22351. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  22352. };
  22353. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22354. if (defines["LOGARITHMICDEPTH"]) {
  22355. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22356. }
  22357. };
  22358. MaterialHelper.BindClipPlane = function (effect, scene) {
  22359. if (scene.clipPlane) {
  22360. var clipPlane = scene.clipPlane;
  22361. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22362. }
  22363. };
  22364. return MaterialHelper;
  22365. }());
  22366. BABYLON.MaterialHelper = MaterialHelper;
  22367. })(BABYLON || (BABYLON = {}));
  22368. //# sourceMappingURL=babylon.materialHelper.js.map
  22369. var BABYLON;
  22370. (function (BABYLON) {
  22371. var MaterialDefines = (function () {
  22372. function MaterialDefines() {
  22373. this._isDirty = true;
  22374. this._areLightsDirty = true;
  22375. this._areAttributesDirty = true;
  22376. this._areTexturesDirty = true;
  22377. this._areFresnelDirty = true;
  22378. this._areMiscDirty = true;
  22379. this._normals = false;
  22380. this._uvs = false;
  22381. this._needNormals = false;
  22382. this._needUVs = false;
  22383. }
  22384. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  22385. get: function () {
  22386. return this._isDirty;
  22387. },
  22388. enumerable: true,
  22389. configurable: true
  22390. });
  22391. MaterialDefines.prototype.markAsProcessed = function () {
  22392. this._isDirty = false;
  22393. this._areAttributesDirty = false;
  22394. this._areTexturesDirty = false;
  22395. this._areFresnelDirty = false;
  22396. this._areLightsDirty = false;
  22397. this._areMiscDirty = false;
  22398. };
  22399. MaterialDefines.prototype.markAsUnprocessed = function () {
  22400. this._isDirty = true;
  22401. };
  22402. MaterialDefines.prototype.markAllAsDirty = function () {
  22403. this._areTexturesDirty = true;
  22404. this._areAttributesDirty = true;
  22405. this._areLightsDirty = true;
  22406. this._areFresnelDirty = true;
  22407. this._areMiscDirty = true;
  22408. this._isDirty = true;
  22409. };
  22410. MaterialDefines.prototype.markAsLightDirty = function () {
  22411. this._areLightsDirty = true;
  22412. this._isDirty = true;
  22413. };
  22414. MaterialDefines.prototype.markAsAttributesDirty = function () {
  22415. this._areAttributesDirty = true;
  22416. this._isDirty = true;
  22417. };
  22418. MaterialDefines.prototype.markAsTexturesDirty = function () {
  22419. this._areTexturesDirty = true;
  22420. this._isDirty = true;
  22421. };
  22422. MaterialDefines.prototype.markAsFresnelDirty = function () {
  22423. this._areFresnelDirty = true;
  22424. this._isDirty = true;
  22425. };
  22426. MaterialDefines.prototype.markAsMiscDirty = function () {
  22427. this._areMiscDirty = true;
  22428. this._isDirty = true;
  22429. };
  22430. MaterialDefines.prototype.rebuild = function () {
  22431. if (this._keys) {
  22432. delete this._keys;
  22433. }
  22434. this._keys = [];
  22435. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  22436. var key = _a[_i];
  22437. if (key[0] === "_") {
  22438. continue;
  22439. }
  22440. this._keys.push(key);
  22441. }
  22442. };
  22443. MaterialDefines.prototype.isEqual = function (other) {
  22444. if (this._keys.length !== other._keys.length) {
  22445. return false;
  22446. }
  22447. for (var index = 0; index < this._keys.length; index++) {
  22448. var prop = this._keys[index];
  22449. if (this[prop] !== other[prop]) {
  22450. return false;
  22451. }
  22452. }
  22453. return true;
  22454. };
  22455. MaterialDefines.prototype.cloneTo = function (other) {
  22456. if (this._keys.length !== other._keys.length) {
  22457. other._keys = this._keys.slice(0);
  22458. }
  22459. for (var index = 0; index < this._keys.length; index++) {
  22460. var prop = this._keys[index];
  22461. other[prop] = this[prop];
  22462. }
  22463. };
  22464. MaterialDefines.prototype.reset = function () {
  22465. for (var index = 0; index < this._keys.length; index++) {
  22466. var prop = this._keys[index];
  22467. if (typeof (this[prop]) === "number") {
  22468. this[prop] = 0;
  22469. }
  22470. else {
  22471. this[prop] = false;
  22472. }
  22473. }
  22474. };
  22475. MaterialDefines.prototype.toString = function () {
  22476. var result = "";
  22477. for (var index = 0; index < this._keys.length; index++) {
  22478. var prop = this._keys[index];
  22479. var value = this[prop];
  22480. if (typeof (value) === "number") {
  22481. result += "#define " + prop + " " + this[prop] + "\n";
  22482. }
  22483. else if (value) {
  22484. result += "#define " + prop + "\n";
  22485. }
  22486. }
  22487. return result;
  22488. };
  22489. return MaterialDefines;
  22490. }());
  22491. BABYLON.MaterialDefines = MaterialDefines;
  22492. var Material = (function () {
  22493. function Material(name, scene, doNotAdd) {
  22494. this.checkReadyOnEveryCall = false;
  22495. this.checkReadyOnlyOnce = false;
  22496. this.state = "";
  22497. this.alpha = 1.0;
  22498. this._backFaceCulling = true;
  22499. this.doNotSerialize = false;
  22500. this.storeEffectOnSubMeshes = false;
  22501. /**
  22502. * An event triggered when the material is disposed.
  22503. * @type {BABYLON.Observable}
  22504. */
  22505. this.onDisposeObservable = new BABYLON.Observable();
  22506. /**
  22507. * An event triggered when the material is bound.
  22508. * @type {BABYLON.Observable}
  22509. */
  22510. this.onBindObservable = new BABYLON.Observable();
  22511. /**
  22512. * An event triggered when the material is unbound.
  22513. * @type {BABYLON.Observable}
  22514. */
  22515. this.onUnBindObservable = new BABYLON.Observable();
  22516. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22517. this.disableDepthWrite = false;
  22518. this._fogEnabled = true;
  22519. this.pointSize = 1.0;
  22520. this.zOffset = 0;
  22521. this._wasPreviouslyReady = false;
  22522. this._fillMode = Material.TriangleFillMode;
  22523. this.name = name;
  22524. this.id = name;
  22525. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22526. if (this._scene.useRightHandedSystem) {
  22527. this.sideOrientation = Material.ClockWiseSideOrientation;
  22528. }
  22529. else {
  22530. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22531. }
  22532. if (!doNotAdd) {
  22533. this._scene.materials.push(this);
  22534. }
  22535. }
  22536. Object.defineProperty(Material, "TriangleFillMode", {
  22537. get: function () {
  22538. return Material._TriangleFillMode;
  22539. },
  22540. enumerable: true,
  22541. configurable: true
  22542. });
  22543. Object.defineProperty(Material, "WireFrameFillMode", {
  22544. get: function () {
  22545. return Material._WireFrameFillMode;
  22546. },
  22547. enumerable: true,
  22548. configurable: true
  22549. });
  22550. Object.defineProperty(Material, "PointFillMode", {
  22551. get: function () {
  22552. return Material._PointFillMode;
  22553. },
  22554. enumerable: true,
  22555. configurable: true
  22556. });
  22557. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22558. get: function () {
  22559. return Material._ClockWiseSideOrientation;
  22560. },
  22561. enumerable: true,
  22562. configurable: true
  22563. });
  22564. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22565. get: function () {
  22566. return Material._CounterClockWiseSideOrientation;
  22567. },
  22568. enumerable: true,
  22569. configurable: true
  22570. });
  22571. Object.defineProperty(Material, "TextureDirtyFlag", {
  22572. get: function () {
  22573. return Material._TextureDirtyFlag;
  22574. },
  22575. enumerable: true,
  22576. configurable: true
  22577. });
  22578. Object.defineProperty(Material, "LightDirtyFlag", {
  22579. get: function () {
  22580. return Material._LightDirtyFlag;
  22581. },
  22582. enumerable: true,
  22583. configurable: true
  22584. });
  22585. Object.defineProperty(Material, "FresnelDirtyFlag", {
  22586. get: function () {
  22587. return Material._FresnelDirtyFlag;
  22588. },
  22589. enumerable: true,
  22590. configurable: true
  22591. });
  22592. Object.defineProperty(Material, "AttributesDirtyFlag", {
  22593. get: function () {
  22594. return Material._AttributesDirtyFlag;
  22595. },
  22596. enumerable: true,
  22597. configurable: true
  22598. });
  22599. Object.defineProperty(Material, "MiscDirtyFlag", {
  22600. get: function () {
  22601. return Material._MiscDirtyFlag;
  22602. },
  22603. enumerable: true,
  22604. configurable: true
  22605. });
  22606. Object.defineProperty(Material.prototype, "backFaceCulling", {
  22607. get: function () {
  22608. return this._backFaceCulling;
  22609. },
  22610. set: function (value) {
  22611. if (this._backFaceCulling === value) {
  22612. return;
  22613. }
  22614. this._backFaceCulling = value;
  22615. this.markAsDirty(Material.TextureDirtyFlag);
  22616. },
  22617. enumerable: true,
  22618. configurable: true
  22619. });
  22620. Object.defineProperty(Material.prototype, "onDispose", {
  22621. set: function (callback) {
  22622. if (this._onDisposeObserver) {
  22623. this.onDisposeObservable.remove(this._onDisposeObserver);
  22624. }
  22625. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22626. },
  22627. enumerable: true,
  22628. configurable: true
  22629. });
  22630. Object.defineProperty(Material.prototype, "onBind", {
  22631. set: function (callback) {
  22632. if (this._onBindObserver) {
  22633. this.onBindObservable.remove(this._onBindObserver);
  22634. }
  22635. this._onBindObserver = this.onBindObservable.add(callback);
  22636. },
  22637. enumerable: true,
  22638. configurable: true
  22639. });
  22640. Object.defineProperty(Material.prototype, "fogEnabled", {
  22641. get: function () {
  22642. return this._fogEnabled;
  22643. },
  22644. set: function (value) {
  22645. if (this._fogEnabled === value) {
  22646. return;
  22647. }
  22648. this._fogEnabled = value;
  22649. this.markAsDirty(Material.MiscDirtyFlag);
  22650. },
  22651. enumerable: true,
  22652. configurable: true
  22653. });
  22654. Object.defineProperty(Material.prototype, "wireframe", {
  22655. get: function () {
  22656. return this._fillMode === Material.WireFrameFillMode;
  22657. },
  22658. set: function (value) {
  22659. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22660. },
  22661. enumerable: true,
  22662. configurable: true
  22663. });
  22664. Object.defineProperty(Material.prototype, "pointsCloud", {
  22665. get: function () {
  22666. return this._fillMode === Material.PointFillMode;
  22667. },
  22668. set: function (value) {
  22669. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22670. },
  22671. enumerable: true,
  22672. configurable: true
  22673. });
  22674. Object.defineProperty(Material.prototype, "fillMode", {
  22675. get: function () {
  22676. return this._fillMode;
  22677. },
  22678. set: function (value) {
  22679. if (this._fillMode === value) {
  22680. return;
  22681. }
  22682. this._fillMode = value;
  22683. this.markAsDirty(Material.MiscDirtyFlag);
  22684. },
  22685. enumerable: true,
  22686. configurable: true
  22687. });
  22688. /**
  22689. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22690. * subclasses should override adding information pertainent to themselves
  22691. */
  22692. Material.prototype.toString = function (fullDetails) {
  22693. var ret = "Name: " + this.name;
  22694. if (fullDetails) {
  22695. }
  22696. return ret;
  22697. };
  22698. /**
  22699. * Child classes can use it to update shaders
  22700. */
  22701. Material.prototype.markAsDirty = function (flag) {
  22702. };
  22703. Material.prototype.getClassName = function () {
  22704. return "Material";
  22705. };
  22706. Object.defineProperty(Material.prototype, "isFrozen", {
  22707. get: function () {
  22708. return this.checkReadyOnlyOnce;
  22709. },
  22710. enumerable: true,
  22711. configurable: true
  22712. });
  22713. Material.prototype.freeze = function () {
  22714. this.checkReadyOnlyOnce = true;
  22715. };
  22716. Material.prototype.unfreeze = function () {
  22717. this.checkReadyOnlyOnce = false;
  22718. };
  22719. Material.prototype.isReady = function (mesh, useInstances) {
  22720. return true;
  22721. };
  22722. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  22723. return false;
  22724. };
  22725. Material.prototype.getEffect = function () {
  22726. return this._effect;
  22727. };
  22728. Material.prototype.getScene = function () {
  22729. return this._scene;
  22730. };
  22731. Material.prototype.needAlphaBlending = function () {
  22732. return (this.alpha < 1.0);
  22733. };
  22734. Material.prototype.needAlphaTesting = function () {
  22735. return false;
  22736. };
  22737. Material.prototype.getAlphaTestTexture = function () {
  22738. return null;
  22739. };
  22740. Material.prototype.markDirty = function () {
  22741. this._wasPreviouslyReady = false;
  22742. };
  22743. Material.prototype._preBind = function (effect) {
  22744. var engine = this._scene.getEngine();
  22745. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  22746. engine.enableEffect(effect ? effect : this._effect);
  22747. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  22748. };
  22749. Material.prototype.bind = function (world, mesh) {
  22750. };
  22751. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  22752. };
  22753. Material.prototype.bindOnlyWorldMatrix = function (world) {
  22754. };
  22755. Material.prototype._afterBind = function (mesh) {
  22756. this._scene._cachedMaterial = this;
  22757. this.onBindObservable.notifyObservers(mesh);
  22758. if (this.disableDepthWrite) {
  22759. var engine = this._scene.getEngine();
  22760. this._cachedDepthWriteState = engine.getDepthWrite();
  22761. engine.setDepthWrite(false);
  22762. }
  22763. };
  22764. Material.prototype.unbind = function () {
  22765. this.onUnBindObservable.notifyObservers(this);
  22766. if (this.disableDepthWrite) {
  22767. var engine = this._scene.getEngine();
  22768. engine.setDepthWrite(this._cachedDepthWriteState);
  22769. }
  22770. };
  22771. Material.prototype.clone = function (name) {
  22772. return null;
  22773. };
  22774. Material.prototype.getBindedMeshes = function () {
  22775. var result = new Array();
  22776. for (var index = 0; index < this._scene.meshes.length; index++) {
  22777. var mesh = this._scene.meshes[index];
  22778. if (mesh.material === this) {
  22779. result.push(mesh);
  22780. }
  22781. }
  22782. return result;
  22783. };
  22784. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  22785. // Animations
  22786. this.getScene().stopAnimation(this);
  22787. // Remove from scene
  22788. var index = this._scene.materials.indexOf(this);
  22789. if (index >= 0) {
  22790. this._scene.materials.splice(index, 1);
  22791. }
  22792. // Remove from meshes
  22793. for (index = 0; index < this._scene.meshes.length; index++) {
  22794. var mesh = this._scene.meshes[index];
  22795. if (mesh.material === this) {
  22796. mesh.material = null;
  22797. if (mesh.geometry) {
  22798. var geometry = mesh.geometry;
  22799. if (this.storeEffectOnSubMeshes) {
  22800. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  22801. var subMesh = _a[_i];
  22802. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  22803. }
  22804. }
  22805. else {
  22806. geometry._releaseVertexArrayObject(this._effect);
  22807. }
  22808. }
  22809. }
  22810. }
  22811. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  22812. if (forceDisposeEffect && this._effect) {
  22813. if (this.storeEffectOnSubMeshes) {
  22814. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22815. var subMesh = _c[_b];
  22816. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  22817. }
  22818. }
  22819. else {
  22820. this._scene.getEngine()._releaseEffect(this._effect);
  22821. }
  22822. this._effect = null;
  22823. }
  22824. // Callback
  22825. this.onDisposeObservable.notifyObservers(this);
  22826. this.onDisposeObservable.clear();
  22827. this.onBindObservable.clear();
  22828. this.onUnBindObservable.clear();
  22829. };
  22830. Material.prototype.serialize = function () {
  22831. return BABYLON.SerializationHelper.Serialize(this);
  22832. };
  22833. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  22834. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  22835. multiMaterial.id = parsedMultiMaterial.id;
  22836. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  22837. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  22838. var subMatId = parsedMultiMaterial.materials[matIndex];
  22839. if (subMatId) {
  22840. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  22841. }
  22842. else {
  22843. multiMaterial.subMaterials.push(null);
  22844. }
  22845. }
  22846. return multiMaterial;
  22847. };
  22848. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  22849. if (!parsedMaterial.customType) {
  22850. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  22851. }
  22852. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  22853. return materialType.Parse(parsedMaterial, scene, rootUrl);
  22854. ;
  22855. };
  22856. return Material;
  22857. }());
  22858. Material._TriangleFillMode = 0;
  22859. Material._WireFrameFillMode = 1;
  22860. Material._PointFillMode = 2;
  22861. Material._ClockWiseSideOrientation = 0;
  22862. Material._CounterClockWiseSideOrientation = 1;
  22863. Material._TextureDirtyFlag = 0;
  22864. Material._LightDirtyFlag = 1;
  22865. Material._FresnelDirtyFlag = 2;
  22866. Material._AttributesDirtyFlag = 4;
  22867. Material._MiscDirtyFlag = 8;
  22868. __decorate([
  22869. BABYLON.serialize()
  22870. ], Material.prototype, "id", void 0);
  22871. __decorate([
  22872. BABYLON.serialize()
  22873. ], Material.prototype, "name", void 0);
  22874. __decorate([
  22875. BABYLON.serialize()
  22876. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  22877. __decorate([
  22878. BABYLON.serialize()
  22879. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  22880. __decorate([
  22881. BABYLON.serialize()
  22882. ], Material.prototype, "state", void 0);
  22883. __decorate([
  22884. BABYLON.serialize()
  22885. ], Material.prototype, "alpha", void 0);
  22886. __decorate([
  22887. BABYLON.serialize("backFaceCulling")
  22888. ], Material.prototype, "_backFaceCulling", void 0);
  22889. __decorate([
  22890. BABYLON.serialize()
  22891. ], Material.prototype, "sideOrientation", void 0);
  22892. __decorate([
  22893. BABYLON.serialize()
  22894. ], Material.prototype, "alphaMode", void 0);
  22895. __decorate([
  22896. BABYLON.serialize()
  22897. ], Material.prototype, "disableDepthWrite", void 0);
  22898. __decorate([
  22899. BABYLON.serialize("fogEnabled")
  22900. ], Material.prototype, "_fogEnabled", void 0);
  22901. __decorate([
  22902. BABYLON.serialize()
  22903. ], Material.prototype, "pointSize", void 0);
  22904. __decorate([
  22905. BABYLON.serialize()
  22906. ], Material.prototype, "zOffset", void 0);
  22907. __decorate([
  22908. BABYLON.serialize()
  22909. ], Material.prototype, "wireframe", null);
  22910. __decorate([
  22911. BABYLON.serialize()
  22912. ], Material.prototype, "pointsCloud", null);
  22913. __decorate([
  22914. BABYLON.serialize()
  22915. ], Material.prototype, "fillMode", null);
  22916. BABYLON.Material = Material;
  22917. })(BABYLON || (BABYLON = {}));
  22918. //# sourceMappingURL=babylon.material.js.map
  22919. var BABYLON;
  22920. (function (BABYLON) {
  22921. var PushMaterial = (function (_super) {
  22922. __extends(PushMaterial, _super);
  22923. function PushMaterial(name, scene) {
  22924. var _this = _super.call(this, name, scene) || this;
  22925. _this.storeEffectOnSubMeshes = true;
  22926. return _this;
  22927. }
  22928. PushMaterial.prototype.getEffect = function () {
  22929. return this._activeEffect;
  22930. };
  22931. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  22932. if (!mesh) {
  22933. return false;
  22934. }
  22935. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22936. return true;
  22937. }
  22938. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  22939. };
  22940. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  22941. this._activeEffect.setMatrix("world", world);
  22942. };
  22943. PushMaterial.prototype.bind = function (world, mesh) {
  22944. if (!mesh) {
  22945. return;
  22946. }
  22947. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  22948. };
  22949. PushMaterial.prototype._afterBind = function (mesh, effect) {
  22950. _super.prototype._afterBind.call(this, mesh);
  22951. this.getScene()._cachedEffect = effect;
  22952. };
  22953. PushMaterial.prototype._mustRebind = function (scene, effect) {
  22954. return scene.getCachedEffect() !== effect || scene.getCachedMaterial() !== this;
  22955. };
  22956. PushMaterial.prototype.markAsDirty = function (flag) {
  22957. if (flag & BABYLON.Material.TextureDirtyFlag) {
  22958. this._markAllSubMeshesAsTexturesDirty();
  22959. }
  22960. if (flag & BABYLON.Material.LightDirtyFlag) {
  22961. this._markAllSubMeshesAsLightsDirty();
  22962. }
  22963. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  22964. this._markAllSubMeshesAsFresnelDirty();
  22965. }
  22966. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  22967. this._markAllSubMeshesAsAttributesDirty();
  22968. }
  22969. if (flag & BABYLON.Material.MiscDirtyFlag) {
  22970. this._markAllSubMeshesAsMiscDirty();
  22971. }
  22972. };
  22973. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  22974. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22975. var mesh = _a[_i];
  22976. if (!mesh.subMeshes) {
  22977. continue;
  22978. }
  22979. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22980. var subMesh = _c[_b];
  22981. if (subMesh.getMaterial() !== this) {
  22982. continue;
  22983. }
  22984. if (!subMesh._materialDefines) {
  22985. return;
  22986. }
  22987. func(subMesh._materialDefines);
  22988. }
  22989. }
  22990. };
  22991. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  22992. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  22993. };
  22994. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  22995. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  22996. };
  22997. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  22998. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  22999. };
  23000. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  23001. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  23002. };
  23003. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  23004. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  23005. };
  23006. return PushMaterial;
  23007. }(BABYLON.Material));
  23008. BABYLON.PushMaterial = PushMaterial;
  23009. })(BABYLON || (BABYLON = {}));
  23010. //# sourceMappingURL=babylon.pushMaterial.js.map
  23011. var BABYLON;
  23012. (function (BABYLON) {
  23013. var VertexData = (function () {
  23014. function VertexData() {
  23015. }
  23016. VertexData.prototype.set = function (data, kind) {
  23017. switch (kind) {
  23018. case BABYLON.VertexBuffer.PositionKind:
  23019. this.positions = data;
  23020. break;
  23021. case BABYLON.VertexBuffer.NormalKind:
  23022. this.normals = data;
  23023. break;
  23024. case BABYLON.VertexBuffer.TangentKind:
  23025. this.tangents = data;
  23026. break;
  23027. case BABYLON.VertexBuffer.UVKind:
  23028. this.uvs = data;
  23029. break;
  23030. case BABYLON.VertexBuffer.UV2Kind:
  23031. this.uvs2 = data;
  23032. break;
  23033. case BABYLON.VertexBuffer.UV3Kind:
  23034. this.uvs3 = data;
  23035. break;
  23036. case BABYLON.VertexBuffer.UV4Kind:
  23037. this.uvs4 = data;
  23038. break;
  23039. case BABYLON.VertexBuffer.UV5Kind:
  23040. this.uvs5 = data;
  23041. break;
  23042. case BABYLON.VertexBuffer.UV6Kind:
  23043. this.uvs6 = data;
  23044. break;
  23045. case BABYLON.VertexBuffer.ColorKind:
  23046. this.colors = data;
  23047. break;
  23048. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23049. this.matricesIndices = data;
  23050. break;
  23051. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23052. this.matricesWeights = data;
  23053. break;
  23054. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23055. this.matricesIndicesExtra = data;
  23056. break;
  23057. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23058. this.matricesWeightsExtra = data;
  23059. break;
  23060. }
  23061. };
  23062. /**
  23063. * Associates the vertexData to the passed Mesh.
  23064. * Sets it as updatable or not (default `false`).
  23065. * Returns the VertexData.
  23066. */
  23067. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23068. this._applyTo(mesh, updatable);
  23069. return this;
  23070. };
  23071. /**
  23072. * Associates the vertexData to the passed Geometry.
  23073. * Sets it as updatable or not (default `false`).
  23074. * Returns the VertexData.
  23075. */
  23076. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23077. this._applyTo(geometry, updatable);
  23078. return this;
  23079. };
  23080. /**
  23081. * Updates the associated mesh.
  23082. * Returns the VertexData.
  23083. */
  23084. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23085. this._update(mesh);
  23086. return this;
  23087. };
  23088. /**
  23089. * Updates the associated geometry.
  23090. * Returns the VertexData.
  23091. */
  23092. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23093. this._update(geometry);
  23094. return this;
  23095. };
  23096. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23097. if (this.positions) {
  23098. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23099. }
  23100. if (this.normals) {
  23101. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23102. }
  23103. if (this.tangents) {
  23104. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  23105. }
  23106. if (this.uvs) {
  23107. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23108. }
  23109. if (this.uvs2) {
  23110. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23111. }
  23112. if (this.uvs3) {
  23113. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23114. }
  23115. if (this.uvs4) {
  23116. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23117. }
  23118. if (this.uvs5) {
  23119. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23120. }
  23121. if (this.uvs6) {
  23122. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23123. }
  23124. if (this.colors) {
  23125. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23126. }
  23127. if (this.matricesIndices) {
  23128. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23129. }
  23130. if (this.matricesWeights) {
  23131. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23132. }
  23133. if (this.matricesIndicesExtra) {
  23134. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23135. }
  23136. if (this.matricesWeightsExtra) {
  23137. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23138. }
  23139. if (this.indices) {
  23140. meshOrGeometry.setIndices(this.indices);
  23141. }
  23142. return this;
  23143. };
  23144. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23145. if (this.positions) {
  23146. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23147. }
  23148. if (this.normals) {
  23149. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23150. }
  23151. if (this.tangents) {
  23152. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  23153. }
  23154. if (this.uvs) {
  23155. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23156. }
  23157. if (this.uvs2) {
  23158. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23159. }
  23160. if (this.uvs3) {
  23161. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23162. }
  23163. if (this.uvs4) {
  23164. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23165. }
  23166. if (this.uvs5) {
  23167. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23168. }
  23169. if (this.uvs6) {
  23170. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23171. }
  23172. if (this.colors) {
  23173. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23174. }
  23175. if (this.matricesIndices) {
  23176. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23177. }
  23178. if (this.matricesWeights) {
  23179. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23180. }
  23181. if (this.matricesIndicesExtra) {
  23182. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23183. }
  23184. if (this.matricesWeightsExtra) {
  23185. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23186. }
  23187. if (this.indices) {
  23188. meshOrGeometry.setIndices(this.indices);
  23189. }
  23190. return this;
  23191. };
  23192. /**
  23193. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  23194. * Returns the VertexData.
  23195. */
  23196. VertexData.prototype.transform = function (matrix) {
  23197. var transformed = BABYLON.Vector3.Zero();
  23198. var index;
  23199. if (this.positions) {
  23200. var position = BABYLON.Vector3.Zero();
  23201. for (index = 0; index < this.positions.length; index += 3) {
  23202. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23203. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23204. this.positions[index] = transformed.x;
  23205. this.positions[index + 1] = transformed.y;
  23206. this.positions[index + 2] = transformed.z;
  23207. }
  23208. }
  23209. if (this.normals) {
  23210. var normal = BABYLON.Vector3.Zero();
  23211. for (index = 0; index < this.normals.length; index += 3) {
  23212. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23213. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23214. this.normals[index] = transformed.x;
  23215. this.normals[index + 1] = transformed.y;
  23216. this.normals[index + 2] = transformed.z;
  23217. }
  23218. }
  23219. if (this.tangents) {
  23220. var tangent = BABYLON.Vector4.Zero();
  23221. var tangentTransformed = BABYLON.Vector4.Zero();
  23222. for (index = 0; index < this.tangents.length; index += 4) {
  23223. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  23224. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  23225. this.tangents[index] = tangentTransformed.x;
  23226. this.tangents[index + 1] = tangentTransformed.y;
  23227. this.tangents[index + 2] = tangentTransformed.z;
  23228. this.tangents[index + 3] = tangentTransformed.w;
  23229. }
  23230. }
  23231. return this;
  23232. };
  23233. /**
  23234. * Merges the passed VertexData into the current one.
  23235. * Returns the modified VertexData.
  23236. */
  23237. VertexData.prototype.merge = function (other) {
  23238. if (other.indices) {
  23239. if (!this.indices) {
  23240. this.indices = [];
  23241. }
  23242. var offset = this.positions ? this.positions.length / 3 : 0;
  23243. for (var index = 0; index < other.indices.length; index++) {
  23244. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  23245. this.indices.push(other.indices[index] + offset);
  23246. }
  23247. }
  23248. this.positions = this._mergeElement(this.positions, other.positions);
  23249. this.normals = this._mergeElement(this.normals, other.normals);
  23250. this.tangents = this._mergeElement(this.tangents, other.tangents);
  23251. this.uvs = this._mergeElement(this.uvs, other.uvs);
  23252. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  23253. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  23254. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  23255. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  23256. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  23257. this.colors = this._mergeElement(this.colors, other.colors);
  23258. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  23259. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  23260. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  23261. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  23262. return this;
  23263. };
  23264. VertexData.prototype._mergeElement = function (source, other) {
  23265. if (!other)
  23266. return source;
  23267. if (!source)
  23268. return other;
  23269. var len = other.length + source.length;
  23270. var isSrcTypedArray = source instanceof Float32Array;
  23271. var isOthTypedArray = other instanceof Float32Array;
  23272. // use non-loop method when the source is Float32Array
  23273. if (isSrcTypedArray) {
  23274. var ret32 = new Float32Array(len);
  23275. ret32.set(source);
  23276. ret32.set(other, source.length);
  23277. return ret32;
  23278. // source is number[], when other is also use concat
  23279. }
  23280. else if (!isOthTypedArray) {
  23281. return source.concat(other);
  23282. // source is a number[], but other is a Float32Array, loop required
  23283. }
  23284. else {
  23285. var ret = source.slice(0); // copy source to a separate array
  23286. for (var i = 0, len = other.length; i < len; i++) {
  23287. ret.push(other[i]);
  23288. }
  23289. return ret;
  23290. }
  23291. };
  23292. /**
  23293. * Serializes the VertexData.
  23294. * Returns a serialized object.
  23295. */
  23296. VertexData.prototype.serialize = function () {
  23297. var serializationObject = this.serialize();
  23298. if (this.positions) {
  23299. serializationObject.positions = this.positions;
  23300. }
  23301. if (this.normals) {
  23302. serializationObject.normals = this.normals;
  23303. }
  23304. if (this.tangents) {
  23305. serializationObject.tangents = this.tangents;
  23306. }
  23307. if (this.uvs) {
  23308. serializationObject.uvs = this.uvs;
  23309. }
  23310. if (this.uvs2) {
  23311. serializationObject.uvs2 = this.uvs2;
  23312. }
  23313. if (this.uvs3) {
  23314. serializationObject.uvs3 = this.uvs3;
  23315. }
  23316. if (this.uvs4) {
  23317. serializationObject.uvs4 = this.uvs4;
  23318. }
  23319. if (this.uvs5) {
  23320. serializationObject.uvs5 = this.uvs5;
  23321. }
  23322. if (this.uvs6) {
  23323. serializationObject.uvs6 = this.uvs6;
  23324. }
  23325. if (this.colors) {
  23326. serializationObject.colors = this.colors;
  23327. }
  23328. if (this.matricesIndices) {
  23329. serializationObject.matricesIndices = this.matricesIndices;
  23330. serializationObject.matricesIndices._isExpanded = true;
  23331. }
  23332. if (this.matricesWeights) {
  23333. serializationObject.matricesWeights = this.matricesWeights;
  23334. }
  23335. if (this.matricesIndicesExtra) {
  23336. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  23337. serializationObject.matricesIndicesExtra._isExpanded = true;
  23338. }
  23339. if (this.matricesWeightsExtra) {
  23340. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  23341. }
  23342. serializationObject.indices = this.indices;
  23343. return serializationObject;
  23344. };
  23345. // Statics
  23346. /**
  23347. * Returns the object VertexData associated to the passed mesh.
  23348. */
  23349. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23350. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23351. };
  23352. /**
  23353. * Returns the object VertexData associated to the passed geometry.
  23354. */
  23355. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23356. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23357. };
  23358. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23359. var result = new VertexData();
  23360. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23361. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23362. }
  23363. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23364. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23365. }
  23366. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23367. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared);
  23368. }
  23369. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23370. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23371. }
  23372. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23373. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23374. }
  23375. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23376. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23377. }
  23378. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23379. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23380. }
  23381. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23382. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23383. }
  23384. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23385. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23386. }
  23387. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23388. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23389. }
  23390. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23391. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23392. }
  23393. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23394. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23395. }
  23396. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23397. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23398. }
  23399. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23400. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23401. }
  23402. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23403. return result;
  23404. };
  23405. /**
  23406. * Creates the vertexData of the Ribbon.
  23407. */
  23408. VertexData.CreateRibbon = function (options) {
  23409. var pathArray = options.pathArray;
  23410. var closeArray = options.closeArray || false;
  23411. var closePath = options.closePath || false;
  23412. var invertUV = options.invertUV || false;
  23413. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23414. var offset = options.offset || defaultOffset;
  23415. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23416. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23417. var customUV = options.uvs;
  23418. var customColors = options.colors;
  23419. var positions = [];
  23420. var indices = [];
  23421. var normals = [];
  23422. var uvs = [];
  23423. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23424. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23425. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23426. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23427. var minlg; // minimal length among all paths from pathArray
  23428. var lg = []; // array of path lengths : nb of vertex per path
  23429. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23430. var p; // path iterator
  23431. var i; // point iterator
  23432. var j; // point iterator
  23433. // if single path in pathArray
  23434. if (pathArray.length < 2) {
  23435. var ar1 = [];
  23436. var ar2 = [];
  23437. for (i = 0; i < pathArray[0].length - offset; i++) {
  23438. ar1.push(pathArray[0][i]);
  23439. ar2.push(pathArray[0][i + offset]);
  23440. }
  23441. pathArray = [ar1, ar2];
  23442. }
  23443. // positions and horizontal distances (u)
  23444. var idc = 0;
  23445. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  23446. var path;
  23447. var l;
  23448. minlg = pathArray[0].length;
  23449. var vectlg;
  23450. var dist;
  23451. for (p = 0; p < pathArray.length; p++) {
  23452. uTotalDistance[p] = 0;
  23453. us[p] = [0];
  23454. path = pathArray[p];
  23455. l = path.length;
  23456. minlg = (minlg < l) ? minlg : l;
  23457. j = 0;
  23458. while (j < l) {
  23459. positions.push(path[j].x, path[j].y, path[j].z);
  23460. if (j > 0) {
  23461. vectlg = path[j].subtract(path[j - 1]).length();
  23462. dist = vectlg + uTotalDistance[p];
  23463. us[p].push(dist);
  23464. uTotalDistance[p] = dist;
  23465. }
  23466. j++;
  23467. }
  23468. if (closePath) {
  23469. j--;
  23470. positions.push(path[0].x, path[0].y, path[0].z);
  23471. vectlg = path[j].subtract(path[0]).length();
  23472. dist = vectlg + uTotalDistance[p];
  23473. us[p].push(dist);
  23474. uTotalDistance[p] = dist;
  23475. }
  23476. lg[p] = l + closePathCorr;
  23477. idx[p] = idc;
  23478. idc += (l + closePathCorr);
  23479. }
  23480. // vertical distances (v)
  23481. var path1;
  23482. var path2;
  23483. var vertex1;
  23484. var vertex2;
  23485. for (i = 0; i < minlg + closePathCorr; i++) {
  23486. vTotalDistance[i] = 0;
  23487. vs[i] = [0];
  23488. for (p = 0; p < pathArray.length - 1; p++) {
  23489. path1 = pathArray[p];
  23490. path2 = pathArray[p + 1];
  23491. if (i === minlg) {
  23492. vertex1 = path1[0];
  23493. vertex2 = path2[0];
  23494. }
  23495. else {
  23496. vertex1 = path1[i];
  23497. vertex2 = path2[i];
  23498. }
  23499. vectlg = vertex2.subtract(vertex1).length();
  23500. dist = vectlg + vTotalDistance[i];
  23501. vs[i].push(dist);
  23502. vTotalDistance[i] = dist;
  23503. }
  23504. if (closeArray) {
  23505. path1 = pathArray[p];
  23506. path2 = pathArray[0];
  23507. if (i === minlg) {
  23508. vertex2 = path2[0];
  23509. }
  23510. vectlg = vertex2.subtract(vertex1).length();
  23511. dist = vectlg + vTotalDistance[i];
  23512. vTotalDistance[i] = dist;
  23513. }
  23514. }
  23515. // uvs
  23516. var u;
  23517. var v;
  23518. if (customUV) {
  23519. for (p = 0; p < customUV.length; p++) {
  23520. uvs.push(customUV[p].x, customUV[p].y);
  23521. }
  23522. }
  23523. else {
  23524. for (p = 0; p < pathArray.length; p++) {
  23525. for (i = 0; i < minlg + closePathCorr; i++) {
  23526. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  23527. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  23528. if (invertUV) {
  23529. uvs.push(v, u);
  23530. }
  23531. else {
  23532. uvs.push(u, v);
  23533. }
  23534. }
  23535. }
  23536. }
  23537. // indices
  23538. p = 0; // path index
  23539. var pi = 0; // positions array index
  23540. var l1 = lg[p] - 1; // path1 length
  23541. var l2 = lg[p + 1] - 1; // path2 length
  23542. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23543. var shft = idx[1] - idx[0]; // shift
  23544. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23545. while (pi <= min && p < path1nb) {
  23546. // 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
  23547. indices.push(pi, pi + shft, pi + 1);
  23548. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23549. pi += 1;
  23550. if (pi === min) {
  23551. p++;
  23552. if (p === lg.length - 1) {
  23553. shft = idx[0] - idx[p];
  23554. l1 = lg[p] - 1;
  23555. l2 = lg[0] - 1;
  23556. }
  23557. else {
  23558. shft = idx[p + 1] - idx[p];
  23559. l1 = lg[p] - 1;
  23560. l2 = lg[p + 1] - 1;
  23561. }
  23562. pi = idx[p];
  23563. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23564. }
  23565. }
  23566. // normals
  23567. VertexData.ComputeNormals(positions, indices, normals);
  23568. if (closePath) {
  23569. var indexFirst = 0;
  23570. var indexLast = 0;
  23571. for (p = 0; p < pathArray.length; p++) {
  23572. indexFirst = idx[p] * 3;
  23573. if (p + 1 < pathArray.length) {
  23574. indexLast = (idx[p + 1] - 1) * 3;
  23575. }
  23576. else {
  23577. indexLast = normals.length - 3;
  23578. }
  23579. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23580. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23581. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23582. normals[indexLast] = normals[indexFirst];
  23583. normals[indexLast + 1] = normals[indexFirst + 1];
  23584. normals[indexLast + 2] = normals[indexFirst + 2];
  23585. }
  23586. }
  23587. // sides
  23588. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23589. // Colors
  23590. if (customColors) {
  23591. var colors = new Float32Array(customColors.length * 4);
  23592. for (var c = 0; c < customColors.length; c++) {
  23593. colors[c * 4] = customColors[c].r;
  23594. colors[c * 4 + 1] = customColors[c].g;
  23595. colors[c * 4 + 2] = customColors[c].b;
  23596. colors[c * 4 + 3] = customColors[c].a;
  23597. }
  23598. }
  23599. // Result
  23600. var vertexData = new VertexData();
  23601. var positions32 = new Float32Array(positions);
  23602. var normals32 = new Float32Array(normals);
  23603. var uvs32 = new Float32Array(uvs);
  23604. vertexData.indices = indices;
  23605. vertexData.positions = positions32;
  23606. vertexData.normals = normals32;
  23607. vertexData.uvs = uvs32;
  23608. if (customColors) {
  23609. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  23610. }
  23611. if (closePath) {
  23612. vertexData._idx = idx;
  23613. }
  23614. return vertexData;
  23615. };
  23616. /**
  23617. * Creates the VertexData of the Box.
  23618. */
  23619. VertexData.CreateBox = function (options) {
  23620. var normalsSource = [
  23621. new BABYLON.Vector3(0, 0, 1),
  23622. new BABYLON.Vector3(0, 0, -1),
  23623. new BABYLON.Vector3(1, 0, 0),
  23624. new BABYLON.Vector3(-1, 0, 0),
  23625. new BABYLON.Vector3(0, 1, 0),
  23626. new BABYLON.Vector3(0, -1, 0)
  23627. ];
  23628. var indices = [];
  23629. var positions = [];
  23630. var normals = [];
  23631. var uvs = [];
  23632. var width = options.width || options.size || 1;
  23633. var height = options.height || options.size || 1;
  23634. var depth = options.depth || options.size || 1;
  23635. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23636. var faceUV = options.faceUV || new Array(6);
  23637. var faceColors = options.faceColors;
  23638. var colors = [];
  23639. // default face colors and UV if undefined
  23640. for (var f = 0; f < 6; f++) {
  23641. if (faceUV[f] === undefined) {
  23642. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23643. }
  23644. if (faceColors && faceColors[f] === undefined) {
  23645. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23646. }
  23647. }
  23648. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23649. // Create each face in turn.
  23650. for (var index = 0; index < normalsSource.length; index++) {
  23651. var normal = normalsSource[index];
  23652. // Get two vectors perpendicular to the face normal and to each other.
  23653. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23654. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23655. // Six indices (two triangles) per face.
  23656. var verticesLength = positions.length / 3;
  23657. indices.push(verticesLength);
  23658. indices.push(verticesLength + 1);
  23659. indices.push(verticesLength + 2);
  23660. indices.push(verticesLength);
  23661. indices.push(verticesLength + 2);
  23662. indices.push(verticesLength + 3);
  23663. // Four vertices per face.
  23664. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23665. positions.push(vertex.x, vertex.y, vertex.z);
  23666. normals.push(normal.x, normal.y, normal.z);
  23667. uvs.push(faceUV[index].z, faceUV[index].w);
  23668. if (faceColors) {
  23669. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23670. }
  23671. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23672. positions.push(vertex.x, vertex.y, vertex.z);
  23673. normals.push(normal.x, normal.y, normal.z);
  23674. uvs.push(faceUV[index].x, faceUV[index].w);
  23675. if (faceColors) {
  23676. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23677. }
  23678. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23679. positions.push(vertex.x, vertex.y, vertex.z);
  23680. normals.push(normal.x, normal.y, normal.z);
  23681. uvs.push(faceUV[index].x, faceUV[index].y);
  23682. if (faceColors) {
  23683. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23684. }
  23685. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23686. positions.push(vertex.x, vertex.y, vertex.z);
  23687. normals.push(normal.x, normal.y, normal.z);
  23688. uvs.push(faceUV[index].z, faceUV[index].y);
  23689. if (faceColors) {
  23690. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23691. }
  23692. }
  23693. // sides
  23694. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23695. // Result
  23696. var vertexData = new VertexData();
  23697. vertexData.indices = indices;
  23698. vertexData.positions = positions;
  23699. vertexData.normals = normals;
  23700. vertexData.uvs = uvs;
  23701. if (faceColors) {
  23702. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23703. vertexData.colors = totalColors;
  23704. }
  23705. return vertexData;
  23706. };
  23707. /**
  23708. * Creates the VertexData of the Sphere.
  23709. */
  23710. VertexData.CreateSphere = function (options) {
  23711. var segments = options.segments || 32;
  23712. var diameterX = options.diameterX || options.diameter || 1;
  23713. var diameterY = options.diameterY || options.diameter || 1;
  23714. var diameterZ = options.diameterZ || options.diameter || 1;
  23715. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23716. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23717. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23718. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23719. var totalZRotationSteps = 2 + segments;
  23720. var totalYRotationSteps = 2 * totalZRotationSteps;
  23721. var indices = [];
  23722. var positions = [];
  23723. var normals = [];
  23724. var uvs = [];
  23725. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23726. var normalizedZ = zRotationStep / totalZRotationSteps;
  23727. var angleZ = normalizedZ * Math.PI * slice;
  23728. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23729. var normalizedY = yRotationStep / totalYRotationSteps;
  23730. var angleY = normalizedY * Math.PI * 2 * arc;
  23731. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23732. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23733. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23734. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23735. var vertex = complete.multiply(radius);
  23736. var normal = complete.divide(radius).normalize();
  23737. positions.push(vertex.x, vertex.y, vertex.z);
  23738. normals.push(normal.x, normal.y, normal.z);
  23739. uvs.push(normalizedY, normalizedZ);
  23740. }
  23741. if (zRotationStep > 0) {
  23742. var verticesCount = positions.length / 3;
  23743. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23744. indices.push((firstIndex));
  23745. indices.push((firstIndex + 1));
  23746. indices.push(firstIndex + totalYRotationSteps + 1);
  23747. indices.push((firstIndex + totalYRotationSteps + 1));
  23748. indices.push((firstIndex + 1));
  23749. indices.push((firstIndex + totalYRotationSteps + 2));
  23750. }
  23751. }
  23752. }
  23753. // Sides
  23754. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23755. // Result
  23756. var vertexData = new VertexData();
  23757. vertexData.indices = indices;
  23758. vertexData.positions = positions;
  23759. vertexData.normals = normals;
  23760. vertexData.uvs = uvs;
  23761. return vertexData;
  23762. };
  23763. /**
  23764. * Creates the VertexData of the Cylinder or Cone.
  23765. */
  23766. VertexData.CreateCylinder = function (options) {
  23767. var height = options.height || 2;
  23768. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23769. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  23770. var tessellation = options.tessellation || 24;
  23771. var subdivisions = options.subdivisions || 1;
  23772. var hasRings = options.hasRings;
  23773. var enclose = options.enclose;
  23774. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23775. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23776. var faceUV = options.faceUV || new Array(3);
  23777. var faceColors = options.faceColors;
  23778. // default face colors and UV if undefined
  23779. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  23780. var ringNb = (hasRings) ? subdivisions : 1;
  23781. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  23782. var f;
  23783. for (f = 0; f < surfaceNb; f++) {
  23784. if (faceColors && faceColors[f] === undefined) {
  23785. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23786. }
  23787. }
  23788. for (f = 0; f < surfaceNb; f++) {
  23789. if (faceUV && faceUV[f] === undefined) {
  23790. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23791. }
  23792. }
  23793. var indices = [];
  23794. var positions = [];
  23795. var normals = [];
  23796. var uvs = [];
  23797. var colors = [];
  23798. var angle_step = Math.PI * 2 * arc / tessellation;
  23799. var angle;
  23800. var h;
  23801. var radius;
  23802. var tan = (diameterBottom - diameterTop) / 2 / height;
  23803. var ringVertex = BABYLON.Vector3.Zero();
  23804. var ringNormal = BABYLON.Vector3.Zero();
  23805. var ringFirstVertex = BABYLON.Vector3.Zero();
  23806. var ringFirstNormal = BABYLON.Vector3.Zero();
  23807. var quadNormal = BABYLON.Vector3.Zero();
  23808. var Y = BABYLON.Axis.Y;
  23809. // positions, normals, uvs
  23810. var i;
  23811. var j;
  23812. var r;
  23813. var ringIdx = 1;
  23814. var s = 1; // surface index
  23815. var cs = 0;
  23816. var v = 0;
  23817. for (i = 0; i <= subdivisions; i++) {
  23818. h = i / subdivisions;
  23819. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23820. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  23821. for (r = 0; r < ringIdx; r++) {
  23822. if (hasRings) {
  23823. s += r;
  23824. }
  23825. if (enclose) {
  23826. s += 2 * r;
  23827. }
  23828. for (j = 0; j <= tessellation; j++) {
  23829. angle = j * angle_step;
  23830. // position
  23831. ringVertex.x = Math.cos(-angle) * radius;
  23832. ringVertex.y = -height / 2 + h * height;
  23833. ringVertex.z = Math.sin(-angle) * radius;
  23834. // normal
  23835. if (diameterTop === 0 && i === subdivisions) {
  23836. // if no top cap, reuse former normals
  23837. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23838. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23839. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23840. }
  23841. else {
  23842. ringNormal.x = ringVertex.x;
  23843. ringNormal.z = ringVertex.z;
  23844. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23845. ringNormal.normalize();
  23846. }
  23847. // keep first ring vertex values for enclose
  23848. if (j === 0) {
  23849. ringFirstVertex.copyFrom(ringVertex);
  23850. ringFirstNormal.copyFrom(ringNormal);
  23851. }
  23852. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23853. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23854. if (hasRings) {
  23855. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  23856. }
  23857. else {
  23858. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  23859. }
  23860. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  23861. if (faceColors) {
  23862. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  23863. }
  23864. }
  23865. // if enclose, add four vertices and their dedicated normals
  23866. if (arc !== 1 && enclose) {
  23867. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23868. positions.push(0, ringVertex.y, 0);
  23869. positions.push(0, ringVertex.y, 0);
  23870. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  23871. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  23872. quadNormal.normalize();
  23873. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23874. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  23875. quadNormal.normalize();
  23876. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23877. if (hasRings) {
  23878. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  23879. }
  23880. else {
  23881. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  23882. }
  23883. uvs.push(faceUV[s + 1].x, v);
  23884. uvs.push(faceUV[s + 1].z, v);
  23885. if (hasRings) {
  23886. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  23887. }
  23888. else {
  23889. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  23890. }
  23891. uvs.push(faceUV[s + 2].x, v);
  23892. uvs.push(faceUV[s + 2].z, v);
  23893. if (faceColors) {
  23894. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23895. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23896. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23897. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23898. }
  23899. }
  23900. if (cs !== s) {
  23901. cs = s;
  23902. }
  23903. }
  23904. }
  23905. // indices
  23906. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  23907. var s;
  23908. i = 0;
  23909. for (s = 0; s < subdivisions; s++) {
  23910. for (j = 0; j < tessellation; j++) {
  23911. var i0 = i * (e + 1) + j;
  23912. var i1 = (i + 1) * (e + 1) + j;
  23913. var i2 = i * (e + 1) + (j + 1);
  23914. var i3 = (i + 1) * (e + 1) + (j + 1);
  23915. indices.push(i0, i1, i2);
  23916. indices.push(i3, i2, i1);
  23917. }
  23918. if (arc !== 1 && enclose) {
  23919. indices.push(i0 + 2, i1 + 2, i2 + 2);
  23920. indices.push(i3 + 2, i2 + 2, i1 + 2);
  23921. indices.push(i0 + 4, i1 + 4, i2 + 4);
  23922. indices.push(i3 + 4, i2 + 4, i1 + 4);
  23923. }
  23924. i = (hasRings) ? (i + 2) : (i + 1);
  23925. }
  23926. // Caps
  23927. var createCylinderCap = function (isTop) {
  23928. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23929. if (radius === 0) {
  23930. return;
  23931. }
  23932. // Cap positions, normals & uvs
  23933. var angle;
  23934. var circleVector;
  23935. var i;
  23936. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  23937. var c;
  23938. if (faceColors) {
  23939. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  23940. }
  23941. // cap center
  23942. var vbase = positions.length / 3;
  23943. var offset = isTop ? height / 2 : -height / 2;
  23944. var center = new BABYLON.Vector3(0, offset, 0);
  23945. positions.push(center.x, center.y, center.z);
  23946. normals.push(0, isTop ? 1 : -1, 0);
  23947. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23948. if (faceColors) {
  23949. colors.push(c.r, c.g, c.b, c.a);
  23950. }
  23951. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23952. for (i = 0; i <= tessellation; i++) {
  23953. angle = Math.PI * 2 * i * arc / tessellation;
  23954. var cos = Math.cos(-angle);
  23955. var sin = Math.sin(-angle);
  23956. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23957. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23958. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23959. normals.push(0, isTop ? 1 : -1, 0);
  23960. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23961. if (faceColors) {
  23962. colors.push(c.r, c.g, c.b, c.a);
  23963. }
  23964. }
  23965. // Cap indices
  23966. for (i = 0; i < tessellation; i++) {
  23967. if (!isTop) {
  23968. indices.push(vbase);
  23969. indices.push(vbase + (i + 1));
  23970. indices.push(vbase + (i + 2));
  23971. }
  23972. else {
  23973. indices.push(vbase);
  23974. indices.push(vbase + (i + 2));
  23975. indices.push(vbase + (i + 1));
  23976. }
  23977. }
  23978. };
  23979. // add caps to geometry
  23980. createCylinderCap(false);
  23981. createCylinderCap(true);
  23982. // Sides
  23983. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23984. var vertexData = new VertexData();
  23985. vertexData.indices = indices;
  23986. vertexData.positions = positions;
  23987. vertexData.normals = normals;
  23988. vertexData.uvs = uvs;
  23989. if (faceColors) {
  23990. vertexData.colors = colors;
  23991. }
  23992. return vertexData;
  23993. };
  23994. /**
  23995. * Creates the VertexData of the Torus.
  23996. */
  23997. VertexData.CreateTorus = function (options) {
  23998. var indices = [];
  23999. var positions = [];
  24000. var normals = [];
  24001. var uvs = [];
  24002. var diameter = options.diameter || 1;
  24003. var thickness = options.thickness || 0.5;
  24004. var tessellation = options.tessellation || 16;
  24005. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24006. var stride = tessellation + 1;
  24007. for (var i = 0; i <= tessellation; i++) {
  24008. var u = i / tessellation;
  24009. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24010. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24011. for (var j = 0; j <= tessellation; j++) {
  24012. var v = 1 - j / tessellation;
  24013. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24014. var dx = Math.cos(innerAngle);
  24015. var dy = Math.sin(innerAngle);
  24016. // Create a vertex.
  24017. var normal = new BABYLON.Vector3(dx, dy, 0);
  24018. var position = normal.scale(thickness / 2);
  24019. var textureCoordinate = new BABYLON.Vector2(u, v);
  24020. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24021. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24022. positions.push(position.x, position.y, position.z);
  24023. normals.push(normal.x, normal.y, normal.z);
  24024. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24025. // And create indices for two triangles.
  24026. var nextI = (i + 1) % stride;
  24027. var nextJ = (j + 1) % stride;
  24028. indices.push(i * stride + j);
  24029. indices.push(i * stride + nextJ);
  24030. indices.push(nextI * stride + j);
  24031. indices.push(i * stride + nextJ);
  24032. indices.push(nextI * stride + nextJ);
  24033. indices.push(nextI * stride + j);
  24034. }
  24035. }
  24036. // Sides
  24037. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24038. // Result
  24039. var vertexData = new VertexData();
  24040. vertexData.indices = indices;
  24041. vertexData.positions = positions;
  24042. vertexData.normals = normals;
  24043. vertexData.uvs = uvs;
  24044. return vertexData;
  24045. };
  24046. /**
  24047. * Creates the VertexData of the LineSystem.
  24048. */
  24049. VertexData.CreateLineSystem = function (options) {
  24050. var indices = [];
  24051. var positions = [];
  24052. var lines = options.lines;
  24053. var idx = 0;
  24054. for (var l = 0; l < lines.length; l++) {
  24055. var points = lines[l];
  24056. for (var index = 0; index < points.length; index++) {
  24057. positions.push(points[index].x, points[index].y, points[index].z);
  24058. if (index > 0) {
  24059. indices.push(idx - 1);
  24060. indices.push(idx);
  24061. }
  24062. idx++;
  24063. }
  24064. }
  24065. var vertexData = new VertexData();
  24066. vertexData.indices = indices;
  24067. vertexData.positions = positions;
  24068. return vertexData;
  24069. };
  24070. /**
  24071. * Create the VertexData of the DashedLines.
  24072. */
  24073. VertexData.CreateDashedLines = function (options) {
  24074. var dashSize = options.dashSize || 3;
  24075. var gapSize = options.gapSize || 1;
  24076. var dashNb = options.dashNb || 200;
  24077. var points = options.points;
  24078. var positions = new Array();
  24079. var indices = new Array();
  24080. var curvect = BABYLON.Vector3.Zero();
  24081. var lg = 0;
  24082. var nb = 0;
  24083. var shft = 0;
  24084. var dashshft = 0;
  24085. var curshft = 0;
  24086. var idx = 0;
  24087. var i = 0;
  24088. for (i = 0; i < points.length - 1; i++) {
  24089. points[i + 1].subtractToRef(points[i], curvect);
  24090. lg += curvect.length();
  24091. }
  24092. shft = lg / dashNb;
  24093. dashshft = dashSize * shft / (dashSize + gapSize);
  24094. for (i = 0; i < points.length - 1; i++) {
  24095. points[i + 1].subtractToRef(points[i], curvect);
  24096. nb = Math.floor(curvect.length() / shft);
  24097. curvect.normalize();
  24098. for (var j = 0; j < nb; j++) {
  24099. curshft = shft * j;
  24100. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  24101. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  24102. indices.push(idx, idx + 1);
  24103. idx += 2;
  24104. }
  24105. }
  24106. // Result
  24107. var vertexData = new VertexData();
  24108. vertexData.positions = positions;
  24109. vertexData.indices = indices;
  24110. return vertexData;
  24111. };
  24112. /**
  24113. * Creates the VertexData of the Ground.
  24114. */
  24115. VertexData.CreateGround = function (options) {
  24116. var indices = [];
  24117. var positions = [];
  24118. var normals = [];
  24119. var uvs = [];
  24120. var row, col;
  24121. var width = options.width || 1;
  24122. var height = options.height || 1;
  24123. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  24124. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  24125. for (row = 0; row <= subdivisionsY; row++) {
  24126. for (col = 0; col <= subdivisionsX; col++) {
  24127. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  24128. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24129. positions.push(position.x, position.y, position.z);
  24130. normals.push(normal.x, normal.y, normal.z);
  24131. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  24132. }
  24133. }
  24134. for (row = 0; row < subdivisionsY; row++) {
  24135. for (col = 0; col < subdivisionsX; col++) {
  24136. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  24137. indices.push(col + 1 + row * (subdivisionsX + 1));
  24138. indices.push(col + row * (subdivisionsX + 1));
  24139. indices.push(col + (row + 1) * (subdivisionsX + 1));
  24140. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  24141. indices.push(col + row * (subdivisionsX + 1));
  24142. }
  24143. }
  24144. // Result
  24145. var vertexData = new VertexData();
  24146. vertexData.indices = indices;
  24147. vertexData.positions = positions;
  24148. vertexData.normals = normals;
  24149. vertexData.uvs = uvs;
  24150. return vertexData;
  24151. };
  24152. /**
  24153. * Creates the VertexData of the TiledGround.
  24154. */
  24155. VertexData.CreateTiledGround = function (options) {
  24156. var xmin = options.xmin || -1.0;
  24157. var zmin = options.zmin || -1.0;
  24158. var xmax = options.xmax || 1.0;
  24159. var zmax = options.zmax || 1.0;
  24160. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24161. var precision = options.precision || { w: 1, h: 1 };
  24162. var indices = [];
  24163. var positions = [];
  24164. var normals = [];
  24165. var uvs = [];
  24166. var row, col, tileRow, tileCol;
  24167. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  24168. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24169. precision.w = (precision.w < 1) ? 1 : precision.w;
  24170. precision.h = (precision.h < 1) ? 1 : precision.h;
  24171. var tileSize = {
  24172. 'w': (xmax - xmin) / subdivisions.w,
  24173. 'h': (zmax - zmin) / subdivisions.h
  24174. };
  24175. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24176. // Indices
  24177. var base = positions.length / 3;
  24178. var rowLength = precision.w + 1;
  24179. for (row = 0; row < precision.h; row++) {
  24180. for (col = 0; col < precision.w; col++) {
  24181. var square = [
  24182. base + col + row * rowLength,
  24183. base + (col + 1) + row * rowLength,
  24184. base + (col + 1) + (row + 1) * rowLength,
  24185. base + col + (row + 1) * rowLength
  24186. ];
  24187. indices.push(square[1]);
  24188. indices.push(square[2]);
  24189. indices.push(square[3]);
  24190. indices.push(square[0]);
  24191. indices.push(square[1]);
  24192. indices.push(square[3]);
  24193. }
  24194. }
  24195. // Position, normals and uvs
  24196. var position = BABYLON.Vector3.Zero();
  24197. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24198. for (row = 0; row <= precision.h; row++) {
  24199. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24200. for (col = 0; col <= precision.w; col++) {
  24201. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24202. position.y = 0;
  24203. positions.push(position.x, position.y, position.z);
  24204. normals.push(normal.x, normal.y, normal.z);
  24205. uvs.push(col / precision.w, row / precision.h);
  24206. }
  24207. }
  24208. }
  24209. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24210. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24211. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24212. }
  24213. }
  24214. // Result
  24215. var vertexData = new VertexData();
  24216. vertexData.indices = indices;
  24217. vertexData.positions = positions;
  24218. vertexData.normals = normals;
  24219. vertexData.uvs = uvs;
  24220. return vertexData;
  24221. };
  24222. /**
  24223. * Creates the VertexData of the Ground designed from a heightmap.
  24224. */
  24225. VertexData.CreateGroundFromHeightMap = function (options) {
  24226. var indices = [];
  24227. var positions = [];
  24228. var normals = [];
  24229. var uvs = [];
  24230. var row, col;
  24231. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  24232. // Vertices
  24233. for (row = 0; row <= options.subdivisions; row++) {
  24234. for (col = 0; col <= options.subdivisions; col++) {
  24235. 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));
  24236. // Compute height
  24237. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  24238. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  24239. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  24240. var r = options.buffer[pos] / 255.0;
  24241. var g = options.buffer[pos + 1] / 255.0;
  24242. var b = options.buffer[pos + 2] / 255.0;
  24243. var gradient = r * filter.r + g * filter.g + b * filter.b;
  24244. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  24245. // Add vertex
  24246. positions.push(position.x, position.y, position.z);
  24247. normals.push(0, 0, 0);
  24248. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  24249. }
  24250. }
  24251. // Indices
  24252. for (row = 0; row < options.subdivisions; row++) {
  24253. for (col = 0; col < options.subdivisions; col++) {
  24254. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24255. indices.push(col + 1 + row * (options.subdivisions + 1));
  24256. indices.push(col + row * (options.subdivisions + 1));
  24257. indices.push(col + (row + 1) * (options.subdivisions + 1));
  24258. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24259. indices.push(col + row * (options.subdivisions + 1));
  24260. }
  24261. }
  24262. // Normals
  24263. VertexData.ComputeNormals(positions, indices, normals);
  24264. // Result
  24265. var vertexData = new VertexData();
  24266. vertexData.indices = indices;
  24267. vertexData.positions = positions;
  24268. vertexData.normals = normals;
  24269. vertexData.uvs = uvs;
  24270. return vertexData;
  24271. };
  24272. /**
  24273. * Creates the VertexData of the Plane.
  24274. */
  24275. VertexData.CreatePlane = function (options) {
  24276. var indices = [];
  24277. var positions = [];
  24278. var normals = [];
  24279. var uvs = [];
  24280. var width = options.width || options.size || 1;
  24281. var height = options.height || options.size || 1;
  24282. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24283. // Vertices
  24284. var halfWidth = width / 2.0;
  24285. var halfHeight = height / 2.0;
  24286. positions.push(-halfWidth, -halfHeight, 0);
  24287. normals.push(0, 0, -1.0);
  24288. uvs.push(0.0, 0.0);
  24289. positions.push(halfWidth, -halfHeight, 0);
  24290. normals.push(0, 0, -1.0);
  24291. uvs.push(1.0, 0.0);
  24292. positions.push(halfWidth, halfHeight, 0);
  24293. normals.push(0, 0, -1.0);
  24294. uvs.push(1.0, 1.0);
  24295. positions.push(-halfWidth, halfHeight, 0);
  24296. normals.push(0, 0, -1.0);
  24297. uvs.push(0.0, 1.0);
  24298. // Indices
  24299. indices.push(0);
  24300. indices.push(1);
  24301. indices.push(2);
  24302. indices.push(0);
  24303. indices.push(2);
  24304. indices.push(3);
  24305. // Sides
  24306. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24307. // Result
  24308. var vertexData = new VertexData();
  24309. vertexData.indices = indices;
  24310. vertexData.positions = positions;
  24311. vertexData.normals = normals;
  24312. vertexData.uvs = uvs;
  24313. return vertexData;
  24314. };
  24315. /**
  24316. * Creates the VertexData of the Disc or regular Polygon.
  24317. */
  24318. VertexData.CreateDisc = function (options) {
  24319. var positions = [];
  24320. var indices = [];
  24321. var normals = [];
  24322. var uvs = [];
  24323. var radius = options.radius || 0.5;
  24324. var tessellation = options.tessellation || 64;
  24325. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24326. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24327. // positions and uvs
  24328. positions.push(0, 0, 0); // disc center first
  24329. uvs.push(0.5, 0.5);
  24330. var theta = Math.PI * 2 * arc;
  24331. var step = theta / tessellation;
  24332. for (var a = 0; a < theta; a += step) {
  24333. var x = Math.cos(a);
  24334. var y = Math.sin(a);
  24335. var u = (x + 1) / 2;
  24336. var v = (1 - y) / 2;
  24337. positions.push(radius * x, radius * y, 0);
  24338. uvs.push(u, v);
  24339. }
  24340. if (arc === 1) {
  24341. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24342. uvs.push(uvs[2], uvs[3]);
  24343. }
  24344. //indices
  24345. var vertexNb = positions.length / 3;
  24346. for (var i = 1; i < vertexNb - 1; i++) {
  24347. indices.push(i + 1, 0, i);
  24348. }
  24349. // result
  24350. VertexData.ComputeNormals(positions, indices, normals);
  24351. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24352. var vertexData = new VertexData();
  24353. vertexData.indices = indices;
  24354. vertexData.positions = positions;
  24355. vertexData.normals = normals;
  24356. vertexData.uvs = uvs;
  24357. return vertexData;
  24358. };
  24359. /**
  24360. * Creates the VertexData of the IcoSphere.
  24361. */
  24362. VertexData.CreateIcoSphere = function (options) {
  24363. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24364. var radius = options.radius || 1;
  24365. var flat = (options.flat === undefined) ? true : options.flat;
  24366. var subdivisions = options.subdivisions || 4;
  24367. var radiusX = options.radiusX || radius;
  24368. var radiusY = options.radiusY || radius;
  24369. var radiusZ = options.radiusZ || radius;
  24370. var t = (1 + Math.sqrt(5)) / 2;
  24371. // 12 vertex x,y,z
  24372. var ico_vertices = [
  24373. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24374. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24375. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24376. ];
  24377. // index of 3 vertex makes a face of icopshere
  24378. var ico_indices = [
  24379. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  24380. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  24381. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  24382. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  24383. ];
  24384. // vertex for uv have aliased position, not for UV
  24385. var vertices_unalias_id = [
  24386. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  24387. // vertex alias
  24388. 0,
  24389. 2,
  24390. 3,
  24391. 3,
  24392. 3,
  24393. 4,
  24394. 7,
  24395. 8,
  24396. 9,
  24397. 9,
  24398. 10,
  24399. 11 // 23: B + 12
  24400. ];
  24401. // uv as integer step (not pixels !)
  24402. var ico_vertexuv = [
  24403. 5, 1, 3, 1, 6, 4, 0, 0,
  24404. 5, 3, 4, 2, 2, 2, 4, 0,
  24405. 2, 0, 1, 1, 6, 0, 6, 2,
  24406. // vertex alias (for same vertex on different faces)
  24407. 0, 4,
  24408. 3, 3,
  24409. 4, 4,
  24410. 3, 1,
  24411. 4, 2,
  24412. 4, 4,
  24413. 0, 2,
  24414. 1, 1,
  24415. 2, 2,
  24416. 3, 3,
  24417. 1, 3,
  24418. 2, 4 // 23: B + 12
  24419. ];
  24420. // Vertices[0, 1, ...9, A, B] : position on UV plane
  24421. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  24422. // First island of uv mapping
  24423. // v = 4h 3+ 2
  24424. // v = 3h 9+ 4
  24425. // v = 2h 9+ 5 B
  24426. // v = 1h 9 1 0
  24427. // v = 0h 3 8 7 A
  24428. // u = 0 1 2 3 4 5 6 *a
  24429. // Second island of uv mapping
  24430. // v = 4h 0+ B+ 4+
  24431. // v = 3h A+ 2+
  24432. // v = 2h 7+ 6 3+
  24433. // v = 1h 8+ 3+
  24434. // v = 0h
  24435. // u = 0 1 2 3 4 5 6 *a
  24436. // Face layout on texture UV mapping
  24437. // ============
  24438. // \ 4 /\ 16 / ======
  24439. // \ / \ / /\ 11 /
  24440. // \/ 7 \/ / \ /
  24441. // ======= / 10 \/
  24442. // /\ 17 /\ =======
  24443. // / \ / \ \ 15 /\
  24444. // / 8 \/ 12 \ \ / \
  24445. // ============ \/ 6 \
  24446. // \ 18 /\ ============
  24447. // \ / \ \ 5 /\ 0 /
  24448. // \/ 13 \ \ / \ /
  24449. // ======= \/ 1 \/
  24450. // =============
  24451. // /\ 19 /\ 2 /\
  24452. // / \ / \ / \
  24453. // / 14 \/ 9 \/ 3 \
  24454. // ===================
  24455. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24456. var ustep = 138 / 1024;
  24457. var vstep = 239 / 1024;
  24458. var uoffset = 60 / 1024;
  24459. var voffset = 26 / 1024;
  24460. // Second island should have margin, not to touch the first island
  24461. // avoid any borderline artefact in pixel rounding
  24462. var island_u_offset = -40 / 1024;
  24463. var island_v_offset = +20 / 1024;
  24464. // face is either island 0 or 1 :
  24465. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  24466. var island = [
  24467. 0, 0, 0, 0, 1,
  24468. 0, 0, 1, 1, 0,
  24469. 0, 0, 1, 1, 0,
  24470. 0, 1, 1, 1, 0 // 15 - 19
  24471. ];
  24472. var indices = [];
  24473. var positions = [];
  24474. var normals = [];
  24475. var uvs = [];
  24476. var current_indice = 0;
  24477. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  24478. var face_vertex_pos = new Array(3);
  24479. var face_vertex_uv = new Array(3);
  24480. var v012;
  24481. for (v012 = 0; v012 < 3; v012++) {
  24482. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  24483. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  24484. }
  24485. // create all with normals
  24486. for (var face = 0; face < 20; face++) {
  24487. // 3 vertex per face
  24488. for (v012 = 0; v012 < 3; v012++) {
  24489. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  24490. var v_id = ico_indices[3 * face + v012];
  24491. // vertex have 3D position (x,y,z)
  24492. 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]);
  24493. // Normalize to get normal, then scale to radius
  24494. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  24495. // uv Coordinates from vertex ID
  24496. 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);
  24497. }
  24498. // Subdivide the face (interpolate pos, norm, uv)
  24499. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  24500. // - norm is linear interpolation of vertex corner normal
  24501. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  24502. // - uv is linear interpolation
  24503. //
  24504. // Topology is as below for sub-divide by 2
  24505. // vertex shown as v0,v1,v2
  24506. // interp index is i1 to progress in range [v0,v1[
  24507. // interp index is i2 to progress in range [v0,v2[
  24508. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  24509. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24510. //
  24511. //
  24512. // i2 v2
  24513. // ^ ^
  24514. // / / \
  24515. // / / \
  24516. // / / \
  24517. // / / (0,1) \
  24518. // / #---------\
  24519. // / / \ (0,0)'/ \
  24520. // / / \ / \
  24521. // / / \ / \
  24522. // / / (0,0) \ / (1,0) \
  24523. // / #---------#---------\
  24524. // v0 v1
  24525. //
  24526. // --------------------> i1
  24527. //
  24528. // interp of (i1,i2):
  24529. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  24530. // along i1 : lerp(x0,x1, i1/(S-i2))
  24531. //
  24532. // centroid of triangle is needed to get help normal computation
  24533. // (c1,c2) are used for centroid location
  24534. var interp_vertex = function (i1, i2, c1, c2) {
  24535. // vertex is interpolated from
  24536. // - face_vertex_pos[0..2]
  24537. // - face_vertex_uv[0..2]
  24538. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  24539. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  24540. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  24541. pos_interp.normalize();
  24542. var vertex_normal;
  24543. if (flat) {
  24544. // in flat mode, recalculate normal as face centroid normal
  24545. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  24546. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  24547. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24548. }
  24549. else {
  24550. // in smooth mode, recalculate normal from each single vertex position
  24551. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  24552. }
  24553. // Vertex normal need correction due to X,Y,Z radius scaling
  24554. vertex_normal.x /= radiusX;
  24555. vertex_normal.y /= radiusY;
  24556. vertex_normal.z /= radiusZ;
  24557. vertex_normal.normalize();
  24558. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24559. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24560. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24561. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  24562. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24563. uvs.push(uv_interp.x, uv_interp.y);
  24564. // push each vertex has member of a face
  24565. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24566. indices.push(current_indice);
  24567. current_indice++;
  24568. };
  24569. for (var i2 = 0; i2 < subdivisions; i2++) {
  24570. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24571. // face : (i1,i2) for /\ :
  24572. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24573. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24574. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24575. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24576. if (i1 + i2 + 1 < subdivisions) {
  24577. // face : (i1,i2)' for \/ :
  24578. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24579. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24580. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24581. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24582. }
  24583. }
  24584. }
  24585. }
  24586. // Sides
  24587. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24588. // Result
  24589. var vertexData = new VertexData();
  24590. vertexData.indices = indices;
  24591. vertexData.positions = positions;
  24592. vertexData.normals = normals;
  24593. vertexData.uvs = uvs;
  24594. return vertexData;
  24595. };
  24596. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24597. /**
  24598. * Creates the VertexData of the Polyhedron.
  24599. */
  24600. VertexData.CreatePolyhedron = function (options) {
  24601. // provided polyhedron types :
  24602. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24603. // 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)
  24604. var polyhedra = [];
  24605. 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]] };
  24606. 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]] };
  24607. polyhedra[2] = {
  24608. 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]],
  24609. 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]]
  24610. };
  24611. polyhedra[3] = {
  24612. 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]],
  24613. 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]]
  24614. };
  24615. polyhedra[4] = {
  24616. 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]],
  24617. 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]]
  24618. };
  24619. 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]] };
  24620. 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]] };
  24621. 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]] };
  24622. 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]] };
  24623. 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]] };
  24624. 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]] };
  24625. 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]] };
  24626. 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]] };
  24627. 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]] };
  24628. polyhedra[14] = {
  24629. 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]],
  24630. 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]]
  24631. };
  24632. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24633. var size = options.size;
  24634. var sizeX = options.sizeX || size || 1;
  24635. var sizeY = options.sizeY || size || 1;
  24636. var sizeZ = options.sizeZ || size || 1;
  24637. var data = options.custom || polyhedra[type];
  24638. var nbfaces = data.face.length;
  24639. var faceUV = options.faceUV || new Array(nbfaces);
  24640. var faceColors = options.faceColors;
  24641. var flat = (options.flat === undefined) ? true : options.flat;
  24642. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24643. var positions = [];
  24644. var indices = [];
  24645. var normals = [];
  24646. var uvs = [];
  24647. var colors = [];
  24648. var index = 0;
  24649. var faceIdx = 0; // face cursor in the array "indexes"
  24650. var indexes = [];
  24651. var i = 0;
  24652. var f = 0;
  24653. var u, v, ang, x, y, tmp;
  24654. // default face colors and UV if undefined
  24655. if (flat) {
  24656. for (f = 0; f < nbfaces; f++) {
  24657. if (faceColors && faceColors[f] === undefined) {
  24658. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24659. }
  24660. if (faceUV && faceUV[f] === undefined) {
  24661. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24662. }
  24663. }
  24664. }
  24665. if (!flat) {
  24666. for (i = 0; i < data.vertex.length; i++) {
  24667. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24668. uvs.push(0, 0);
  24669. }
  24670. for (f = 0; f < nbfaces; f++) {
  24671. for (i = 0; i < data.face[f].length - 2; i++) {
  24672. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24673. }
  24674. }
  24675. }
  24676. else {
  24677. for (f = 0; f < nbfaces; f++) {
  24678. var fl = data.face[f].length; // number of vertices of the current face
  24679. ang = 2 * Math.PI / fl;
  24680. x = 0.5 * Math.tan(ang / 2);
  24681. y = 0.5;
  24682. // positions, uvs, colors
  24683. for (i = 0; i < fl; i++) {
  24684. // positions
  24685. 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);
  24686. indexes.push(index);
  24687. index++;
  24688. // uvs
  24689. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24690. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24691. uvs.push(u, v);
  24692. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24693. y = x * Math.sin(ang) + y * Math.cos(ang);
  24694. x = tmp;
  24695. // colors
  24696. if (faceColors) {
  24697. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24698. }
  24699. }
  24700. // indices from indexes
  24701. for (i = 0; i < fl - 2; i++) {
  24702. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24703. }
  24704. faceIdx += fl;
  24705. }
  24706. }
  24707. VertexData.ComputeNormals(positions, indices, normals);
  24708. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24709. var vertexData = new VertexData();
  24710. vertexData.positions = positions;
  24711. vertexData.indices = indices;
  24712. vertexData.normals = normals;
  24713. vertexData.uvs = uvs;
  24714. if (faceColors && flat) {
  24715. vertexData.colors = colors;
  24716. }
  24717. return vertexData;
  24718. };
  24719. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24720. /**
  24721. * Creates the VertexData of the Torus Knot.
  24722. */
  24723. VertexData.CreateTorusKnot = function (options) {
  24724. var indices = [];
  24725. var positions = [];
  24726. var normals = [];
  24727. var uvs = [];
  24728. var radius = options.radius || 2;
  24729. var tube = options.tube || 0.5;
  24730. var radialSegments = options.radialSegments || 32;
  24731. var tubularSegments = options.tubularSegments || 32;
  24732. var p = options.p || 2;
  24733. var q = options.q || 3;
  24734. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24735. // Helper
  24736. var getPos = function (angle) {
  24737. var cu = Math.cos(angle);
  24738. var su = Math.sin(angle);
  24739. var quOverP = q / p * angle;
  24740. var cs = Math.cos(quOverP);
  24741. var tx = radius * (2 + cs) * 0.5 * cu;
  24742. var ty = radius * (2 + cs) * su * 0.5;
  24743. var tz = radius * Math.sin(quOverP) * 0.5;
  24744. return new BABYLON.Vector3(tx, ty, tz);
  24745. };
  24746. // Vertices
  24747. var i;
  24748. var j;
  24749. for (i = 0; i <= radialSegments; i++) {
  24750. var modI = i % radialSegments;
  24751. var u = modI / radialSegments * 2 * p * Math.PI;
  24752. var p1 = getPos(u);
  24753. var p2 = getPos(u + 0.01);
  24754. var tang = p2.subtract(p1);
  24755. var n = p2.add(p1);
  24756. var bitan = BABYLON.Vector3.Cross(tang, n);
  24757. n = BABYLON.Vector3.Cross(bitan, tang);
  24758. bitan.normalize();
  24759. n.normalize();
  24760. for (j = 0; j < tubularSegments; j++) {
  24761. var modJ = j % tubularSegments;
  24762. var v = modJ / tubularSegments * 2 * Math.PI;
  24763. var cx = -tube * Math.cos(v);
  24764. var cy = tube * Math.sin(v);
  24765. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24766. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24767. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24768. uvs.push(i / radialSegments);
  24769. uvs.push(j / tubularSegments);
  24770. }
  24771. }
  24772. for (i = 0; i < radialSegments; i++) {
  24773. for (j = 0; j < tubularSegments; j++) {
  24774. var jNext = (j + 1) % tubularSegments;
  24775. var a = i * tubularSegments + j;
  24776. var b = (i + 1) * tubularSegments + j;
  24777. var c = (i + 1) * tubularSegments + jNext;
  24778. var d = i * tubularSegments + jNext;
  24779. indices.push(d);
  24780. indices.push(b);
  24781. indices.push(a);
  24782. indices.push(d);
  24783. indices.push(c);
  24784. indices.push(b);
  24785. }
  24786. }
  24787. // Normals
  24788. VertexData.ComputeNormals(positions, indices, normals);
  24789. // Sides
  24790. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24791. // Result
  24792. var vertexData = new VertexData();
  24793. vertexData.indices = indices;
  24794. vertexData.positions = positions;
  24795. vertexData.normals = normals;
  24796. vertexData.uvs = uvs;
  24797. return vertexData;
  24798. };
  24799. // Tools
  24800. /**
  24801. * @param {any} - positions (number[] or Float32Array)
  24802. * @param {any} - indices (number[] or Uint16Array)
  24803. * @param {any} - normals (number[] or Float32Array)
  24804. * options (optional) :
  24805. * facetPositions : optional array of facet positions (vector3)
  24806. * facetNormals : optional array of facet normals (vector3)
  24807. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  24808. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  24809. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  24810. * bbSize : optional bounding box size data, required for facetPartitioning computation
  24811. * bInfo : optional bounding info, required for facetPartitioning computation
  24812. */
  24813. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  24814. // temporary scalar variables
  24815. var index = 0; // facet index
  24816. var p1p2x = 0.0; // p1p2 vector x coordinate
  24817. var p1p2y = 0.0; // p1p2 vector y coordinate
  24818. var p1p2z = 0.0; // p1p2 vector z coordinate
  24819. var p3p2x = 0.0; // p3p2 vector x coordinate
  24820. var p3p2y = 0.0; // p3p2 vector y coordinate
  24821. var p3p2z = 0.0; // p3p2 vector z coordinate
  24822. var faceNormalx = 0.0; // facet normal x coordinate
  24823. var faceNormaly = 0.0; // facet normal y coordinate
  24824. var faceNormalz = 0.0; // facet normal z coordinate
  24825. var length = 0.0; // facet normal length before normalization
  24826. var v1x = 0; // vector1 x index in the positions array
  24827. var v1y = 0; // vector1 y index in the positions array
  24828. var v1z = 0; // vector1 z index in the positions array
  24829. var v2x = 0; // vector2 x index in the positions array
  24830. var v2y = 0; // vector2 y index in the positions array
  24831. var v2z = 0; // vector2 z index in the positions array
  24832. var v3x = 0; // vector3 x index in the positions array
  24833. var v3y = 0; // vector3 y index in the positions array
  24834. var v3z = 0; // vector3 z index in the positions array
  24835. var computeFacetNormals = false;
  24836. var computeFacetPositions = false;
  24837. var computeFacetPartitioning = false;
  24838. if (options) {
  24839. computeFacetNormals = (options.facetNormals) ? true : false;
  24840. computeFacetPositions = (options.facetPositions) ? true : false;
  24841. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  24842. }
  24843. // facetPartitioning reinit if needed
  24844. if (computeFacetPartitioning) {
  24845. var ox = 0; // X partitioning index for facet position
  24846. var oy = 0; // Y partinioning index for facet position
  24847. var oz = 0; // Z partinioning index for facet position
  24848. var b1x = 0; // X partitioning index for facet v1 vertex
  24849. var b1y = 0; // Y partitioning index for facet v1 vertex
  24850. var b1z = 0; // z partitioning index for facet v1 vertex
  24851. var b2x = 0; // X partitioning index for facet v2 vertex
  24852. var b2y = 0; // Y partitioning index for facet v2 vertex
  24853. var b2z = 0; // Z partitioning index for facet v2 vertex
  24854. var b3x = 0; // X partitioning index for facet v3 vertex
  24855. var b3y = 0; // Y partitioning index for facet v3 vertex
  24856. var b3z = 0; // Z partitioning index for facet v3 vertex
  24857. var block_idx_o = 0; // facet barycenter block index
  24858. var block_idx_v1 = 0; // v1 vertex block index
  24859. var block_idx_v2 = 0; // v2 vertex block index
  24860. var block_idx_v3 = 0; // v3 vertex block index
  24861. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  24862. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  24863. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  24864. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  24865. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  24866. var subSq = options.subDiv.max * options.subDiv.max;
  24867. options.facetPartitioning.length = 0;
  24868. }
  24869. // reset the normals
  24870. for (index = 0; index < positions.length; index++) {
  24871. normals[index] = 0.0;
  24872. }
  24873. // Loop : 1 indice triplet = 1 facet
  24874. var nbFaces = indices.length / 3;
  24875. for (index = 0; index < nbFaces; index++) {
  24876. // get the indexes of the coordinates of each vertex of the facet
  24877. v1x = indices[index * 3] * 3;
  24878. v1y = v1x + 1;
  24879. v1z = v1x + 2;
  24880. v2x = indices[index * 3 + 1] * 3;
  24881. v2y = v2x + 1;
  24882. v2z = v2x + 2;
  24883. v3x = indices[index * 3 + 2] * 3;
  24884. v3y = v3x + 1;
  24885. v3z = v3x + 2;
  24886. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  24887. p1p2y = positions[v1y] - positions[v2y];
  24888. p1p2z = positions[v1z] - positions[v2z];
  24889. p3p2x = positions[v3x] - positions[v2x];
  24890. p3p2y = positions[v3y] - positions[v2y];
  24891. p3p2z = positions[v3z] - positions[v2z];
  24892. // compute the face normal with the cross product
  24893. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  24894. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  24895. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  24896. // normalize this normal and store it in the array facetData
  24897. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24898. length = (length === 0) ? 1.0 : length;
  24899. faceNormalx /= length;
  24900. faceNormaly /= length;
  24901. faceNormalz /= length;
  24902. if (computeFacetNormals) {
  24903. options.facetNormals[index].x = faceNormalx;
  24904. options.facetNormals[index].y = faceNormaly;
  24905. options.facetNormals[index].z = faceNormalz;
  24906. }
  24907. if (computeFacetPositions) {
  24908. // compute and the facet barycenter coordinates in the array facetPositions
  24909. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  24910. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  24911. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  24912. }
  24913. if (computeFacetPartitioning) {
  24914. // store the facet indexes in arrays in the main facetPartitioning array :
  24915. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  24916. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  24917. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  24918. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  24919. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  24920. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  24921. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  24922. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  24923. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  24924. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  24925. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  24926. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  24927. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  24928. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  24929. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  24930. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  24931. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  24932. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  24933. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  24934. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  24935. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  24936. // push each facet index in each block containing the vertex
  24937. options.facetPartitioning[block_idx_v1].push(index);
  24938. if (block_idx_v2 != block_idx_v1) {
  24939. options.facetPartitioning[block_idx_v2].push(index);
  24940. }
  24941. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  24942. options.facetPartitioning[block_idx_v3].push(index);
  24943. }
  24944. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  24945. options.facetPartitioning[block_idx_o].push(index);
  24946. }
  24947. }
  24948. // compute the normals anyway
  24949. normals[v1x] += faceNormalx; // accumulate all the normals per face
  24950. normals[v1y] += faceNormaly;
  24951. normals[v1z] += faceNormalz;
  24952. normals[v2x] += faceNormalx;
  24953. normals[v2y] += faceNormaly;
  24954. normals[v2z] += faceNormalz;
  24955. normals[v3x] += faceNormalx;
  24956. normals[v3y] += faceNormaly;
  24957. normals[v3z] += faceNormalz;
  24958. }
  24959. // last normalization of each normal
  24960. for (index = 0; index < normals.length / 3; index++) {
  24961. faceNormalx = normals[index * 3];
  24962. faceNormaly = normals[index * 3 + 1];
  24963. faceNormalz = normals[index * 3 + 2];
  24964. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24965. length = (length === 0) ? 1.0 : length;
  24966. faceNormalx /= length;
  24967. faceNormaly /= length;
  24968. faceNormalz /= length;
  24969. normals[index * 3] = faceNormalx;
  24970. normals[index * 3 + 1] = faceNormaly;
  24971. normals[index * 3 + 2] = faceNormalz;
  24972. }
  24973. };
  24974. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24975. var li = indices.length;
  24976. var ln = normals.length;
  24977. var i;
  24978. var n;
  24979. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24980. switch (sideOrientation) {
  24981. case BABYLON.Mesh.FRONTSIDE:
  24982. // nothing changed
  24983. break;
  24984. case BABYLON.Mesh.BACKSIDE:
  24985. var tmp;
  24986. // indices
  24987. for (i = 0; i < li; i += 3) {
  24988. tmp = indices[i];
  24989. indices[i] = indices[i + 2];
  24990. indices[i + 2] = tmp;
  24991. }
  24992. // normals
  24993. for (n = 0; n < ln; n++) {
  24994. normals[n] = -normals[n];
  24995. }
  24996. break;
  24997. case BABYLON.Mesh.DOUBLESIDE:
  24998. // positions
  24999. var lp = positions.length;
  25000. var l = lp / 3;
  25001. for (var p = 0; p < lp; p++) {
  25002. positions[lp + p] = positions[p];
  25003. }
  25004. // indices
  25005. for (i = 0; i < li; i += 3) {
  25006. indices[i + li] = indices[i + 2] + l;
  25007. indices[i + 1 + li] = indices[i + 1] + l;
  25008. indices[i + 2 + li] = indices[i] + l;
  25009. }
  25010. // normals
  25011. for (n = 0; n < ln; n++) {
  25012. normals[ln + n] = -normals[n];
  25013. }
  25014. // uvs
  25015. var lu = uvs.length;
  25016. for (var u = 0; u < lu; u++) {
  25017. uvs[u + lu] = uvs[u];
  25018. }
  25019. break;
  25020. }
  25021. };
  25022. /**
  25023. * Creates a new VertexData from the imported parameters.
  25024. */
  25025. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  25026. var vertexData = new VertexData();
  25027. // positions
  25028. var positions = parsedVertexData.positions;
  25029. if (positions) {
  25030. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  25031. }
  25032. // normals
  25033. var normals = parsedVertexData.normals;
  25034. if (normals) {
  25035. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  25036. }
  25037. // tangents
  25038. var tangents = parsedVertexData.tangents;
  25039. if (tangents) {
  25040. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  25041. }
  25042. // uvs
  25043. var uvs = parsedVertexData.uvs;
  25044. if (uvs) {
  25045. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  25046. }
  25047. // uv2s
  25048. var uv2s = parsedVertexData.uv2s;
  25049. if (uv2s) {
  25050. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  25051. }
  25052. // uv3s
  25053. var uv3s = parsedVertexData.uv3s;
  25054. if (uv3s) {
  25055. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  25056. }
  25057. // uv4s
  25058. var uv4s = parsedVertexData.uv4s;
  25059. if (uv4s) {
  25060. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  25061. }
  25062. // uv5s
  25063. var uv5s = parsedVertexData.uv5s;
  25064. if (uv5s) {
  25065. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  25066. }
  25067. // uv6s
  25068. var uv6s = parsedVertexData.uv6s;
  25069. if (uv6s) {
  25070. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  25071. }
  25072. // colors
  25073. var colors = parsedVertexData.colors;
  25074. if (colors) {
  25075. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  25076. }
  25077. // matricesIndices
  25078. var matricesIndices = parsedVertexData.matricesIndices;
  25079. if (matricesIndices) {
  25080. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  25081. }
  25082. // matricesWeights
  25083. var matricesWeights = parsedVertexData.matricesWeights;
  25084. if (matricesWeights) {
  25085. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  25086. }
  25087. // indices
  25088. var indices = parsedVertexData.indices;
  25089. if (indices) {
  25090. vertexData.indices = indices;
  25091. }
  25092. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  25093. };
  25094. return VertexData;
  25095. }());
  25096. BABYLON.VertexData = VertexData;
  25097. })(BABYLON || (BABYLON = {}));
  25098. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25099. var BABYLON;
  25100. (function (BABYLON) {
  25101. var Geometry = (function () {
  25102. function Geometry(id, scene, vertexData, updatable, mesh) {
  25103. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25104. this._totalVertices = 0;
  25105. this._isDisposed = false;
  25106. this.id = id;
  25107. this._engine = scene.getEngine();
  25108. this._meshes = [];
  25109. this._scene = scene;
  25110. //Init vertex buffer cache
  25111. this._vertexBuffers = {};
  25112. this._indices = [];
  25113. // vertexData
  25114. if (vertexData) {
  25115. this.setAllVerticesData(vertexData, updatable);
  25116. }
  25117. else {
  25118. this._totalVertices = 0;
  25119. this._indices = [];
  25120. }
  25121. if (this._engine.getCaps().vertexArrayObject) {
  25122. this._vertexArrayObjects = {};
  25123. }
  25124. // applyToMesh
  25125. if (mesh) {
  25126. if (mesh.getClassName() === "LinesMesh") {
  25127. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  25128. this.updateExtend();
  25129. }
  25130. this.applyToMesh(mesh);
  25131. mesh.computeWorldMatrix(true);
  25132. }
  25133. }
  25134. Object.defineProperty(Geometry.prototype, "boundingBias", {
  25135. /**
  25136. * 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
  25137. * @returns The Bias Vector
  25138. */
  25139. get: function () {
  25140. return this._boundingBias;
  25141. },
  25142. set: function (value) {
  25143. if (this._boundingBias && this._boundingBias.equals(value)) {
  25144. return;
  25145. }
  25146. this._boundingBias = value.clone();
  25147. this.updateBoundingInfo(true, null);
  25148. },
  25149. enumerable: true,
  25150. configurable: true
  25151. });
  25152. Object.defineProperty(Geometry.prototype, "extend", {
  25153. get: function () {
  25154. return this._extend;
  25155. },
  25156. enumerable: true,
  25157. configurable: true
  25158. });
  25159. Geometry.prototype.getScene = function () {
  25160. return this._scene;
  25161. };
  25162. Geometry.prototype.getEngine = function () {
  25163. return this._engine;
  25164. };
  25165. Geometry.prototype.isReady = function () {
  25166. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25167. };
  25168. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  25169. get: function () {
  25170. for (var index = 0; index < this._meshes.length; index++) {
  25171. if (!this._meshes[index].doNotSerialize) {
  25172. return false;
  25173. }
  25174. }
  25175. return true;
  25176. },
  25177. enumerable: true,
  25178. configurable: true
  25179. });
  25180. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25181. vertexData.applyToGeometry(this, updatable);
  25182. this.notifyUpdate();
  25183. };
  25184. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25185. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25186. this.setVerticesBuffer(buffer);
  25187. };
  25188. Geometry.prototype.removeVerticesData = function (kind) {
  25189. if (this._vertexBuffers[kind]) {
  25190. this._vertexBuffers[kind].dispose();
  25191. delete this._vertexBuffers[kind];
  25192. }
  25193. };
  25194. Geometry.prototype.setVerticesBuffer = function (buffer) {
  25195. var kind = buffer.getKind();
  25196. if (this._vertexBuffers[kind]) {
  25197. this._vertexBuffers[kind].dispose();
  25198. }
  25199. this._vertexBuffers[kind] = buffer;
  25200. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25201. var data = buffer.getData();
  25202. var stride = buffer.getStrideSize();
  25203. this._totalVertices = data.length / stride;
  25204. this.updateExtend(data, stride);
  25205. var meshes = this._meshes;
  25206. var numOfMeshes = meshes.length;
  25207. for (var index = 0; index < numOfMeshes; index++) {
  25208. var mesh = meshes[index];
  25209. mesh._resetPointsArrayCache();
  25210. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25211. mesh._createGlobalSubMesh();
  25212. mesh.computeWorldMatrix(true);
  25213. }
  25214. }
  25215. this.notifyUpdate(kind);
  25216. if (this._vertexArrayObjects) {
  25217. this._disposeVertexArrayObjects();
  25218. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  25219. }
  25220. };
  25221. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25222. var vertexBuffer = this.getVertexBuffer(kind);
  25223. if (!vertexBuffer) {
  25224. return;
  25225. }
  25226. vertexBuffer.updateDirectly(data, offset);
  25227. this.notifyUpdate(kind);
  25228. };
  25229. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25230. var vertexBuffer = this.getVertexBuffer(kind);
  25231. if (!vertexBuffer) {
  25232. return;
  25233. }
  25234. vertexBuffer.update(data);
  25235. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25236. var stride = vertexBuffer.getStrideSize();
  25237. this._totalVertices = data.length / stride;
  25238. this.updateBoundingInfo(updateExtends, data);
  25239. }
  25240. this.notifyUpdate(kind);
  25241. };
  25242. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  25243. if (updateExtends) {
  25244. this.updateExtend(data);
  25245. }
  25246. var meshes = this._meshes;
  25247. var numOfMeshes = meshes.length;
  25248. for (var index = 0; index < numOfMeshes; index++) {
  25249. var mesh = meshes[index];
  25250. mesh._resetPointsArrayCache();
  25251. if (updateExtends) {
  25252. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25253. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25254. var subMesh = mesh.subMeshes[subIndex];
  25255. subMesh.refreshBoundingInfo();
  25256. }
  25257. }
  25258. }
  25259. };
  25260. Geometry.prototype._bind = function (effect, indexToBind) {
  25261. if (indexToBind === void 0) { indexToBind = undefined; }
  25262. if (indexToBind === undefined) {
  25263. indexToBind = this._indexBuffer;
  25264. }
  25265. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  25266. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  25267. return;
  25268. }
  25269. // Using VAO
  25270. if (!this._vertexArrayObjects[effect.key]) {
  25271. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  25272. }
  25273. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  25274. };
  25275. Geometry.prototype.getTotalVertices = function () {
  25276. if (!this.isReady()) {
  25277. return 0;
  25278. }
  25279. return this._totalVertices;
  25280. };
  25281. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  25282. var vertexBuffer = this.getVertexBuffer(kind);
  25283. if (!vertexBuffer) {
  25284. return null;
  25285. }
  25286. var orig = vertexBuffer.getData();
  25287. if (!copyWhenShared || this._meshes.length === 1) {
  25288. return orig;
  25289. }
  25290. else {
  25291. var len = orig.length;
  25292. var copy = [];
  25293. for (var i = 0; i < len; i++) {
  25294. copy.push(orig[i]);
  25295. }
  25296. return copy;
  25297. }
  25298. };
  25299. Geometry.prototype.getVertexBuffer = function (kind) {
  25300. if (!this.isReady()) {
  25301. return null;
  25302. }
  25303. return this._vertexBuffers[kind];
  25304. };
  25305. Geometry.prototype.getVertexBuffers = function () {
  25306. if (!this.isReady()) {
  25307. return null;
  25308. }
  25309. return this._vertexBuffers;
  25310. };
  25311. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25312. if (!this._vertexBuffers) {
  25313. if (this._delayInfo) {
  25314. return this._delayInfo.indexOf(kind) !== -1;
  25315. }
  25316. return false;
  25317. }
  25318. return this._vertexBuffers[kind] !== undefined;
  25319. };
  25320. Geometry.prototype.getVerticesDataKinds = function () {
  25321. var result = [];
  25322. var kind;
  25323. if (!this._vertexBuffers && this._delayInfo) {
  25324. for (kind in this._delayInfo) {
  25325. result.push(kind);
  25326. }
  25327. }
  25328. else {
  25329. for (kind in this._vertexBuffers) {
  25330. result.push(kind);
  25331. }
  25332. }
  25333. return result;
  25334. };
  25335. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25336. if (this._indexBuffer) {
  25337. this._engine._releaseBuffer(this._indexBuffer);
  25338. }
  25339. this._disposeVertexArrayObjects();
  25340. this._indices = indices;
  25341. if (this._meshes.length !== 0 && this._indices) {
  25342. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25343. }
  25344. if (totalVertices !== undefined) {
  25345. this._totalVertices = totalVertices;
  25346. }
  25347. var meshes = this._meshes;
  25348. var numOfMeshes = meshes.length;
  25349. for (var index = 0; index < numOfMeshes; index++) {
  25350. meshes[index]._createGlobalSubMesh();
  25351. }
  25352. this.notifyUpdate();
  25353. };
  25354. Geometry.prototype.getTotalIndices = function () {
  25355. if (!this.isReady()) {
  25356. return 0;
  25357. }
  25358. return this._indices.length;
  25359. };
  25360. Geometry.prototype.getIndices = function (copyWhenShared) {
  25361. if (!this.isReady()) {
  25362. return null;
  25363. }
  25364. var orig = this._indices;
  25365. if (!copyWhenShared || this._meshes.length === 1) {
  25366. return orig;
  25367. }
  25368. else {
  25369. var len = orig.length;
  25370. var copy = [];
  25371. for (var i = 0; i < len; i++) {
  25372. copy.push(orig[i]);
  25373. }
  25374. return copy;
  25375. }
  25376. };
  25377. Geometry.prototype.getIndexBuffer = function () {
  25378. if (!this.isReady()) {
  25379. return null;
  25380. }
  25381. return this._indexBuffer;
  25382. };
  25383. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  25384. if (!effect) {
  25385. return;
  25386. }
  25387. if (this._vertexArrayObjects[effect.key]) {
  25388. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  25389. delete this._vertexArrayObjects[effect.key];
  25390. }
  25391. };
  25392. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25393. var meshes = this._meshes;
  25394. var index = meshes.indexOf(mesh);
  25395. if (index === -1) {
  25396. return;
  25397. }
  25398. meshes.splice(index, 1);
  25399. mesh._geometry = null;
  25400. if (meshes.length === 0 && shouldDispose) {
  25401. this.dispose();
  25402. }
  25403. };
  25404. Geometry.prototype.applyToMesh = function (mesh) {
  25405. if (mesh._geometry === this) {
  25406. return;
  25407. }
  25408. var previousGeometry = mesh._geometry;
  25409. if (previousGeometry) {
  25410. previousGeometry.releaseForMesh(mesh);
  25411. }
  25412. var meshes = this._meshes;
  25413. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25414. mesh._geometry = this;
  25415. this._scene.pushGeometry(this);
  25416. meshes.push(mesh);
  25417. if (this.isReady()) {
  25418. this._applyToMesh(mesh);
  25419. }
  25420. else {
  25421. mesh._boundingInfo = this._boundingInfo;
  25422. }
  25423. };
  25424. Geometry.prototype.updateExtend = function (data, stride) {
  25425. if (data === void 0) { data = null; }
  25426. if (!data) {
  25427. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  25428. }
  25429. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  25430. };
  25431. Geometry.prototype._applyToMesh = function (mesh) {
  25432. var numOfMeshes = this._meshes.length;
  25433. // vertexBuffers
  25434. for (var kind in this._vertexBuffers) {
  25435. if (numOfMeshes === 1) {
  25436. this._vertexBuffers[kind].create();
  25437. }
  25438. var buffer = this._vertexBuffers[kind].getBuffer();
  25439. if (buffer)
  25440. buffer.references = numOfMeshes;
  25441. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25442. mesh._resetPointsArrayCache();
  25443. if (!this._extend) {
  25444. this.updateExtend(this._vertexBuffers[kind].getData());
  25445. }
  25446. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25447. mesh._createGlobalSubMesh();
  25448. //bounding info was just created again, world matrix should be applied again.
  25449. mesh._updateBoundingInfo();
  25450. }
  25451. }
  25452. // indexBuffer
  25453. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  25454. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25455. }
  25456. if (this._indexBuffer) {
  25457. this._indexBuffer.references = numOfMeshes;
  25458. }
  25459. };
  25460. Geometry.prototype.notifyUpdate = function (kind) {
  25461. if (this.onGeometryUpdated) {
  25462. this.onGeometryUpdated(this, kind);
  25463. }
  25464. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  25465. var mesh = _a[_i];
  25466. mesh._markSubMeshesAsAttributesDirty();
  25467. }
  25468. };
  25469. Geometry.prototype.load = function (scene, onLoaded) {
  25470. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25471. return;
  25472. }
  25473. if (this.isReady()) {
  25474. if (onLoaded) {
  25475. onLoaded();
  25476. }
  25477. return;
  25478. }
  25479. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25480. this._queueLoad(scene, onLoaded);
  25481. };
  25482. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  25483. var _this = this;
  25484. scene._addPendingData(this);
  25485. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25486. _this._delayLoadingFunction(JSON.parse(data), _this);
  25487. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25488. _this._delayInfo = [];
  25489. scene._removePendingData(_this);
  25490. var meshes = _this._meshes;
  25491. var numOfMeshes = meshes.length;
  25492. for (var index = 0; index < numOfMeshes; index++) {
  25493. _this._applyToMesh(meshes[index]);
  25494. }
  25495. if (onLoaded) {
  25496. onLoaded();
  25497. }
  25498. }, function () { }, scene.database);
  25499. };
  25500. /**
  25501. * Invert the geometry to move from a right handed system to a left handed one.
  25502. */
  25503. Geometry.prototype.toLeftHanded = function () {
  25504. // Flip faces
  25505. var tIndices = this.getIndices(false);
  25506. if (tIndices != null && tIndices.length > 0) {
  25507. for (var i = 0; i < tIndices.length; i += 3) {
  25508. var tTemp = tIndices[i + 0];
  25509. tIndices[i + 0] = tIndices[i + 2];
  25510. tIndices[i + 2] = tTemp;
  25511. }
  25512. this.setIndices(tIndices);
  25513. }
  25514. // Negate position.z
  25515. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  25516. if (tPositions != null && tPositions.length > 0) {
  25517. for (var i = 0; i < tPositions.length; i += 3) {
  25518. tPositions[i + 2] = -tPositions[i + 2];
  25519. }
  25520. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  25521. }
  25522. // Negate normal.z
  25523. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  25524. if (tNormals != null && tNormals.length > 0) {
  25525. for (var i = 0; i < tNormals.length; i += 3) {
  25526. tNormals[i + 2] = -tNormals[i + 2];
  25527. }
  25528. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  25529. }
  25530. };
  25531. Geometry.prototype.isDisposed = function () {
  25532. return this._isDisposed;
  25533. };
  25534. Geometry.prototype._disposeVertexArrayObjects = function () {
  25535. if (this._vertexArrayObjects) {
  25536. for (var kind in this._vertexArrayObjects) {
  25537. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  25538. }
  25539. this._vertexArrayObjects = {};
  25540. }
  25541. };
  25542. Geometry.prototype.dispose = function () {
  25543. var meshes = this._meshes;
  25544. var numOfMeshes = meshes.length;
  25545. var index;
  25546. for (index = 0; index < numOfMeshes; index++) {
  25547. this.releaseForMesh(meshes[index]);
  25548. }
  25549. this._meshes = [];
  25550. this._disposeVertexArrayObjects();
  25551. for (var kind in this._vertexBuffers) {
  25552. this._vertexBuffers[kind].dispose();
  25553. }
  25554. this._vertexBuffers = {};
  25555. this._totalVertices = 0;
  25556. if (this._indexBuffer) {
  25557. this._engine._releaseBuffer(this._indexBuffer);
  25558. }
  25559. this._indexBuffer = null;
  25560. this._indices = [];
  25561. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25562. this.delayLoadingFile = null;
  25563. this._delayLoadingFunction = null;
  25564. this._delayInfo = [];
  25565. this._boundingInfo = null;
  25566. this._scene.removeGeometry(this);
  25567. this._isDisposed = true;
  25568. };
  25569. Geometry.prototype.copy = function (id) {
  25570. var vertexData = new BABYLON.VertexData();
  25571. vertexData.indices = [];
  25572. var indices = this.getIndices();
  25573. for (var index = 0; index < indices.length; index++) {
  25574. vertexData.indices.push(indices[index]);
  25575. }
  25576. var updatable = false;
  25577. var stopChecking = false;
  25578. var kind;
  25579. for (kind in this._vertexBuffers) {
  25580. // using slice() to make a copy of the array and not just reference it
  25581. var data = this.getVerticesData(kind);
  25582. if (data instanceof Float32Array) {
  25583. vertexData.set(new Float32Array(data), kind);
  25584. }
  25585. else {
  25586. vertexData.set(data.slice(0), kind);
  25587. }
  25588. if (!stopChecking) {
  25589. updatable = this.getVertexBuffer(kind).isUpdatable();
  25590. stopChecking = !updatable;
  25591. }
  25592. }
  25593. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25594. geometry.delayLoadState = this.delayLoadState;
  25595. geometry.delayLoadingFile = this.delayLoadingFile;
  25596. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25597. for (kind in this._delayInfo) {
  25598. geometry._delayInfo = geometry._delayInfo || [];
  25599. geometry._delayInfo.push(kind);
  25600. }
  25601. // Bounding info
  25602. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25603. return geometry;
  25604. };
  25605. Geometry.prototype.serialize = function () {
  25606. var serializationObject = {};
  25607. serializationObject.id = this.id;
  25608. if (BABYLON.Tags.HasTags(this)) {
  25609. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25610. }
  25611. return serializationObject;
  25612. };
  25613. Geometry.prototype.serializeVerticeData = function () {
  25614. var serializationObject = this.serialize();
  25615. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25616. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25617. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  25618. serializationObject.positions._updatable = true;
  25619. }
  25620. }
  25621. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25622. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25623. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  25624. serializationObject.normals._updatable = true;
  25625. }
  25626. }
  25627. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25628. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25629. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  25630. serializationObject.uvs._updatable = true;
  25631. }
  25632. }
  25633. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25634. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  25635. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  25636. serializationObject.uv2s._updatable = true;
  25637. }
  25638. }
  25639. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25640. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  25641. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  25642. serializationObject.uv3s._updatable = true;
  25643. }
  25644. }
  25645. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25646. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  25647. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  25648. serializationObject.uv4s._updatable = true;
  25649. }
  25650. }
  25651. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25652. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  25653. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  25654. serializationObject.uv5s._updatable = true;
  25655. }
  25656. }
  25657. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25658. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  25659. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  25660. serializationObject.uv6s._updatable = true;
  25661. }
  25662. }
  25663. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25664. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  25665. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  25666. serializationObject.colors._updatable = true;
  25667. }
  25668. }
  25669. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25670. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25671. serializationObject.matricesIndices._isExpanded = true;
  25672. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  25673. serializationObject.matricesIndices._updatable = true;
  25674. }
  25675. }
  25676. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25677. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25678. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  25679. serializationObject.matricesWeights._updatable = true;
  25680. }
  25681. }
  25682. serializationObject.indices = this.getIndices();
  25683. return serializationObject;
  25684. };
  25685. // Statics
  25686. Geometry.ExtractFromMesh = function (mesh, id) {
  25687. var geometry = mesh._geometry;
  25688. if (!geometry) {
  25689. return null;
  25690. }
  25691. return geometry.copy(id);
  25692. };
  25693. /**
  25694. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  25695. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25696. * Be aware Math.random() could cause collisions, but:
  25697. * "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"
  25698. */
  25699. Geometry.RandomId = function () {
  25700. return BABYLON.Tools.RandomId();
  25701. };
  25702. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  25703. var scene = mesh.getScene();
  25704. // Geometry
  25705. var geometryId = parsedGeometry.geometryId;
  25706. if (geometryId) {
  25707. var geometry = scene.getGeometryByID(geometryId);
  25708. if (geometry) {
  25709. geometry.applyToMesh(mesh);
  25710. }
  25711. }
  25712. else if (parsedGeometry instanceof ArrayBuffer) {
  25713. var binaryInfo = mesh._binaryInfo;
  25714. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  25715. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  25716. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  25717. }
  25718. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  25719. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  25720. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  25721. }
  25722. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  25723. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  25724. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  25725. }
  25726. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  25727. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  25728. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  25729. }
  25730. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  25731. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  25732. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  25733. }
  25734. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  25735. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  25736. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  25737. }
  25738. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  25739. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  25740. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  25741. }
  25742. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  25743. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  25744. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  25745. }
  25746. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  25747. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  25748. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  25749. }
  25750. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  25751. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  25752. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  25753. }
  25754. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  25755. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  25756. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  25757. }
  25758. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  25759. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  25760. mesh.setIndices(indicesData);
  25761. }
  25762. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  25763. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  25764. mesh.subMeshes = [];
  25765. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  25766. var materialIndex = subMeshesData[(i * 5) + 0];
  25767. var verticesStart = subMeshesData[(i * 5) + 1];
  25768. var verticesCount = subMeshesData[(i * 5) + 2];
  25769. var indexStart = subMeshesData[(i * 5) + 3];
  25770. var indexCount = subMeshesData[(i * 5) + 4];
  25771. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  25772. }
  25773. }
  25774. }
  25775. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  25776. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  25777. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  25778. if (parsedGeometry.uvs) {
  25779. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  25780. }
  25781. if (parsedGeometry.uvs2) {
  25782. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  25783. }
  25784. if (parsedGeometry.uvs3) {
  25785. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  25786. }
  25787. if (parsedGeometry.uvs4) {
  25788. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  25789. }
  25790. if (parsedGeometry.uvs5) {
  25791. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  25792. }
  25793. if (parsedGeometry.uvs6) {
  25794. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  25795. }
  25796. if (parsedGeometry.colors) {
  25797. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  25798. }
  25799. if (parsedGeometry.matricesIndices) {
  25800. if (!parsedGeometry.matricesIndices._isExpanded) {
  25801. var floatIndices = [];
  25802. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  25803. var matricesIndex = parsedGeometry.matricesIndices[i];
  25804. floatIndices.push(matricesIndex & 0x000000FF);
  25805. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  25806. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  25807. floatIndices.push(matricesIndex >> 24);
  25808. }
  25809. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  25810. }
  25811. else {
  25812. delete parsedGeometry.matricesIndices._isExpanded;
  25813. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  25814. }
  25815. }
  25816. if (parsedGeometry.matricesIndicesExtra) {
  25817. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  25818. var floatIndices = [];
  25819. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  25820. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  25821. floatIndices.push(matricesIndex & 0x000000FF);
  25822. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  25823. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  25824. floatIndices.push(matricesIndex >> 24);
  25825. }
  25826. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  25827. }
  25828. else {
  25829. delete parsedGeometry.matricesIndices._isExpanded;
  25830. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  25831. }
  25832. }
  25833. if (parsedGeometry.matricesWeights) {
  25834. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  25835. }
  25836. if (parsedGeometry.matricesWeightsExtra) {
  25837. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  25838. }
  25839. mesh.setIndices(parsedGeometry.indices);
  25840. }
  25841. // SubMeshes
  25842. if (parsedGeometry.subMeshes) {
  25843. mesh.subMeshes = [];
  25844. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  25845. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  25846. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  25847. }
  25848. }
  25849. // Flat shading
  25850. if (mesh._shouldGenerateFlatShading) {
  25851. mesh.convertToFlatShadedMesh();
  25852. delete mesh._shouldGenerateFlatShading;
  25853. }
  25854. // Update
  25855. mesh.computeWorldMatrix(true);
  25856. // Octree
  25857. if (scene['_selectionOctree']) {
  25858. scene['_selectionOctree'].addMesh(mesh);
  25859. }
  25860. };
  25861. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  25862. if (scene.getGeometryByID(parsedVertexData.id)) {
  25863. return null; // null since geometry could be something else than a box...
  25864. }
  25865. var geometry = new Geometry(parsedVertexData.id, scene);
  25866. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  25867. if (parsedVertexData.delayLoadingFile) {
  25868. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25869. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  25870. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  25871. geometry._delayInfo = [];
  25872. if (parsedVertexData.hasUVs) {
  25873. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  25874. }
  25875. if (parsedVertexData.hasUVs2) {
  25876. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  25877. }
  25878. if (parsedVertexData.hasUVs3) {
  25879. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  25880. }
  25881. if (parsedVertexData.hasUVs4) {
  25882. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  25883. }
  25884. if (parsedVertexData.hasUVs5) {
  25885. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  25886. }
  25887. if (parsedVertexData.hasUVs6) {
  25888. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  25889. }
  25890. if (parsedVertexData.hasColors) {
  25891. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  25892. }
  25893. if (parsedVertexData.hasMatricesIndices) {
  25894. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25895. }
  25896. if (parsedVertexData.hasMatricesWeights) {
  25897. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25898. }
  25899. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  25900. }
  25901. else {
  25902. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  25903. }
  25904. scene.pushGeometry(geometry, true);
  25905. return geometry;
  25906. };
  25907. return Geometry;
  25908. }());
  25909. BABYLON.Geometry = Geometry;
  25910. /////// Primitives //////////////////////////////////////////////
  25911. (function (Geometry) {
  25912. var Primitives;
  25913. (function (Primitives) {
  25914. /// Abstract class
  25915. var _Primitive = (function (_super) {
  25916. __extends(_Primitive, _super);
  25917. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  25918. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  25919. _this._canBeRegenerated = _canBeRegenerated;
  25920. _this._beingRegenerated = true;
  25921. _this.regenerate();
  25922. _this._beingRegenerated = false;
  25923. return _this;
  25924. }
  25925. _Primitive.prototype.canBeRegenerated = function () {
  25926. return this._canBeRegenerated;
  25927. };
  25928. _Primitive.prototype.regenerate = function () {
  25929. if (!this._canBeRegenerated) {
  25930. return;
  25931. }
  25932. this._beingRegenerated = true;
  25933. this.setAllVerticesData(this._regenerateVertexData(), false);
  25934. this._beingRegenerated = false;
  25935. };
  25936. _Primitive.prototype.asNewGeometry = function (id) {
  25937. return _super.prototype.copy.call(this, id);
  25938. };
  25939. // overrides
  25940. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25941. if (!this._beingRegenerated) {
  25942. return;
  25943. }
  25944. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25945. };
  25946. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25947. if (!this._beingRegenerated) {
  25948. return;
  25949. }
  25950. _super.prototype.setVerticesData.call(this, kind, data, false);
  25951. };
  25952. // to override
  25953. // protected
  25954. _Primitive.prototype._regenerateVertexData = function () {
  25955. throw new Error("Abstract method");
  25956. };
  25957. _Primitive.prototype.copy = function (id) {
  25958. throw new Error("Must be overriden in sub-classes.");
  25959. };
  25960. _Primitive.prototype.serialize = function () {
  25961. var serializationObject = _super.prototype.serialize.call(this);
  25962. serializationObject.canBeRegenerated = this.canBeRegenerated();
  25963. return serializationObject;
  25964. };
  25965. return _Primitive;
  25966. }(Geometry));
  25967. Primitives._Primitive = _Primitive;
  25968. var Ribbon = (function (_super) {
  25969. __extends(Ribbon, _super);
  25970. // Members
  25971. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25972. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25973. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  25974. _this.pathArray = pathArray;
  25975. _this.closeArray = closeArray;
  25976. _this.closePath = closePath;
  25977. _this.offset = offset;
  25978. _this.side = side;
  25979. return _this;
  25980. }
  25981. Ribbon.prototype._regenerateVertexData = function () {
  25982. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  25983. };
  25984. Ribbon.prototype.copy = function (id) {
  25985. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25986. };
  25987. return Ribbon;
  25988. }(_Primitive));
  25989. Primitives.Ribbon = Ribbon;
  25990. var Box = (function (_super) {
  25991. __extends(Box, _super);
  25992. // Members
  25993. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25994. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25995. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  25996. _this.size = size;
  25997. _this.side = side;
  25998. return _this;
  25999. }
  26000. Box.prototype._regenerateVertexData = function () {
  26001. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26002. };
  26003. Box.prototype.copy = function (id) {
  26004. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26005. };
  26006. Box.prototype.serialize = function () {
  26007. var serializationObject = _super.prototype.serialize.call(this);
  26008. serializationObject.size = this.size;
  26009. return serializationObject;
  26010. };
  26011. Box.Parse = function (parsedBox, scene) {
  26012. if (scene.getGeometryByID(parsedBox.id)) {
  26013. return null; // null since geometry could be something else than a box...
  26014. }
  26015. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  26016. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  26017. scene.pushGeometry(box, true);
  26018. return box;
  26019. };
  26020. return Box;
  26021. }(_Primitive));
  26022. Primitives.Box = Box;
  26023. var Sphere = (function (_super) {
  26024. __extends(Sphere, _super);
  26025. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26026. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26027. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26028. _this.segments = segments;
  26029. _this.diameter = diameter;
  26030. _this.side = side;
  26031. return _this;
  26032. }
  26033. Sphere.prototype._regenerateVertexData = function () {
  26034. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26035. };
  26036. Sphere.prototype.copy = function (id) {
  26037. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26038. };
  26039. Sphere.prototype.serialize = function () {
  26040. var serializationObject = _super.prototype.serialize.call(this);
  26041. serializationObject.segments = this.segments;
  26042. serializationObject.diameter = this.diameter;
  26043. return serializationObject;
  26044. };
  26045. Sphere.Parse = function (parsedSphere, scene) {
  26046. if (scene.getGeometryByID(parsedSphere.id)) {
  26047. return null; // null since geometry could be something else than a sphere...
  26048. }
  26049. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  26050. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  26051. scene.pushGeometry(sphere, true);
  26052. return sphere;
  26053. };
  26054. return Sphere;
  26055. }(_Primitive));
  26056. Primitives.Sphere = Sphere;
  26057. var Disc = (function (_super) {
  26058. __extends(Disc, _super);
  26059. // Members
  26060. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26061. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26062. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26063. _this.radius = radius;
  26064. _this.tessellation = tessellation;
  26065. _this.side = side;
  26066. return _this;
  26067. }
  26068. Disc.prototype._regenerateVertexData = function () {
  26069. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26070. };
  26071. Disc.prototype.copy = function (id) {
  26072. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26073. };
  26074. return Disc;
  26075. }(_Primitive));
  26076. Primitives.Disc = Disc;
  26077. var Cylinder = (function (_super) {
  26078. __extends(Cylinder, _super);
  26079. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26080. if (subdivisions === void 0) { subdivisions = 1; }
  26081. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26082. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26083. _this.height = height;
  26084. _this.diameterTop = diameterTop;
  26085. _this.diameterBottom = diameterBottom;
  26086. _this.tessellation = tessellation;
  26087. _this.subdivisions = subdivisions;
  26088. _this.side = side;
  26089. return _this;
  26090. }
  26091. Cylinder.prototype._regenerateVertexData = function () {
  26092. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26093. };
  26094. Cylinder.prototype.copy = function (id) {
  26095. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26096. };
  26097. Cylinder.prototype.serialize = function () {
  26098. var serializationObject = _super.prototype.serialize.call(this);
  26099. serializationObject.height = this.height;
  26100. serializationObject.diameterTop = this.diameterTop;
  26101. serializationObject.diameterBottom = this.diameterBottom;
  26102. serializationObject.tessellation = this.tessellation;
  26103. return serializationObject;
  26104. };
  26105. Cylinder.Parse = function (parsedCylinder, scene) {
  26106. if (scene.getGeometryByID(parsedCylinder.id)) {
  26107. return null; // null since geometry could be something else than a cylinder...
  26108. }
  26109. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  26110. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  26111. scene.pushGeometry(cylinder, true);
  26112. return cylinder;
  26113. };
  26114. return Cylinder;
  26115. }(_Primitive));
  26116. Primitives.Cylinder = Cylinder;
  26117. var Torus = (function (_super) {
  26118. __extends(Torus, _super);
  26119. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26120. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26121. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26122. _this.diameter = diameter;
  26123. _this.thickness = thickness;
  26124. _this.tessellation = tessellation;
  26125. _this.side = side;
  26126. return _this;
  26127. }
  26128. Torus.prototype._regenerateVertexData = function () {
  26129. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26130. };
  26131. Torus.prototype.copy = function (id) {
  26132. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26133. };
  26134. Torus.prototype.serialize = function () {
  26135. var serializationObject = _super.prototype.serialize.call(this);
  26136. serializationObject.diameter = this.diameter;
  26137. serializationObject.thickness = this.thickness;
  26138. serializationObject.tessellation = this.tessellation;
  26139. return serializationObject;
  26140. };
  26141. Torus.Parse = function (parsedTorus, scene) {
  26142. if (scene.getGeometryByID(parsedTorus.id)) {
  26143. return null; // null since geometry could be something else than a torus...
  26144. }
  26145. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  26146. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  26147. scene.pushGeometry(torus, true);
  26148. return torus;
  26149. };
  26150. return Torus;
  26151. }(_Primitive));
  26152. Primitives.Torus = Torus;
  26153. var Ground = (function (_super) {
  26154. __extends(Ground, _super);
  26155. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26156. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26157. _this.width = width;
  26158. _this.height = height;
  26159. _this.subdivisions = subdivisions;
  26160. return _this;
  26161. }
  26162. Ground.prototype._regenerateVertexData = function () {
  26163. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26164. };
  26165. Ground.prototype.copy = function (id) {
  26166. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26167. };
  26168. Ground.prototype.serialize = function () {
  26169. var serializationObject = _super.prototype.serialize.call(this);
  26170. serializationObject.width = this.width;
  26171. serializationObject.height = this.height;
  26172. serializationObject.subdivisions = this.subdivisions;
  26173. return serializationObject;
  26174. };
  26175. Ground.Parse = function (parsedGround, scene) {
  26176. if (scene.getGeometryByID(parsedGround.id)) {
  26177. return null; // null since geometry could be something else than a ground...
  26178. }
  26179. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  26180. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  26181. scene.pushGeometry(ground, true);
  26182. return ground;
  26183. };
  26184. return Ground;
  26185. }(_Primitive));
  26186. Primitives.Ground = Ground;
  26187. var TiledGround = (function (_super) {
  26188. __extends(TiledGround, _super);
  26189. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26190. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26191. _this.xmin = xmin;
  26192. _this.zmin = zmin;
  26193. _this.xmax = xmax;
  26194. _this.zmax = zmax;
  26195. _this.subdivisions = subdivisions;
  26196. _this.precision = precision;
  26197. return _this;
  26198. }
  26199. TiledGround.prototype._regenerateVertexData = function () {
  26200. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26201. };
  26202. TiledGround.prototype.copy = function (id) {
  26203. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26204. };
  26205. return TiledGround;
  26206. }(_Primitive));
  26207. Primitives.TiledGround = TiledGround;
  26208. var Plane = (function (_super) {
  26209. __extends(Plane, _super);
  26210. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26211. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26212. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26213. _this.size = size;
  26214. _this.side = side;
  26215. return _this;
  26216. }
  26217. Plane.prototype._regenerateVertexData = function () {
  26218. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26219. };
  26220. Plane.prototype.copy = function (id) {
  26221. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26222. };
  26223. Plane.prototype.serialize = function () {
  26224. var serializationObject = _super.prototype.serialize.call(this);
  26225. serializationObject.size = this.size;
  26226. return serializationObject;
  26227. };
  26228. Plane.Parse = function (parsedPlane, scene) {
  26229. if (scene.getGeometryByID(parsedPlane.id)) {
  26230. return null; // null since geometry could be something else than a ground...
  26231. }
  26232. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  26233. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  26234. scene.pushGeometry(plane, true);
  26235. return plane;
  26236. };
  26237. return Plane;
  26238. }(_Primitive));
  26239. Primitives.Plane = Plane;
  26240. var TorusKnot = (function (_super) {
  26241. __extends(TorusKnot, _super);
  26242. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26243. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26244. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26245. _this.radius = radius;
  26246. _this.tube = tube;
  26247. _this.radialSegments = radialSegments;
  26248. _this.tubularSegments = tubularSegments;
  26249. _this.p = p;
  26250. _this.q = q;
  26251. _this.side = side;
  26252. return _this;
  26253. }
  26254. TorusKnot.prototype._regenerateVertexData = function () {
  26255. 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 });
  26256. };
  26257. TorusKnot.prototype.copy = function (id) {
  26258. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26259. };
  26260. TorusKnot.prototype.serialize = function () {
  26261. var serializationObject = _super.prototype.serialize.call(this);
  26262. serializationObject.radius = this.radius;
  26263. serializationObject.tube = this.tube;
  26264. serializationObject.radialSegments = this.radialSegments;
  26265. serializationObject.tubularSegments = this.tubularSegments;
  26266. serializationObject.p = this.p;
  26267. serializationObject.q = this.q;
  26268. return serializationObject;
  26269. };
  26270. ;
  26271. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  26272. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  26273. return null; // null since geometry could be something else than a ground...
  26274. }
  26275. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  26276. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  26277. scene.pushGeometry(torusKnot, true);
  26278. return torusKnot;
  26279. };
  26280. return TorusKnot;
  26281. }(_Primitive));
  26282. Primitives.TorusKnot = TorusKnot;
  26283. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26284. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26285. })(BABYLON || (BABYLON = {}));
  26286. //# sourceMappingURL=babylon.geometry.js.map
  26287. var BABYLON;
  26288. (function (BABYLON) {
  26289. var PostProcessManager = (function () {
  26290. function PostProcessManager(scene) {
  26291. this._vertexBuffers = {};
  26292. this._scene = scene;
  26293. }
  26294. PostProcessManager.prototype._prepareBuffers = function () {
  26295. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  26296. return;
  26297. }
  26298. // VBO
  26299. var vertices = [];
  26300. vertices.push(1, 1);
  26301. vertices.push(-1, 1);
  26302. vertices.push(-1, -1);
  26303. vertices.push(1, -1);
  26304. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  26305. // Indices
  26306. var indices = [];
  26307. indices.push(0);
  26308. indices.push(1);
  26309. indices.push(2);
  26310. indices.push(0);
  26311. indices.push(2);
  26312. indices.push(3);
  26313. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  26314. };
  26315. // Methods
  26316. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  26317. var postProcesses = this._scene.activeCamera._postProcesses;
  26318. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  26319. return false;
  26320. }
  26321. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  26322. return true;
  26323. };
  26324. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  26325. var engine = this._scene.getEngine();
  26326. for (var index = 0; index < postProcesses.length; index++) {
  26327. if (index < postProcesses.length - 1) {
  26328. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26329. }
  26330. else {
  26331. if (targetTexture) {
  26332. engine.bindFramebuffer(targetTexture);
  26333. }
  26334. else {
  26335. engine.restoreDefaultFramebuffer();
  26336. }
  26337. }
  26338. var pp = postProcesses[index];
  26339. var effect = pp.apply();
  26340. if (effect) {
  26341. pp.onBeforeRenderObservable.notifyObservers(effect);
  26342. // VBOs
  26343. this._prepareBuffers();
  26344. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26345. // Draw order
  26346. engine.draw(true, 0, 6);
  26347. pp.onAfterRenderObservable.notifyObservers(effect);
  26348. }
  26349. }
  26350. // Restore depth buffer
  26351. engine.setDepthBuffer(true);
  26352. engine.setDepthWrite(true);
  26353. };
  26354. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  26355. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  26356. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  26357. return;
  26358. }
  26359. var engine = this._scene.getEngine();
  26360. for (var index = 0, len = postProcesses.length; index < len; index++) {
  26361. if (index < len - 1) {
  26362. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26363. }
  26364. else {
  26365. if (targetTexture) {
  26366. engine.bindFramebuffer(targetTexture, faceIndex);
  26367. }
  26368. else {
  26369. engine.restoreDefaultFramebuffer();
  26370. }
  26371. }
  26372. if (doNotPresent) {
  26373. break;
  26374. }
  26375. var pp = postProcesses[index];
  26376. var effect = pp.apply();
  26377. if (effect) {
  26378. pp.onBeforeRenderObservable.notifyObservers(effect);
  26379. // VBOs
  26380. this._prepareBuffers();
  26381. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26382. // Draw order
  26383. engine.draw(true, 0, 6);
  26384. pp.onAfterRenderObservable.notifyObservers(effect);
  26385. }
  26386. }
  26387. // Restore depth buffer
  26388. engine.setDepthBuffer(true);
  26389. engine.setDepthWrite(true);
  26390. };
  26391. PostProcessManager.prototype.dispose = function () {
  26392. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  26393. if (buffer) {
  26394. buffer.dispose();
  26395. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  26396. }
  26397. if (this._indexBuffer) {
  26398. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26399. this._indexBuffer = null;
  26400. }
  26401. };
  26402. return PostProcessManager;
  26403. }());
  26404. BABYLON.PostProcessManager = PostProcessManager;
  26405. })(BABYLON || (BABYLON = {}));
  26406. //# sourceMappingURL=babylon.postProcessManager.js.map
  26407. var BABYLON;
  26408. (function (BABYLON) {
  26409. var StandardMaterialDefines = (function (_super) {
  26410. __extends(StandardMaterialDefines, _super);
  26411. function StandardMaterialDefines() {
  26412. var _this = _super.call(this) || this;
  26413. _this.DIFFUSE = false;
  26414. _this.AMBIENT = false;
  26415. _this.OPACITY = false;
  26416. _this.OPACITYRGB = false;
  26417. _this.REFLECTION = false;
  26418. _this.EMISSIVE = false;
  26419. _this.SPECULAR = false;
  26420. _this.BUMP = false;
  26421. _this.PARALLAX = false;
  26422. _this.PARALLAXOCCLUSION = false;
  26423. _this.SPECULAROVERALPHA = false;
  26424. _this.CLIPPLANE = false;
  26425. _this.ALPHATEST = false;
  26426. _this.ALPHAFROMDIFFUSE = false;
  26427. _this.POINTSIZE = false;
  26428. _this.FOG = false;
  26429. _this.SPECULARTERM = false;
  26430. _this.DIFFUSEFRESNEL = false;
  26431. _this.OPACITYFRESNEL = false;
  26432. _this.REFLECTIONFRESNEL = false;
  26433. _this.REFRACTIONFRESNEL = false;
  26434. _this.EMISSIVEFRESNEL = false;
  26435. _this.FRESNEL = false;
  26436. _this.NORMAL = false;
  26437. _this.UV1 = false;
  26438. _this.UV2 = false;
  26439. _this.VERTEXCOLOR = false;
  26440. _this.VERTEXALPHA = false;
  26441. _this.NUM_BONE_INFLUENCERS = 0;
  26442. _this.BonesPerMesh = 0;
  26443. _this.INSTANCES = false;
  26444. _this.GLOSSINESS = false;
  26445. _this.ROUGHNESS = false;
  26446. _this.EMISSIVEASILLUMINATION = false;
  26447. _this.LINKEMISSIVEWITHDIFFUSE = false;
  26448. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  26449. _this.LIGHTMAP = false;
  26450. _this.USELIGHTMAPASSHADOWMAP = false;
  26451. _this.REFLECTIONMAP_3D = false;
  26452. _this.REFLECTIONMAP_SPHERICAL = false;
  26453. _this.REFLECTIONMAP_PLANAR = false;
  26454. _this.REFLECTIONMAP_CUBIC = false;
  26455. _this.REFLECTIONMAP_PROJECTION = false;
  26456. _this.REFLECTIONMAP_SKYBOX = false;
  26457. _this.REFLECTIONMAP_EXPLICIT = false;
  26458. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  26459. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  26460. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  26461. _this.INVERTCUBICMAP = false;
  26462. _this.LOGARITHMICDEPTH = false;
  26463. _this.REFRACTION = false;
  26464. _this.REFRACTIONMAP_3D = false;
  26465. _this.REFLECTIONOVERALPHA = false;
  26466. _this.INVERTNORMALMAPX = false;
  26467. _this.INVERTNORMALMAPY = false;
  26468. _this.TWOSIDEDLIGHTING = false;
  26469. _this.SHADOWFULLFLOAT = false;
  26470. _this.CAMERACOLORGRADING = false;
  26471. _this.CAMERACOLORCURVES = false;
  26472. _this.MORPHTARGETS = false;
  26473. _this.MORPHTARGETS_NORMAL = false;
  26474. _this.NUM_MORPH_INFLUENCERS = 0;
  26475. _this.rebuild();
  26476. return _this;
  26477. }
  26478. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  26479. var modes = [
  26480. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  26481. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  26482. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  26483. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  26484. ];
  26485. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  26486. var mode = modes_1[_i];
  26487. this[mode] = (mode === modeToEnable);
  26488. }
  26489. };
  26490. return StandardMaterialDefines;
  26491. }(BABYLON.MaterialDefines));
  26492. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  26493. var StandardMaterial = (function (_super) {
  26494. __extends(StandardMaterial, _super);
  26495. function StandardMaterial(name, scene) {
  26496. var _this = _super.call(this, name, scene) || this;
  26497. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  26498. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  26499. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  26500. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  26501. _this.specularPower = 64;
  26502. _this._useAlphaFromDiffuseTexture = false;
  26503. _this._useEmissiveAsIllumination = false;
  26504. _this._linkEmissiveWithDiffuse = false;
  26505. _this._useSpecularOverAlpha = false;
  26506. _this._useReflectionOverAlpha = false;
  26507. _this._disableLighting = false;
  26508. _this._useParallax = false;
  26509. _this._useParallaxOcclusion = false;
  26510. _this.parallaxScaleBias = 0.05;
  26511. _this._roughness = 0;
  26512. _this.indexOfRefraction = 0.98;
  26513. _this.invertRefractionY = true;
  26514. _this._useLightmapAsShadowmap = false;
  26515. _this._useReflectionFresnelFromSpecular = false;
  26516. _this._useGlossinessFromSpecularMapAlpha = false;
  26517. _this._maxSimultaneousLights = 4;
  26518. /**
  26519. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  26520. */
  26521. _this._invertNormalMapX = false;
  26522. /**
  26523. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  26524. */
  26525. _this._invertNormalMapY = false;
  26526. /**
  26527. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  26528. */
  26529. _this._twoSidedLighting = false;
  26530. /**
  26531. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  26532. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  26533. * 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;
  26534. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  26535. */
  26536. _this._cameraColorCurves = null;
  26537. _this._renderTargets = new BABYLON.SmartArray(16);
  26538. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  26539. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  26540. _this.getRenderTargetTextures = function () {
  26541. _this._renderTargets.reset();
  26542. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  26543. _this._renderTargets.push(_this._reflectionTexture);
  26544. }
  26545. if (_this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  26546. _this._renderTargets.push(_this._refractionTexture);
  26547. }
  26548. return _this._renderTargets;
  26549. };
  26550. return _this;
  26551. }
  26552. StandardMaterial.prototype.getClassName = function () {
  26553. return "StandardMaterial";
  26554. };
  26555. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  26556. get: function () {
  26557. return this._useLogarithmicDepth;
  26558. },
  26559. set: function (value) {
  26560. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  26561. this._markAllSubMeshesAsMiscDirty();
  26562. },
  26563. enumerable: true,
  26564. configurable: true
  26565. });
  26566. StandardMaterial.prototype.needAlphaBlending = function () {
  26567. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  26568. };
  26569. StandardMaterial.prototype.needAlphaTesting = function () {
  26570. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  26571. };
  26572. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  26573. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  26574. };
  26575. StandardMaterial.prototype.getAlphaTestTexture = function () {
  26576. return this._diffuseTexture;
  26577. };
  26578. /**
  26579. * Child classes can use it to update shaders
  26580. */
  26581. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  26582. if (this.isFrozen) {
  26583. if (this._wasPreviouslyReady && subMesh.effect) {
  26584. return true;
  26585. }
  26586. }
  26587. if (!subMesh._materialDefines) {
  26588. subMesh._materialDefines = new StandardMaterialDefines();
  26589. }
  26590. var scene = this.getScene();
  26591. var defines = subMesh._materialDefines;
  26592. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  26593. if (defines._renderId === scene.getRenderId()) {
  26594. return true;
  26595. }
  26596. }
  26597. var engine = scene.getEngine();
  26598. // Lights
  26599. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  26600. // Textures
  26601. if (defines._areTexturesDirty) {
  26602. defines._needUVs = false;
  26603. if (scene.texturesEnabled) {
  26604. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26605. if (!this._diffuseTexture.isReady()) {
  26606. return false;
  26607. }
  26608. else {
  26609. defines._needUVs = true;
  26610. defines.DIFFUSE = true;
  26611. }
  26612. }
  26613. else {
  26614. defines.DIFFUSE = false;
  26615. }
  26616. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26617. if (!this._ambientTexture.isReady()) {
  26618. return false;
  26619. }
  26620. else {
  26621. defines._needUVs = true;
  26622. defines.AMBIENT = true;
  26623. }
  26624. }
  26625. else {
  26626. defines.AMBIENT = false;
  26627. }
  26628. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26629. if (!this._opacityTexture.isReady()) {
  26630. return false;
  26631. }
  26632. else {
  26633. defines._needUVs = true;
  26634. defines.OPACITY = true;
  26635. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  26636. }
  26637. }
  26638. else {
  26639. defines.OPACITY = false;
  26640. }
  26641. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26642. if (!this._reflectionTexture.isReady()) {
  26643. return false;
  26644. }
  26645. else {
  26646. defines._needNormals = true;
  26647. defines.REFLECTION = true;
  26648. defines.ROUGHNESS = (this._roughness > 0);
  26649. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  26650. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  26651. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  26652. switch (this._reflectionTexture.coordinatesMode) {
  26653. case BABYLON.Texture.CUBIC_MODE:
  26654. case BABYLON.Texture.INVCUBIC_MODE:
  26655. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  26656. break;
  26657. case BABYLON.Texture.EXPLICIT_MODE:
  26658. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  26659. break;
  26660. case BABYLON.Texture.PLANAR_MODE:
  26661. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  26662. break;
  26663. case BABYLON.Texture.PROJECTION_MODE:
  26664. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  26665. break;
  26666. case BABYLON.Texture.SKYBOX_MODE:
  26667. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  26668. break;
  26669. case BABYLON.Texture.SPHERICAL_MODE:
  26670. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  26671. break;
  26672. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  26673. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  26674. break;
  26675. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  26676. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  26677. break;
  26678. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  26679. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  26680. break;
  26681. }
  26682. }
  26683. }
  26684. else {
  26685. defines.REFLECTION = false;
  26686. }
  26687. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26688. if (!this._emissiveTexture.isReady()) {
  26689. return false;
  26690. }
  26691. else {
  26692. defines._needUVs = true;
  26693. defines.EMISSIVE = true;
  26694. }
  26695. }
  26696. else {
  26697. defines.EMISSIVE = false;
  26698. }
  26699. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26700. if (!this._lightmapTexture.isReady()) {
  26701. return false;
  26702. }
  26703. else {
  26704. defines._needUVs = true;
  26705. defines.LIGHTMAP = true;
  26706. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  26707. }
  26708. }
  26709. else {
  26710. defines.LIGHTMAP = false;
  26711. }
  26712. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26713. if (!this._specularTexture.isReady()) {
  26714. return false;
  26715. }
  26716. else {
  26717. defines._needUVs = true;
  26718. defines.SPECULAR = true;
  26719. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  26720. }
  26721. }
  26722. else {
  26723. defines.SPECULAR = false;
  26724. }
  26725. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  26726. if (!this._bumpTexture.isReady()) {
  26727. return false;
  26728. }
  26729. else {
  26730. defines._needUVs = true;
  26731. defines.BUMP = true;
  26732. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  26733. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  26734. defines.PARALLAX = this._useParallax;
  26735. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  26736. }
  26737. }
  26738. else {
  26739. defines.BUMP = false;
  26740. }
  26741. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26742. if (!this._refractionTexture.isReady()) {
  26743. return false;
  26744. }
  26745. else {
  26746. defines._needUVs = true;
  26747. defines.REFRACTION = true;
  26748. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  26749. }
  26750. }
  26751. else {
  26752. defines.REFRACTION = false;
  26753. }
  26754. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26755. if (!this._cameraColorGradingTexture.isReady()) {
  26756. return false;
  26757. }
  26758. else {
  26759. defines.CAMERACOLORGRADING = true;
  26760. }
  26761. }
  26762. else {
  26763. defines.CAMERACOLORGRADING = false;
  26764. }
  26765. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  26766. }
  26767. else {
  26768. defines.DIFFUSE = false;
  26769. defines.AMBIENT = false;
  26770. defines.OPACITY = false;
  26771. defines.REFLECTION = false;
  26772. defines.EMISSIVE = false;
  26773. defines.LIGHTMAP = false;
  26774. defines.BUMP = false;
  26775. defines.REFRACTION = false;
  26776. defines.CAMERACOLORGRADING = false;
  26777. }
  26778. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  26779. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  26780. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  26781. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  26782. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  26783. }
  26784. if (defines._areFresnelDirty) {
  26785. if (StandardMaterial.FresnelEnabled) {
  26786. // Fresnel
  26787. if (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled ||
  26788. this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  26789. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled ||
  26790. this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled ||
  26791. this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled) {
  26792. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  26793. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  26794. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  26795. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  26796. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  26797. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  26798. defines._needNormals = true;
  26799. defines.FRESNEL = true;
  26800. }
  26801. }
  26802. else {
  26803. defines.FRESNEL = false;
  26804. }
  26805. }
  26806. // Misc.
  26807. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  26808. // Attribs
  26809. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  26810. // Values that need to be evaluated on every frame
  26811. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  26812. if (scene._mirroredCameraPosition && defines.BUMP) {
  26813. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  26814. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  26815. defines.markAsUnprocessed();
  26816. }
  26817. // Get correct effect
  26818. if (defines.isDirty) {
  26819. defines.markAsProcessed();
  26820. scene.resetCachedMaterial();
  26821. // Fallbacks
  26822. var fallbacks = new BABYLON.EffectFallbacks();
  26823. if (defines.REFLECTION) {
  26824. fallbacks.addFallback(0, "REFLECTION");
  26825. }
  26826. if (defines.SPECULAR) {
  26827. fallbacks.addFallback(0, "SPECULAR");
  26828. }
  26829. if (defines.BUMP) {
  26830. fallbacks.addFallback(0, "BUMP");
  26831. }
  26832. if (defines.PARALLAX) {
  26833. fallbacks.addFallback(1, "PARALLAX");
  26834. }
  26835. if (defines.PARALLAXOCCLUSION) {
  26836. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  26837. }
  26838. if (defines.SPECULAROVERALPHA) {
  26839. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  26840. }
  26841. if (defines.FOG) {
  26842. fallbacks.addFallback(1, "FOG");
  26843. }
  26844. if (defines.POINTSIZE) {
  26845. fallbacks.addFallback(0, "POINTSIZE");
  26846. }
  26847. if (defines.LOGARITHMICDEPTH) {
  26848. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  26849. }
  26850. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  26851. if (defines.SPECULARTERM) {
  26852. fallbacks.addFallback(0, "SPECULARTERM");
  26853. }
  26854. if (defines.DIFFUSEFRESNEL) {
  26855. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  26856. }
  26857. if (defines.OPACITYFRESNEL) {
  26858. fallbacks.addFallback(2, "OPACITYFRESNEL");
  26859. }
  26860. if (defines.REFLECTIONFRESNEL) {
  26861. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  26862. }
  26863. if (defines.EMISSIVEFRESNEL) {
  26864. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  26865. }
  26866. if (defines.FRESNEL) {
  26867. fallbacks.addFallback(4, "FRESNEL");
  26868. }
  26869. //Attributes
  26870. var attribs = [BABYLON.VertexBuffer.PositionKind];
  26871. if (defines.NORMAL) {
  26872. attribs.push(BABYLON.VertexBuffer.NormalKind);
  26873. }
  26874. if (defines.UV1) {
  26875. attribs.push(BABYLON.VertexBuffer.UVKind);
  26876. }
  26877. if (defines.UV2) {
  26878. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26879. }
  26880. if (defines.VERTEXCOLOR) {
  26881. attribs.push(BABYLON.VertexBuffer.ColorKind);
  26882. }
  26883. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  26884. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  26885. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  26886. var shaderName = "default";
  26887. if (this.customShaderNameResolve) {
  26888. shaderName = this.customShaderNameResolve(shaderName);
  26889. }
  26890. var join = defines.toString();
  26891. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  26892. "vFogInfos", "vFogColor", "pointSize",
  26893. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  26894. "mBones",
  26895. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  26896. "depthValues",
  26897. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  26898. "logarithmicDepthConstant"
  26899. ];
  26900. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  26901. if (defines.CAMERACOLORCURVES) {
  26902. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  26903. }
  26904. if (defines.CAMERACOLORGRADING) {
  26905. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  26906. }
  26907. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, defines, this._maxSimultaneousLights);
  26908. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  26909. attributes: attribs,
  26910. uniformsNames: uniforms,
  26911. samplers: samplers,
  26912. defines: join,
  26913. fallbacks: fallbacks,
  26914. onCompiled: this.onCompiled,
  26915. onError: this.onError,
  26916. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  26917. }, engine), defines);
  26918. }
  26919. if (!subMesh.effect.isReady()) {
  26920. return false;
  26921. }
  26922. defines._renderId = scene.getRenderId();
  26923. this._wasPreviouslyReady = true;
  26924. return true;
  26925. };
  26926. StandardMaterial.prototype.unbind = function () {
  26927. if (this._activeEffect) {
  26928. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  26929. this._activeEffect.setTexture("reflection2DSampler", null);
  26930. }
  26931. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  26932. this._activeEffect.setTexture("refraction2DSampler", null);
  26933. }
  26934. }
  26935. _super.prototype.unbind.call(this);
  26936. };
  26937. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  26938. var scene = this.getScene();
  26939. var defines = subMesh._materialDefines;
  26940. if (!defines) {
  26941. return;
  26942. }
  26943. var effect = subMesh.effect;
  26944. this._activeEffect = effect;
  26945. // Matrices
  26946. this.bindOnlyWorldMatrix(world);
  26947. // Bones
  26948. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  26949. if (this._mustRebind(scene, effect)) {
  26950. effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26951. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  26952. // Fresnel
  26953. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26954. effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  26955. effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  26956. }
  26957. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26958. effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  26959. }
  26960. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26961. effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  26962. effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  26963. }
  26964. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26965. effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  26966. effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  26967. }
  26968. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26969. effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  26970. effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  26971. }
  26972. }
  26973. // Textures
  26974. if (scene.texturesEnabled) {
  26975. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26976. effect.setTexture("diffuseSampler", this._diffuseTexture);
  26977. effect.setFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  26978. effect.setMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  26979. }
  26980. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26981. effect.setTexture("ambientSampler", this._ambientTexture);
  26982. effect.setFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  26983. effect.setMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  26984. }
  26985. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26986. effect.setTexture("opacitySampler", this._opacityTexture);
  26987. effect.setFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  26988. effect.setMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  26989. }
  26990. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26991. if (this._reflectionTexture.isCube) {
  26992. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  26993. }
  26994. else {
  26995. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  26996. }
  26997. effect.setMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  26998. effect.setFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  26999. }
  27000. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27001. effect.setTexture("emissiveSampler", this._emissiveTexture);
  27002. effect.setFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  27003. effect.setMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  27004. }
  27005. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27006. effect.setTexture("lightmapSampler", this._lightmapTexture);
  27007. effect.setFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  27008. effect.setMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  27009. }
  27010. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27011. effect.setTexture("specularSampler", this._specularTexture);
  27012. effect.setFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  27013. effect.setMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  27014. }
  27015. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27016. effect.setTexture("bumpSampler", this._bumpTexture);
  27017. effect.setFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  27018. effect.setMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  27019. }
  27020. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27021. var depth = 1.0;
  27022. if (this._refractionTexture.isCube) {
  27023. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  27024. }
  27025. else {
  27026. effect.setTexture("refraction2DSampler", this._refractionTexture);
  27027. effect.setMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  27028. if (this._refractionTexture.depth) {
  27029. depth = this._refractionTexture.depth;
  27030. }
  27031. }
  27032. effect.setFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  27033. }
  27034. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27035. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  27036. }
  27037. }
  27038. // Clip plane
  27039. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  27040. // Point size
  27041. if (this.pointsCloud) {
  27042. effect.setFloat("pointSize", this.pointSize);
  27043. }
  27044. // Colors
  27045. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  27046. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  27047. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  27048. if (defines.SPECULARTERM) {
  27049. effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  27050. }
  27051. effect.setColor3("vEmissiveColor", this.emissiveColor);
  27052. }
  27053. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  27054. // Diffuse
  27055. effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  27056. // Lights
  27057. if (scene.lightsEnabled && !this.disableLighting) {
  27058. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  27059. }
  27060. // View
  27061. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  27062. effect.setMatrix("view", scene.getViewMatrix());
  27063. }
  27064. // Fog
  27065. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  27066. // Morph targets
  27067. if (defines.NUM_MORPH_INFLUENCERS) {
  27068. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  27069. }
  27070. // Log. depth
  27071. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  27072. // Color Curves
  27073. if (this.cameraColorCurves) {
  27074. BABYLON.ColorCurves.Bind(this.cameraColorCurves, effect);
  27075. }
  27076. }
  27077. this._afterBind(mesh, this._activeEffect);
  27078. };
  27079. StandardMaterial.prototype.getAnimatables = function () {
  27080. var results = [];
  27081. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  27082. results.push(this._diffuseTexture);
  27083. }
  27084. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  27085. results.push(this._ambientTexture);
  27086. }
  27087. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  27088. results.push(this._opacityTexture);
  27089. }
  27090. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  27091. results.push(this._reflectionTexture);
  27092. }
  27093. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  27094. results.push(this._emissiveTexture);
  27095. }
  27096. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  27097. results.push(this._specularTexture);
  27098. }
  27099. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  27100. results.push(this._bumpTexture);
  27101. }
  27102. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  27103. results.push(this._lightmapTexture);
  27104. }
  27105. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  27106. results.push(this._refractionTexture);
  27107. }
  27108. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  27109. results.push(this._cameraColorGradingTexture);
  27110. }
  27111. return results;
  27112. };
  27113. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27114. if (forceDisposeTextures) {
  27115. if (this._diffuseTexture) {
  27116. this._diffuseTexture.dispose();
  27117. }
  27118. if (this._ambientTexture) {
  27119. this._ambientTexture.dispose();
  27120. }
  27121. if (this._opacityTexture) {
  27122. this._opacityTexture.dispose();
  27123. }
  27124. if (this._reflectionTexture) {
  27125. this._reflectionTexture.dispose();
  27126. }
  27127. if (this._emissiveTexture) {
  27128. this._emissiveTexture.dispose();
  27129. }
  27130. if (this._specularTexture) {
  27131. this._specularTexture.dispose();
  27132. }
  27133. if (this._bumpTexture) {
  27134. this._bumpTexture.dispose();
  27135. }
  27136. if (this._lightmapTexture) {
  27137. this._lightmapTexture.dispose();
  27138. }
  27139. if (this._refractionTexture) {
  27140. this._refractionTexture.dispose();
  27141. }
  27142. if (this._cameraColorGradingTexture) {
  27143. this._cameraColorGradingTexture.dispose();
  27144. }
  27145. }
  27146. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  27147. };
  27148. StandardMaterial.prototype.clone = function (name) {
  27149. var _this = this;
  27150. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27151. result.name = name;
  27152. result.id = name;
  27153. return result;
  27154. };
  27155. StandardMaterial.prototype.serialize = function () {
  27156. return BABYLON.SerializationHelper.Serialize(this);
  27157. };
  27158. // Statics
  27159. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27160. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  27161. };
  27162. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  27163. get: function () {
  27164. return StandardMaterial._DiffuseTextureEnabled;
  27165. },
  27166. set: function (value) {
  27167. if (StandardMaterial._DiffuseTextureEnabled === value) {
  27168. return;
  27169. }
  27170. StandardMaterial._DiffuseTextureEnabled = value;
  27171. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27172. },
  27173. enumerable: true,
  27174. configurable: true
  27175. });
  27176. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  27177. get: function () {
  27178. return StandardMaterial._AmbientTextureEnabled;
  27179. },
  27180. set: function (value) {
  27181. if (StandardMaterial._AmbientTextureEnabled === value) {
  27182. return;
  27183. }
  27184. StandardMaterial._AmbientTextureEnabled = value;
  27185. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27186. },
  27187. enumerable: true,
  27188. configurable: true
  27189. });
  27190. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  27191. get: function () {
  27192. return StandardMaterial._OpacityTextureEnabled;
  27193. },
  27194. set: function (value) {
  27195. if (StandardMaterial._OpacityTextureEnabled === value) {
  27196. return;
  27197. }
  27198. StandardMaterial._OpacityTextureEnabled = value;
  27199. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27200. },
  27201. enumerable: true,
  27202. configurable: true
  27203. });
  27204. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  27205. get: function () {
  27206. return StandardMaterial._ReflectionTextureEnabled;
  27207. },
  27208. set: function (value) {
  27209. if (StandardMaterial._ReflectionTextureEnabled === value) {
  27210. return;
  27211. }
  27212. StandardMaterial._ReflectionTextureEnabled = value;
  27213. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27214. },
  27215. enumerable: true,
  27216. configurable: true
  27217. });
  27218. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  27219. get: function () {
  27220. return StandardMaterial._EmissiveTextureEnabled;
  27221. },
  27222. set: function (value) {
  27223. if (StandardMaterial._EmissiveTextureEnabled === value) {
  27224. return;
  27225. }
  27226. StandardMaterial._EmissiveTextureEnabled = value;
  27227. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27228. },
  27229. enumerable: true,
  27230. configurable: true
  27231. });
  27232. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  27233. get: function () {
  27234. return StandardMaterial._SpecularTextureEnabled;
  27235. },
  27236. set: function (value) {
  27237. if (StandardMaterial._SpecularTextureEnabled === value) {
  27238. return;
  27239. }
  27240. StandardMaterial._SpecularTextureEnabled = value;
  27241. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27242. },
  27243. enumerable: true,
  27244. configurable: true
  27245. });
  27246. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  27247. get: function () {
  27248. return StandardMaterial._BumpTextureEnabled;
  27249. },
  27250. set: function (value) {
  27251. if (StandardMaterial._BumpTextureEnabled === value) {
  27252. return;
  27253. }
  27254. StandardMaterial._BumpTextureEnabled = value;
  27255. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27256. },
  27257. enumerable: true,
  27258. configurable: true
  27259. });
  27260. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  27261. get: function () {
  27262. return StandardMaterial._LightmapTextureEnabled;
  27263. },
  27264. set: function (value) {
  27265. if (StandardMaterial._LightmapTextureEnabled === value) {
  27266. return;
  27267. }
  27268. StandardMaterial._LightmapTextureEnabled = value;
  27269. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27270. },
  27271. enumerable: true,
  27272. configurable: true
  27273. });
  27274. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  27275. get: function () {
  27276. return StandardMaterial._RefractionTextureEnabled;
  27277. },
  27278. set: function (value) {
  27279. if (StandardMaterial._RefractionTextureEnabled === value) {
  27280. return;
  27281. }
  27282. StandardMaterial._RefractionTextureEnabled = value;
  27283. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27284. },
  27285. enumerable: true,
  27286. configurable: true
  27287. });
  27288. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  27289. get: function () {
  27290. return StandardMaterial._ColorGradingTextureEnabled;
  27291. },
  27292. set: function (value) {
  27293. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  27294. return;
  27295. }
  27296. StandardMaterial._ColorGradingTextureEnabled = value;
  27297. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27298. },
  27299. enumerable: true,
  27300. configurable: true
  27301. });
  27302. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  27303. get: function () {
  27304. return StandardMaterial._FresnelEnabled;
  27305. },
  27306. set: function (value) {
  27307. if (StandardMaterial._FresnelEnabled === value) {
  27308. return;
  27309. }
  27310. StandardMaterial._FresnelEnabled = value;
  27311. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  27312. },
  27313. enumerable: true,
  27314. configurable: true
  27315. });
  27316. return StandardMaterial;
  27317. }(BABYLON.PushMaterial));
  27318. // Flags used to enable or disable a type of texture for all Standard Materials
  27319. StandardMaterial._DiffuseTextureEnabled = true;
  27320. StandardMaterial._AmbientTextureEnabled = true;
  27321. StandardMaterial._OpacityTextureEnabled = true;
  27322. StandardMaterial._ReflectionTextureEnabled = true;
  27323. StandardMaterial._EmissiveTextureEnabled = true;
  27324. StandardMaterial._SpecularTextureEnabled = true;
  27325. StandardMaterial._BumpTextureEnabled = true;
  27326. StandardMaterial._LightmapTextureEnabled = true;
  27327. StandardMaterial._RefractionTextureEnabled = true;
  27328. StandardMaterial._ColorGradingTextureEnabled = true;
  27329. StandardMaterial._FresnelEnabled = true;
  27330. __decorate([
  27331. BABYLON.serializeAsTexture("diffuseTexture")
  27332. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  27333. __decorate([
  27334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27335. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  27336. __decorate([
  27337. BABYLON.serializeAsTexture("ambientTexture")
  27338. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  27339. __decorate([
  27340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27341. ], StandardMaterial.prototype, "ambientTexture", void 0);
  27342. __decorate([
  27343. BABYLON.serializeAsTexture("opacityTexture")
  27344. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  27345. __decorate([
  27346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27347. ], StandardMaterial.prototype, "opacityTexture", void 0);
  27348. __decorate([
  27349. BABYLON.serializeAsTexture("reflectionTexture")
  27350. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  27351. __decorate([
  27352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27353. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  27354. __decorate([
  27355. BABYLON.serializeAsTexture("emissiveTexture")
  27356. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  27357. __decorate([
  27358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27359. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  27360. __decorate([
  27361. BABYLON.serializeAsTexture("specularTexture")
  27362. ], StandardMaterial.prototype, "_specularTexture", void 0);
  27363. __decorate([
  27364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27365. ], StandardMaterial.prototype, "specularTexture", void 0);
  27366. __decorate([
  27367. BABYLON.serializeAsTexture("bumpTexture")
  27368. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  27369. __decorate([
  27370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27371. ], StandardMaterial.prototype, "bumpTexture", void 0);
  27372. __decorate([
  27373. BABYLON.serializeAsTexture("lightmapTexture")
  27374. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  27375. __decorate([
  27376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27377. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  27378. __decorate([
  27379. BABYLON.serializeAsTexture("refractionTexture")
  27380. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  27381. __decorate([
  27382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27383. ], StandardMaterial.prototype, "refractionTexture", void 0);
  27384. __decorate([
  27385. BABYLON.serializeAsColor3("ambient")
  27386. ], StandardMaterial.prototype, "ambientColor", void 0);
  27387. __decorate([
  27388. BABYLON.serializeAsColor3("diffuse")
  27389. ], StandardMaterial.prototype, "diffuseColor", void 0);
  27390. __decorate([
  27391. BABYLON.serializeAsColor3("specular")
  27392. ], StandardMaterial.prototype, "specularColor", void 0);
  27393. __decorate([
  27394. BABYLON.serializeAsColor3("emissive")
  27395. ], StandardMaterial.prototype, "emissiveColor", void 0);
  27396. __decorate([
  27397. BABYLON.serialize()
  27398. ], StandardMaterial.prototype, "specularPower", void 0);
  27399. __decorate([
  27400. BABYLON.serialize("useAlphaFromDiffuseTexture")
  27401. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  27402. __decorate([
  27403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27404. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  27405. __decorate([
  27406. BABYLON.serialize("useEmissiveAsIllumination")
  27407. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  27408. __decorate([
  27409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27410. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  27411. __decorate([
  27412. BABYLON.serialize("linkEmissiveWithDiffuse")
  27413. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  27414. __decorate([
  27415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27416. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  27417. __decorate([
  27418. BABYLON.serialize("useSpecularOverAlpha")
  27419. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  27420. __decorate([
  27421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27422. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  27423. __decorate([
  27424. BABYLON.serialize("useReflectionOverAlpha")
  27425. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  27426. __decorate([
  27427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27428. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  27429. __decorate([
  27430. BABYLON.serialize("disableLighting")
  27431. ], StandardMaterial.prototype, "_disableLighting", void 0);
  27432. __decorate([
  27433. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  27434. ], StandardMaterial.prototype, "disableLighting", void 0);
  27435. __decorate([
  27436. BABYLON.serialize("useParallax")
  27437. ], StandardMaterial.prototype, "_useParallax", void 0);
  27438. __decorate([
  27439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27440. ], StandardMaterial.prototype, "useParallax", void 0);
  27441. __decorate([
  27442. BABYLON.serialize("useParallaxOcclusion")
  27443. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  27444. __decorate([
  27445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27446. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  27447. __decorate([
  27448. BABYLON.serialize()
  27449. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  27450. __decorate([
  27451. BABYLON.serialize("roughness")
  27452. ], StandardMaterial.prototype, "_roughness", void 0);
  27453. __decorate([
  27454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27455. ], StandardMaterial.prototype, "roughness", void 0);
  27456. __decorate([
  27457. BABYLON.serialize()
  27458. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  27459. __decorate([
  27460. BABYLON.serialize()
  27461. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  27462. __decorate([
  27463. BABYLON.serialize("useLightmapAsShadowmap")
  27464. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  27465. __decorate([
  27466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27467. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  27468. __decorate([
  27469. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  27470. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  27471. __decorate([
  27472. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  27473. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  27474. __decorate([
  27475. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  27476. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  27477. __decorate([
  27478. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  27479. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  27480. __decorate([
  27481. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  27482. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  27483. __decorate([
  27484. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  27485. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  27486. __decorate([
  27487. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  27488. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  27489. __decorate([
  27490. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  27491. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  27492. __decorate([
  27493. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  27494. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  27495. __decorate([
  27496. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  27497. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  27498. __decorate([
  27499. BABYLON.serialize("useReflectionFresnelFromSpecular")
  27500. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  27501. __decorate([
  27502. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  27503. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  27504. __decorate([
  27505. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  27506. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  27507. __decorate([
  27508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27509. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  27510. __decorate([
  27511. BABYLON.serialize("maxSimultaneousLights")
  27512. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  27513. __decorate([
  27514. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  27515. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  27516. __decorate([
  27517. BABYLON.serialize("invertNormalMapX")
  27518. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  27519. __decorate([
  27520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27521. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  27522. __decorate([
  27523. BABYLON.serialize("invertNormalMapY")
  27524. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  27525. __decorate([
  27526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27527. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  27528. __decorate([
  27529. BABYLON.serialize("twoSidedLighting")
  27530. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  27531. __decorate([
  27532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27533. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  27534. __decorate([
  27535. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  27536. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  27537. __decorate([
  27538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27539. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  27540. __decorate([
  27541. BABYLON.serializeAsColorCurves("cameraColorCurves")
  27542. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  27543. __decorate([
  27544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27545. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  27546. __decorate([
  27547. BABYLON.serialize()
  27548. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  27549. BABYLON.StandardMaterial = StandardMaterial;
  27550. })(BABYLON || (BABYLON = {}));
  27551. //# sourceMappingURL=babylon.standardMaterial.js.map
  27552. var BABYLON;
  27553. (function (BABYLON) {
  27554. var PBRMaterialDefines = (function (_super) {
  27555. __extends(PBRMaterialDefines, _super);
  27556. function PBRMaterialDefines() {
  27557. var _this = _super.call(this) || this;
  27558. _this.ALBEDO = false;
  27559. _this.AMBIENT = false;
  27560. _this.AMBIENTINGRAYSCALE = false;
  27561. _this.OPACITY = false;
  27562. _this.OPACITYRGB = false;
  27563. _this.REFLECTION = false;
  27564. _this.EMISSIVE = false;
  27565. _this.REFLECTIVITY = false;
  27566. _this.BUMP = false;
  27567. _this.PARALLAX = false;
  27568. _this.PARALLAXOCCLUSION = false;
  27569. _this.SPECULAROVERALPHA = false;
  27570. _this.CLIPPLANE = false;
  27571. _this.ALPHATEST = false;
  27572. _this.ALPHAFROMALBEDO = false;
  27573. _this.POINTSIZE = false;
  27574. _this.FOG = false;
  27575. _this.SPECULARTERM = false;
  27576. _this.OPACITYFRESNEL = false;
  27577. _this.EMISSIVEFRESNEL = false;
  27578. _this.FRESNEL = false;
  27579. _this.NORMAL = false;
  27580. _this.TANGENT = false;
  27581. _this.UV1 = false;
  27582. _this.UV2 = false;
  27583. _this.VERTEXCOLOR = false;
  27584. _this.VERTEXALPHA = false;
  27585. _this.NUM_BONE_INFLUENCERS = 0;
  27586. _this.BonesPerMesh = 0;
  27587. _this.INSTANCES = false;
  27588. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  27589. _this.MICROSURFACEAUTOMATIC = false;
  27590. _this.EMISSIVEASILLUMINATION = false;
  27591. _this.LINKEMISSIVEWITHALBEDO = false;
  27592. _this.LIGHTMAP = false;
  27593. _this.USELIGHTMAPASSHADOWMAP = false;
  27594. _this.REFLECTIONMAP_3D = false;
  27595. _this.REFLECTIONMAP_SPHERICAL = false;
  27596. _this.REFLECTIONMAP_PLANAR = false;
  27597. _this.REFLECTIONMAP_CUBIC = false;
  27598. _this.REFLECTIONMAP_PROJECTION = false;
  27599. _this.REFLECTIONMAP_SKYBOX = false;
  27600. _this.REFLECTIONMAP_EXPLICIT = false;
  27601. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  27602. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  27603. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  27604. _this.INVERTCUBICMAP = false;
  27605. _this.LOGARITHMICDEPTH = false;
  27606. _this.CAMERATONEMAP = false;
  27607. _this.CAMERACONTRAST = false;
  27608. _this.CAMERACOLORGRADING = false;
  27609. _this.CAMERACOLORCURVES = false;
  27610. _this.OVERLOADEDVALUES = false;
  27611. _this.OVERLOADEDSHADOWVALUES = false;
  27612. _this.USESPHERICALFROMREFLECTIONMAP = false;
  27613. _this.REFRACTION = false;
  27614. _this.REFRACTIONMAP_3D = false;
  27615. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  27616. _this.REFRACTIONMAPINLINEARSPACE = false;
  27617. _this.LODBASEDMICROSFURACE = false;
  27618. _this.USEPHYSICALLIGHTFALLOFF = false;
  27619. _this.RADIANCEOVERALPHA = false;
  27620. _this.USEPMREMREFLECTION = false;
  27621. _this.USEPMREMREFRACTION = false;
  27622. _this.INVERTNORMALMAPX = false;
  27623. _this.INVERTNORMALMAPY = false;
  27624. _this.TWOSIDEDLIGHTING = false;
  27625. _this.SHADOWFULLFLOAT = false;
  27626. _this.METALLICWORKFLOW = false;
  27627. _this.METALLICMAP = false;
  27628. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  27629. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  27630. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  27631. _this.AOSTOREINMETALMAPRED = false;
  27632. _this.MICROSURFACEMAP = false;
  27633. _this.MORPHTARGETS = false;
  27634. _this.MORPHTARGETS_NORMAL = false;
  27635. _this.NUM_MORPH_INFLUENCERS = 0;
  27636. _this.rebuild();
  27637. return _this;
  27638. }
  27639. return PBRMaterialDefines;
  27640. }(BABYLON.MaterialDefines));
  27641. /**
  27642. * The Physically based material of BJS.
  27643. *
  27644. * This offers the main features of a standard PBR material.
  27645. * For more information, please refer to the documentation :
  27646. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  27647. */
  27648. var PBRMaterial = (function (_super) {
  27649. __extends(PBRMaterial, _super);
  27650. /**
  27651. * Instantiates a new PBRMaterial instance.
  27652. *
  27653. * @param name The material name
  27654. * @param scene The scene the material will be use in.
  27655. */
  27656. function PBRMaterial(name, scene) {
  27657. var _this = _super.call(this, name, scene) || this;
  27658. /**
  27659. * Intensity of the direct lights e.g. the four lights available in your scene.
  27660. * This impacts both the direct diffuse and specular highlights.
  27661. */
  27662. _this.directIntensity = 1.0;
  27663. /**
  27664. * Intensity of the emissive part of the material.
  27665. * This helps controlling the emissive effect without modifying the emissive color.
  27666. */
  27667. _this.emissiveIntensity = 1.0;
  27668. /**
  27669. * Intensity of the environment e.g. how much the environment will light the object
  27670. * either through harmonics for rough material or through the refelction for shiny ones.
  27671. */
  27672. _this.environmentIntensity = 1.0;
  27673. /**
  27674. * This is a special control allowing the reduction of the specular highlights coming from the
  27675. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  27676. */
  27677. _this.specularIntensity = 1.0;
  27678. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  27679. /**
  27680. * Debug Control allowing disabling the bump map on this material.
  27681. */
  27682. _this.disableBumpMap = false;
  27683. /**
  27684. * Debug Control helping enforcing or dropping the darkness of shadows.
  27685. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  27686. */
  27687. _this.overloadedShadowIntensity = 1.0;
  27688. /**
  27689. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  27690. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  27691. */
  27692. _this.overloadedShadeIntensity = 1.0;
  27693. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  27694. /**
  27695. * The camera exposure used on this material.
  27696. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  27697. * This corresponds to a photographic exposure.
  27698. */
  27699. _this.cameraExposure = 1.0;
  27700. /**
  27701. * The camera contrast used on this material.
  27702. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  27703. */
  27704. _this.cameraContrast = 1.0;
  27705. /**
  27706. * Color Grading 2D Lookup Texture.
  27707. * This allows special effects like sepia, black and white to sixties rendering style.
  27708. */
  27709. _this.cameraColorGradingTexture = null;
  27710. /**
  27711. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  27712. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  27713. * 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;
  27714. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  27715. */
  27716. _this.cameraColorCurves = null;
  27717. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  27718. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  27719. /**
  27720. * Debug Control allowing to overload the ambient color.
  27721. * This as to be use with the overloadedAmbientIntensity parameter.
  27722. */
  27723. _this.overloadedAmbient = BABYLON.Color3.White();
  27724. /**
  27725. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  27726. */
  27727. _this.overloadedAmbientIntensity = 0.0;
  27728. /**
  27729. * Debug Control allowing to overload the albedo color.
  27730. * This as to be use with the overloadedAlbedoIntensity parameter.
  27731. */
  27732. _this.overloadedAlbedo = BABYLON.Color3.White();
  27733. /**
  27734. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  27735. */
  27736. _this.overloadedAlbedoIntensity = 0.0;
  27737. /**
  27738. * Debug Control allowing to overload the reflectivity color.
  27739. * This as to be use with the overloadedReflectivityIntensity parameter.
  27740. */
  27741. _this.overloadedReflectivity = new BABYLON.Color3(0.0, 0.0, 0.0);
  27742. /**
  27743. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  27744. */
  27745. _this.overloadedReflectivityIntensity = 0.0;
  27746. /**
  27747. * Debug Control allowing to overload the emissive color.
  27748. * This as to be use with the overloadedEmissiveIntensity parameter.
  27749. */
  27750. _this.overloadedEmissive = BABYLON.Color3.White();
  27751. /**
  27752. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  27753. */
  27754. _this.overloadedEmissiveIntensity = 0.0;
  27755. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  27756. /**
  27757. * Debug Control allowing to overload the reflection color.
  27758. * This as to be use with the overloadedReflectionIntensity parameter.
  27759. */
  27760. _this.overloadedReflection = BABYLON.Color3.White();
  27761. /**
  27762. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  27763. */
  27764. _this.overloadedReflectionIntensity = 0.0;
  27765. /**
  27766. * Debug Control allowing to overload the microsurface.
  27767. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  27768. */
  27769. _this.overloadedMicroSurface = 0.0;
  27770. /**
  27771. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  27772. */
  27773. _this.overloadedMicroSurfaceIntensity = 0.0;
  27774. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  27775. /**
  27776. * AKA Occlusion Texture Intensity in other nomenclature.
  27777. */
  27778. _this.ambientTextureStrength = 1.0;
  27779. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  27780. /**
  27781. * AKA Diffuse Color in other nomenclature.
  27782. */
  27783. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  27784. /**
  27785. * AKA Specular Color in other nomenclature.
  27786. */
  27787. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  27788. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  27789. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  27790. /**
  27791. * AKA Glossiness in other nomenclature.
  27792. */
  27793. _this.microSurface = 0.9;
  27794. /**
  27795. * source material index of refraction (IOR)' / 'destination material IOR.
  27796. */
  27797. _this.indexOfRefraction = 0.66;
  27798. /**
  27799. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  27800. */
  27801. _this.invertRefractionY = false;
  27802. /**
  27803. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  27804. * Materials half opaque for instance using refraction could benefit from this control.
  27805. */
  27806. _this.linkRefractionWithTransparency = false;
  27807. /**
  27808. * The emissive and albedo are linked to never be more than one (Energy conservation).
  27809. */
  27810. _this.linkEmissiveWithAlbedo = false;
  27811. _this.useLightmapAsShadowmap = false;
  27812. /**
  27813. * In this mode, the emissive informtaion will always be added to the lighting once.
  27814. * A light for instance can be thought as emissive.
  27815. */
  27816. _this.useEmissiveAsIllumination = false;
  27817. /**
  27818. * Secifies that the alpha is coming form the albedo channel alpha channel.
  27819. */
  27820. _this.useAlphaFromAlbedoTexture = false;
  27821. /**
  27822. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  27823. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  27824. */
  27825. _this.useSpecularOverAlpha = true;
  27826. /**
  27827. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  27828. */
  27829. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  27830. /**
  27831. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  27832. */
  27833. _this.useRoughnessFromMetallicTextureAlpha = true;
  27834. /**
  27835. * Specifies if the metallic texture contains the roughness information in its green channel.
  27836. */
  27837. _this.useRoughnessFromMetallicTextureGreen = false;
  27838. /**
  27839. * Specifies if the metallic texture contains the metallness information in its blue channel.
  27840. */
  27841. _this.useMetallnessFromMetallicTextureBlue = false;
  27842. /**
  27843. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  27844. */
  27845. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  27846. /**
  27847. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  27848. */
  27849. _this.useAmbientInGrayScale = false;
  27850. /**
  27851. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  27852. * The material will try to infer what glossiness each pixel should be.
  27853. */
  27854. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  27855. /**
  27856. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  27857. * the creation of the material.
  27858. */
  27859. _this.useScalarInLinearSpace = false;
  27860. /**
  27861. * BJS is using an harcoded light falloff based on a manually sets up range.
  27862. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  27863. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  27864. */
  27865. _this.usePhysicalLightFalloff = true;
  27866. /**
  27867. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  27868. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  27869. */
  27870. _this.useRadianceOverAlpha = true;
  27871. /**
  27872. * Allows using the bump map in parallax mode.
  27873. */
  27874. _this.useParallax = false;
  27875. /**
  27876. * Allows using the bump map in parallax occlusion mode.
  27877. */
  27878. _this.useParallaxOcclusion = false;
  27879. /**
  27880. * Controls the scale bias of the parallax mode.
  27881. */
  27882. _this.parallaxScaleBias = 0.05;
  27883. /**
  27884. * If sets to true, disables all the lights affecting the material.
  27885. */
  27886. _this.disableLighting = false;
  27887. /**
  27888. * Number of Simultaneous lights allowed on the material.
  27889. */
  27890. _this.maxSimultaneousLights = 4;
  27891. /**
  27892. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  27893. */
  27894. _this.invertNormalMapX = false;
  27895. /**
  27896. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  27897. */
  27898. _this.invertNormalMapY = false;
  27899. /**
  27900. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  27901. */
  27902. _this.twoSidedLighting = false;
  27903. _this._renderTargets = new BABYLON.SmartArray(16);
  27904. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  27905. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  27906. _this._tempColor = new BABYLON.Color3();
  27907. _this._defines = new PBRMaterialDefines();
  27908. _this._cachedDefines = new PBRMaterialDefines();
  27909. _this._myScene = null;
  27910. _this._myShadowGenerator = null;
  27911. _this._cachedDefines.BonesPerMesh = -1;
  27912. _this.getRenderTargetTextures = function () {
  27913. _this._renderTargets.reset();
  27914. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  27915. _this._renderTargets.push(_this.reflectionTexture);
  27916. }
  27917. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  27918. _this._renderTargets.push(_this.refractionTexture);
  27919. }
  27920. return _this._renderTargets;
  27921. };
  27922. return _this;
  27923. }
  27924. PBRMaterial.prototype.getClassName = function () {
  27925. return "PBRMaterial";
  27926. };
  27927. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  27928. get: function () {
  27929. return this._useLogarithmicDepth;
  27930. },
  27931. set: function (value) {
  27932. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  27933. },
  27934. enumerable: true,
  27935. configurable: true
  27936. });
  27937. PBRMaterial.prototype.needAlphaBlending = function () {
  27938. if (this.linkRefractionWithTransparency) {
  27939. return false;
  27940. }
  27941. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  27942. };
  27943. PBRMaterial.prototype.needAlphaTesting = function () {
  27944. if (this.linkRefractionWithTransparency) {
  27945. return false;
  27946. }
  27947. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  27948. };
  27949. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  27950. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  27951. };
  27952. PBRMaterial.prototype.getAlphaTestTexture = function () {
  27953. return this.albedoTexture;
  27954. };
  27955. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  27956. if (!mesh) {
  27957. return true;
  27958. }
  27959. if (this._defines.INSTANCES !== useInstances) {
  27960. return false;
  27961. }
  27962. return false;
  27963. };
  27964. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  27965. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  27966. };
  27967. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  27968. if (!useScalarInLinear) {
  27969. color.toLinearSpaceToRef(ref);
  27970. }
  27971. else {
  27972. ref.r = color.r;
  27973. ref.g = color.g;
  27974. ref.b = color.b;
  27975. }
  27976. };
  27977. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  27978. var lightIndex = 0;
  27979. var depthValuesAlreadySet = false;
  27980. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  27981. var light = _a[_i];
  27982. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  27983. // GAMMA CORRECTION.
  27984. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  27985. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  27986. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  27987. if (defines["SPECULARTERM"]) {
  27988. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  27989. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  27990. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  27991. }
  27992. // Shadows
  27993. if (scene.shadowsEnabled) {
  27994. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  27995. }
  27996. lightIndex++;
  27997. if (lightIndex === maxSimultaneousLights)
  27998. break;
  27999. }
  28000. };
  28001. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  28002. if (this.isFrozen) {
  28003. if (this._wasPreviouslyReady) {
  28004. return true;
  28005. }
  28006. }
  28007. var scene = this.getScene();
  28008. var engine = scene.getEngine();
  28009. var needUVs = false;
  28010. this._defines.reset();
  28011. if (scene.lightsEnabled && !this.disableLighting) {
  28012. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, true, this.maxSimultaneousLights);
  28013. }
  28014. if (!this.checkReadyOnEveryCall) {
  28015. if (this._renderId === scene.getRenderId()) {
  28016. if (this._checkCache(scene, mesh, useInstances)) {
  28017. return true;
  28018. }
  28019. }
  28020. }
  28021. if (scene.texturesEnabled) {
  28022. if (scene.getEngine().getCaps().textureLOD) {
  28023. this._defines.LODBASEDMICROSFURACE = true;
  28024. }
  28025. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  28026. if (!this.albedoTexture.isReady()) {
  28027. return false;
  28028. }
  28029. needUVs = true;
  28030. this._defines.ALBEDO = true;
  28031. }
  28032. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  28033. if (!this.ambientTexture.isReady()) {
  28034. return false;
  28035. }
  28036. needUVs = true;
  28037. this._defines.AMBIENT = true;
  28038. this._defines.AMBIENTINGRAYSCALE = this.useAmbientInGrayScale;
  28039. }
  28040. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  28041. if (!this.opacityTexture.isReady()) {
  28042. return false;
  28043. }
  28044. needUVs = true;
  28045. this._defines.OPACITY = true;
  28046. if (this.opacityTexture.getAlphaFromRGB) {
  28047. this._defines.OPACITYRGB = true;
  28048. }
  28049. }
  28050. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  28051. if (!this.reflectionTexture.isReady()) {
  28052. return false;
  28053. }
  28054. this._defines.REFLECTION = true;
  28055. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  28056. this._defines.INVERTCUBICMAP = true;
  28057. }
  28058. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  28059. switch (this.reflectionTexture.coordinatesMode) {
  28060. case BABYLON.Texture.CUBIC_MODE:
  28061. case BABYLON.Texture.INVCUBIC_MODE:
  28062. this._defines.REFLECTIONMAP_CUBIC = true;
  28063. break;
  28064. case BABYLON.Texture.EXPLICIT_MODE:
  28065. this._defines.REFLECTIONMAP_EXPLICIT = true;
  28066. break;
  28067. case BABYLON.Texture.PLANAR_MODE:
  28068. this._defines.REFLECTIONMAP_PLANAR = true;
  28069. break;
  28070. case BABYLON.Texture.PROJECTION_MODE:
  28071. this._defines.REFLECTIONMAP_PROJECTION = true;
  28072. break;
  28073. case BABYLON.Texture.SKYBOX_MODE:
  28074. this._defines.REFLECTIONMAP_SKYBOX = true;
  28075. break;
  28076. case BABYLON.Texture.SPHERICAL_MODE:
  28077. this._defines.REFLECTIONMAP_SPHERICAL = true;
  28078. break;
  28079. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  28080. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  28081. break;
  28082. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  28083. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  28084. break;
  28085. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  28086. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  28087. break;
  28088. }
  28089. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  28090. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  28091. if (this.reflectionTexture.isPMREM) {
  28092. this._defines.USEPMREMREFLECTION = true;
  28093. }
  28094. }
  28095. }
  28096. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  28097. if (!this.lightmapTexture.isReady()) {
  28098. return false;
  28099. }
  28100. needUVs = true;
  28101. this._defines.LIGHTMAP = true;
  28102. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  28103. }
  28104. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  28105. if (!this.emissiveTexture.isReady()) {
  28106. return false;
  28107. }
  28108. needUVs = true;
  28109. this._defines.EMISSIVE = true;
  28110. }
  28111. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  28112. if (this.metallicTexture) {
  28113. if (!this.metallicTexture.isReady()) {
  28114. return false;
  28115. }
  28116. needUVs = true;
  28117. this._defines.METALLICWORKFLOW = true;
  28118. this._defines.METALLICMAP = true;
  28119. this._defines.ROUGHNESSSTOREINMETALMAPALPHA = this.useRoughnessFromMetallicTextureAlpha;
  28120. this._defines.ROUGHNESSSTOREINMETALMAPGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  28121. this._defines.METALLNESSSTOREINMETALMAPBLUE = this.useMetallnessFromMetallicTextureBlue;
  28122. this._defines.AOSTOREINMETALMAPRED = this.useAmbientOcclusionFromMetallicTextureRed;
  28123. }
  28124. else if (this.reflectivityTexture) {
  28125. if (!this.reflectivityTexture.isReady()) {
  28126. return false;
  28127. }
  28128. needUVs = true;
  28129. this._defines.REFLECTIVITY = true;
  28130. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  28131. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  28132. }
  28133. if (this.microSurfaceTexture) {
  28134. if (!this.microSurfaceTexture.isReady()) {
  28135. return false;
  28136. }
  28137. needUVs = true;
  28138. this._defines.MICROSURFACEMAP = true;
  28139. }
  28140. }
  28141. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  28142. if (!this.bumpTexture.isReady()) {
  28143. return false;
  28144. }
  28145. needUVs = true;
  28146. this._defines.BUMP = true;
  28147. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  28148. this._defines.PARALLAX = true;
  28149. if (this.useParallaxOcclusion) {
  28150. this._defines.PARALLAXOCCLUSION = true;
  28151. }
  28152. }
  28153. if (this.invertNormalMapX) {
  28154. this._defines.INVERTNORMALMAPX = true;
  28155. }
  28156. if (this.invertNormalMapY) {
  28157. this._defines.INVERTNORMALMAPY = true;
  28158. }
  28159. if (scene._mirroredCameraPosition) {
  28160. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  28161. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  28162. }
  28163. }
  28164. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  28165. if (!this.refractionTexture.isReady()) {
  28166. return false;
  28167. }
  28168. needUVs = true;
  28169. this._defines.REFRACTION = true;
  28170. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  28171. if (this.linkRefractionWithTransparency) {
  28172. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  28173. }
  28174. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  28175. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  28176. if (this.refractionTexture.isPMREM) {
  28177. this._defines.USEPMREMREFRACTION = true;
  28178. }
  28179. }
  28180. }
  28181. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  28182. if (!this.cameraColorGradingTexture.isReady()) {
  28183. return false;
  28184. }
  28185. this._defines.CAMERACOLORGRADING = true;
  28186. }
  28187. if (!this.backFaceCulling && this.twoSidedLighting) {
  28188. this._defines.TWOSIDEDLIGHTING = true;
  28189. }
  28190. }
  28191. // Effect
  28192. if (scene.clipPlane) {
  28193. this._defines.CLIPPLANE = true;
  28194. }
  28195. if (engine.getAlphaTesting()) {
  28196. this._defines.ALPHATEST = true;
  28197. }
  28198. if (this._shouldUseAlphaFromAlbedoTexture()) {
  28199. this._defines.ALPHAFROMALBEDO = true;
  28200. }
  28201. if (this.useEmissiveAsIllumination) {
  28202. this._defines.EMISSIVEASILLUMINATION = true;
  28203. }
  28204. if (this.linkEmissiveWithAlbedo) {
  28205. this._defines.LINKEMISSIVEWITHALBEDO = true;
  28206. }
  28207. if (this.useLogarithmicDepth) {
  28208. this._defines.LOGARITHMICDEPTH = true;
  28209. }
  28210. if (this.cameraContrast != 1) {
  28211. this._defines.CAMERACONTRAST = true;
  28212. }
  28213. if (this.cameraExposure != 1) {
  28214. this._defines.CAMERATONEMAP = true;
  28215. }
  28216. if (this.cameraColorCurves) {
  28217. this._defines.CAMERACOLORCURVES = true;
  28218. }
  28219. if (this.overloadedShadeIntensity != 1 ||
  28220. this.overloadedShadowIntensity != 1) {
  28221. this._defines.OVERLOADEDSHADOWVALUES = true;
  28222. }
  28223. if (this.overloadedMicroSurfaceIntensity > 0 ||
  28224. this.overloadedEmissiveIntensity > 0 ||
  28225. this.overloadedReflectivityIntensity > 0 ||
  28226. this.overloadedAlbedoIntensity > 0 ||
  28227. this.overloadedAmbientIntensity > 0 ||
  28228. this.overloadedReflectionIntensity > 0) {
  28229. this._defines.OVERLOADEDVALUES = true;
  28230. }
  28231. // Point size
  28232. if (this.pointsCloud || scene.forcePointsCloud) {
  28233. this._defines.POINTSIZE = true;
  28234. }
  28235. // Fog
  28236. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28237. this._defines.FOG = true;
  28238. }
  28239. if (BABYLON.StandardMaterial.FresnelEnabled) {
  28240. // Fresnel
  28241. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  28242. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  28243. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  28244. this._defines.OPACITYFRESNEL = true;
  28245. }
  28246. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  28247. this._defines.EMISSIVEFRESNEL = true;
  28248. }
  28249. this._defines.FRESNEL = true;
  28250. }
  28251. }
  28252. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  28253. this._defines.SPECULAROVERALPHA = true;
  28254. }
  28255. if (this.usePhysicalLightFalloff) {
  28256. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  28257. }
  28258. if (this.useRadianceOverAlpha) {
  28259. this._defines.RADIANCEOVERALPHA = true;
  28260. }
  28261. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  28262. this._defines.METALLICWORKFLOW = true;
  28263. }
  28264. // Attribs
  28265. if (mesh) {
  28266. if (!mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28267. mesh.createNormals(true);
  28268. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  28269. }
  28270. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28271. this._defines.NORMAL = true;
  28272. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28273. this._defines.TANGENT = true;
  28274. }
  28275. }
  28276. if (needUVs) {
  28277. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28278. this._defines.UV1 = true;
  28279. }
  28280. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28281. this._defines.UV2 = true;
  28282. }
  28283. }
  28284. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28285. this._defines.VERTEXCOLOR = true;
  28286. if (mesh.hasVertexAlpha) {
  28287. this._defines.VERTEXALPHA = true;
  28288. }
  28289. }
  28290. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  28291. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  28292. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  28293. }
  28294. // Instances
  28295. if (useInstances) {
  28296. this._defines.INSTANCES = true;
  28297. }
  28298. if (mesh.morphTargetManager) {
  28299. var manager = mesh.morphTargetManager;
  28300. this._defines.MORPHTARGETS_NORMAL = manager.supportsNormals && this._defines.NORMAL;
  28301. this._defines.MORPHTARGETS = (manager.numInfluencers > 0);
  28302. this._defines.NUM_MORPH_INFLUENCERS = manager.numInfluencers;
  28303. }
  28304. }
  28305. // Get correct effect
  28306. if (!this._defines.isEqual(this._cachedDefines)) {
  28307. this._defines.cloneTo(this._cachedDefines);
  28308. scene.resetCachedMaterial();
  28309. // Fallbacks
  28310. var fallbacks = new BABYLON.EffectFallbacks();
  28311. if (this._defines.REFLECTION) {
  28312. fallbacks.addFallback(0, "REFLECTION");
  28313. }
  28314. if (this._defines.REFRACTION) {
  28315. fallbacks.addFallback(0, "REFRACTION");
  28316. }
  28317. if (this._defines.REFLECTIVITY) {
  28318. fallbacks.addFallback(0, "REFLECTIVITY");
  28319. }
  28320. if (this._defines.BUMP) {
  28321. fallbacks.addFallback(0, "BUMP");
  28322. }
  28323. if (this._defines.PARALLAX) {
  28324. fallbacks.addFallback(1, "PARALLAX");
  28325. }
  28326. if (this._defines.PARALLAXOCCLUSION) {
  28327. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  28328. }
  28329. if (this._defines.SPECULAROVERALPHA) {
  28330. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  28331. }
  28332. if (this._defines.FOG) {
  28333. fallbacks.addFallback(1, "FOG");
  28334. }
  28335. if (this._defines.POINTSIZE) {
  28336. fallbacks.addFallback(0, "POINTSIZE");
  28337. }
  28338. if (this._defines.LOGARITHMICDEPTH) {
  28339. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  28340. }
  28341. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  28342. if (this._defines.SPECULARTERM) {
  28343. fallbacks.addFallback(0, "SPECULARTERM");
  28344. }
  28345. if (this._defines.OPACITYFRESNEL) {
  28346. fallbacks.addFallback(1, "OPACITYFRESNEL");
  28347. }
  28348. if (this._defines.EMISSIVEFRESNEL) {
  28349. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  28350. }
  28351. if (this._defines.FRESNEL) {
  28352. fallbacks.addFallback(3, "FRESNEL");
  28353. }
  28354. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  28355. fallbacks.addCPUSkinningFallback(0, mesh);
  28356. }
  28357. //Attributes
  28358. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28359. if (this._defines.NORMAL) {
  28360. attribs.push(BABYLON.VertexBuffer.NormalKind);
  28361. }
  28362. if (this._defines.TANGENT) {
  28363. attribs.push(BABYLON.VertexBuffer.TangentKind);
  28364. }
  28365. if (this._defines.UV1) {
  28366. attribs.push(BABYLON.VertexBuffer.UVKind);
  28367. }
  28368. if (this._defines.UV2) {
  28369. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28370. }
  28371. if (this._defines.VERTEXCOLOR) {
  28372. attribs.push(BABYLON.VertexBuffer.ColorKind);
  28373. }
  28374. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  28375. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  28376. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, this._defines);
  28377. // Legacy browser patch
  28378. var join = this._defines.toString();
  28379. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  28380. "vFogInfos", "vFogColor", "pointSize",
  28381. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  28382. "mBones",
  28383. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  28384. "depthValues",
  28385. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  28386. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  28387. "logarithmicDepthConstant",
  28388. "vSphericalX", "vSphericalY", "vSphericalZ",
  28389. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  28390. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  28391. "vMicrosurfaceTextureLods",
  28392. "vCameraInfos"
  28393. ];
  28394. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  28395. if (this._defines.CAMERACOLORCURVES) {
  28396. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  28397. }
  28398. if (this._defines.CAMERACOLORGRADING) {
  28399. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  28400. }
  28401. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  28402. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: this._defines.NUM_MORPH_INFLUENCERS });
  28403. }
  28404. if (!this._effect.isReady()) {
  28405. return false;
  28406. }
  28407. this._renderId = scene.getRenderId();
  28408. this._wasPreviouslyReady = true;
  28409. return true;
  28410. };
  28411. PBRMaterial.prototype.unbind = function () {
  28412. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  28413. this._effect.setTexture("reflection2DSampler", null);
  28414. }
  28415. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  28416. this._effect.setTexture("refraction2DSampler", null);
  28417. }
  28418. _super.prototype.unbind.call(this);
  28419. };
  28420. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28421. this._effect.setMatrix("world", world);
  28422. };
  28423. PBRMaterial.prototype.bind = function (world, mesh) {
  28424. this._myScene = this.getScene();
  28425. // Matrices
  28426. this.bindOnlyWorldMatrix(world);
  28427. // Bones
  28428. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  28429. if (this._myScene.getCachedMaterial() !== this) {
  28430. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  28431. if (BABYLON.StandardMaterial.FresnelEnabled) {
  28432. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  28433. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  28434. }
  28435. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  28436. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  28437. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  28438. }
  28439. }
  28440. // Textures
  28441. if (this._myScene.texturesEnabled) {
  28442. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  28443. this._effect.setTexture("albedoSampler", this.albedoTexture);
  28444. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  28445. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  28446. }
  28447. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  28448. this._effect.setTexture("ambientSampler", this.ambientTexture);
  28449. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  28450. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  28451. }
  28452. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  28453. this._effect.setTexture("opacitySampler", this.opacityTexture);
  28454. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  28455. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  28456. }
  28457. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  28458. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  28459. if (this.reflectionTexture.isCube) {
  28460. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  28461. }
  28462. else {
  28463. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  28464. }
  28465. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  28466. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  28467. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  28468. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  28469. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  28470. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  28471. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  28472. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  28473. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  28474. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  28475. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  28476. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  28477. }
  28478. }
  28479. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  28480. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  28481. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  28482. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  28483. }
  28484. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  28485. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  28486. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  28487. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  28488. }
  28489. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  28490. if (this.metallicTexture) {
  28491. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  28492. this._effect.setFloat3("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level, this.ambientTextureStrength);
  28493. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  28494. }
  28495. else if (this.reflectivityTexture) {
  28496. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  28497. this._effect.setFloat3("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level, 1.0);
  28498. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  28499. }
  28500. if (this.microSurfaceTexture) {
  28501. this._effect.setTexture("microSurfaceSampler", this.microSurfaceTexture);
  28502. this._effect.setFloat2("vMicroSurfaceSamplerInfos", this.microSurfaceTexture.coordinatesIndex, this.microSurfaceTexture.level);
  28503. this._effect.setMatrix("microSurfaceSamplerMatrix", this.microSurfaceTexture.getTextureMatrix());
  28504. }
  28505. }
  28506. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  28507. this._effect.setTexture("bumpSampler", this.bumpTexture);
  28508. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  28509. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  28510. }
  28511. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  28512. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  28513. var depth = 1.0;
  28514. if (this.refractionTexture.isCube) {
  28515. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  28516. }
  28517. else {
  28518. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  28519. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  28520. if (this.refractionTexture.depth) {
  28521. depth = this.refractionTexture.depth;
  28522. }
  28523. }
  28524. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  28525. }
  28526. if ((this.reflectionTexture || this.refractionTexture)) {
  28527. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  28528. }
  28529. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  28530. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  28531. }
  28532. }
  28533. // Clip plane
  28534. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  28535. // Point size
  28536. if (this.pointsCloud) {
  28537. this._effect.setFloat("pointSize", this.pointSize);
  28538. }
  28539. // Colors
  28540. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  28541. if (this._defines.METALLICWORKFLOW) {
  28542. PBRMaterial._scaledReflectivity.r = (this.metallic === undefined || this.metallic === null) ? 1 : this.metallic;
  28543. PBRMaterial._scaledReflectivity.g = (this.roughness === undefined || this.roughness === null) ? 1 : this.roughness;
  28544. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  28545. }
  28546. else {
  28547. // GAMMA CORRECTION.
  28548. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  28549. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  28550. }
  28551. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  28552. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  28553. // GAMMA CORRECTION.
  28554. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  28555. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  28556. // GAMMA CORRECTION.
  28557. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  28558. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  28559. }
  28560. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  28561. // GAMMA CORRECTION.
  28562. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  28563. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  28564. // Lights
  28565. if (this._myScene.lightsEnabled && !this.disableLighting) {
  28566. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  28567. }
  28568. // View
  28569. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  28570. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  28571. }
  28572. // Fog
  28573. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  28574. // Morph targets
  28575. if (this._defines.NUM_MORPH_INFLUENCERS) {
  28576. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  28577. }
  28578. this._lightingInfos.x = this.directIntensity;
  28579. this._lightingInfos.y = this.emissiveIntensity;
  28580. this._lightingInfos.z = this.environmentIntensity;
  28581. this._lightingInfos.w = this.specularIntensity;
  28582. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  28583. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  28584. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  28585. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  28586. this._cameraInfos.x = this.cameraExposure;
  28587. this._cameraInfos.y = this.cameraContrast;
  28588. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  28589. if (this.cameraColorCurves) {
  28590. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  28591. }
  28592. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  28593. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  28594. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  28595. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  28596. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  28597. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  28598. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  28599. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  28600. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  28601. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  28602. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  28603. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  28604. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  28605. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  28606. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  28607. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  28608. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  28609. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  28610. // Log. depth
  28611. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  28612. }
  28613. this._afterBind(mesh);
  28614. this._myScene = null;
  28615. };
  28616. PBRMaterial.prototype.getAnimatables = function () {
  28617. var results = [];
  28618. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  28619. results.push(this.albedoTexture);
  28620. }
  28621. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  28622. results.push(this.ambientTexture);
  28623. }
  28624. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  28625. results.push(this.opacityTexture);
  28626. }
  28627. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  28628. results.push(this.reflectionTexture);
  28629. }
  28630. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  28631. results.push(this.emissiveTexture);
  28632. }
  28633. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  28634. results.push(this.metallicTexture);
  28635. }
  28636. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  28637. results.push(this.reflectivityTexture);
  28638. }
  28639. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  28640. results.push(this.bumpTexture);
  28641. }
  28642. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  28643. results.push(this.lightmapTexture);
  28644. }
  28645. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  28646. results.push(this.refractionTexture);
  28647. }
  28648. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  28649. results.push(this.cameraColorGradingTexture);
  28650. }
  28651. return results;
  28652. };
  28653. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28654. if (forceDisposeTextures) {
  28655. if (this.albedoTexture) {
  28656. this.albedoTexture.dispose();
  28657. }
  28658. if (this.ambientTexture) {
  28659. this.ambientTexture.dispose();
  28660. }
  28661. if (this.opacityTexture) {
  28662. this.opacityTexture.dispose();
  28663. }
  28664. if (this.reflectionTexture) {
  28665. this.reflectionTexture.dispose();
  28666. }
  28667. if (this.emissiveTexture) {
  28668. this.emissiveTexture.dispose();
  28669. }
  28670. if (this.metallicTexture) {
  28671. this.metallicTexture.dispose();
  28672. }
  28673. if (this.reflectivityTexture) {
  28674. this.reflectivityTexture.dispose();
  28675. }
  28676. if (this.bumpTexture) {
  28677. this.bumpTexture.dispose();
  28678. }
  28679. if (this.lightmapTexture) {
  28680. this.lightmapTexture.dispose();
  28681. }
  28682. if (this.refractionTexture) {
  28683. this.refractionTexture.dispose();
  28684. }
  28685. if (this.cameraColorGradingTexture) {
  28686. this.cameraColorGradingTexture.dispose();
  28687. }
  28688. }
  28689. this._renderTargets.dispose();
  28690. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  28691. };
  28692. PBRMaterial.prototype.clone = function (name) {
  28693. var _this = this;
  28694. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  28695. };
  28696. PBRMaterial.prototype.serialize = function () {
  28697. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  28698. serializationObject.customType = "BABYLON.PBRMaterial";
  28699. return serializationObject;
  28700. };
  28701. // Statics
  28702. PBRMaterial.Parse = function (source, scene, rootUrl) {
  28703. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  28704. };
  28705. return PBRMaterial;
  28706. }(BABYLON.Material));
  28707. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  28708. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  28709. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  28710. PBRMaterial._scaledReflection = new BABYLON.Color3();
  28711. __decorate([
  28712. BABYLON.serialize()
  28713. ], PBRMaterial.prototype, "directIntensity", void 0);
  28714. __decorate([
  28715. BABYLON.serialize()
  28716. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  28717. __decorate([
  28718. BABYLON.serialize()
  28719. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  28720. __decorate([
  28721. BABYLON.serialize()
  28722. ], PBRMaterial.prototype, "specularIntensity", void 0);
  28723. __decorate([
  28724. BABYLON.serialize()
  28725. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  28726. __decorate([
  28727. BABYLON.serialize()
  28728. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  28729. __decorate([
  28730. BABYLON.serialize()
  28731. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  28732. __decorate([
  28733. BABYLON.serialize()
  28734. ], PBRMaterial.prototype, "cameraExposure", void 0);
  28735. __decorate([
  28736. BABYLON.serialize()
  28737. ], PBRMaterial.prototype, "cameraContrast", void 0);
  28738. __decorate([
  28739. BABYLON.serializeAsTexture()
  28740. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  28741. __decorate([
  28742. BABYLON.serializeAsColorCurves()
  28743. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  28744. __decorate([
  28745. BABYLON.serializeAsColor3()
  28746. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  28747. __decorate([
  28748. BABYLON.serialize()
  28749. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  28750. __decorate([
  28751. BABYLON.serializeAsColor3()
  28752. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  28753. __decorate([
  28754. BABYLON.serialize()
  28755. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  28756. __decorate([
  28757. BABYLON.serializeAsColor3()
  28758. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  28759. __decorate([
  28760. BABYLON.serialize()
  28761. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  28762. __decorate([
  28763. BABYLON.serializeAsColor3()
  28764. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  28765. __decorate([
  28766. BABYLON.serialize()
  28767. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  28768. __decorate([
  28769. BABYLON.serializeAsColor3()
  28770. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  28771. __decorate([
  28772. BABYLON.serialize()
  28773. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  28774. __decorate([
  28775. BABYLON.serialize()
  28776. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  28777. __decorate([
  28778. BABYLON.serialize()
  28779. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  28780. __decorate([
  28781. BABYLON.serializeAsTexture()
  28782. ], PBRMaterial.prototype, "albedoTexture", void 0);
  28783. __decorate([
  28784. BABYLON.serializeAsTexture()
  28785. ], PBRMaterial.prototype, "ambientTexture", void 0);
  28786. __decorate([
  28787. BABYLON.serialize()
  28788. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  28789. __decorate([
  28790. BABYLON.serializeAsTexture()
  28791. ], PBRMaterial.prototype, "opacityTexture", void 0);
  28792. __decorate([
  28793. BABYLON.serializeAsTexture()
  28794. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  28795. __decorate([
  28796. BABYLON.serializeAsTexture()
  28797. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  28798. __decorate([
  28799. BABYLON.serializeAsTexture()
  28800. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  28801. __decorate([
  28802. BABYLON.serializeAsTexture()
  28803. ], PBRMaterial.prototype, "metallicTexture", void 0);
  28804. __decorate([
  28805. BABYLON.serialize()
  28806. ], PBRMaterial.prototype, "metallic", void 0);
  28807. __decorate([
  28808. BABYLON.serialize()
  28809. ], PBRMaterial.prototype, "roughness", void 0);
  28810. __decorate([
  28811. BABYLON.serializeAsTexture()
  28812. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  28813. __decorate([
  28814. BABYLON.serializeAsTexture()
  28815. ], PBRMaterial.prototype, "bumpTexture", void 0);
  28816. __decorate([
  28817. BABYLON.serializeAsTexture()
  28818. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  28819. __decorate([
  28820. BABYLON.serializeAsTexture()
  28821. ], PBRMaterial.prototype, "refractionTexture", void 0);
  28822. __decorate([
  28823. BABYLON.serializeAsColor3("ambient")
  28824. ], PBRMaterial.prototype, "ambientColor", void 0);
  28825. __decorate([
  28826. BABYLON.serializeAsColor3("albedo")
  28827. ], PBRMaterial.prototype, "albedoColor", void 0);
  28828. __decorate([
  28829. BABYLON.serializeAsColor3("reflectivity")
  28830. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  28831. __decorate([
  28832. BABYLON.serializeAsColor3("reflection")
  28833. ], PBRMaterial.prototype, "reflectionColor", void 0);
  28834. __decorate([
  28835. BABYLON.serializeAsColor3("emissive")
  28836. ], PBRMaterial.prototype, "emissiveColor", void 0);
  28837. __decorate([
  28838. BABYLON.serialize()
  28839. ], PBRMaterial.prototype, "microSurface", void 0);
  28840. __decorate([
  28841. BABYLON.serialize()
  28842. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  28843. __decorate([
  28844. BABYLON.serialize()
  28845. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  28846. __decorate([
  28847. BABYLON.serializeAsFresnelParameters()
  28848. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  28849. __decorate([
  28850. BABYLON.serializeAsFresnelParameters()
  28851. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  28852. __decorate([
  28853. BABYLON.serialize()
  28854. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  28855. __decorate([
  28856. BABYLON.serialize()
  28857. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  28858. __decorate([
  28859. BABYLON.serialize()
  28860. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  28861. __decorate([
  28862. BABYLON.serialize()
  28863. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  28864. __decorate([
  28865. BABYLON.serialize()
  28866. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  28867. __decorate([
  28868. BABYLON.serialize()
  28869. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  28870. __decorate([
  28871. BABYLON.serialize()
  28872. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  28873. __decorate([
  28874. BABYLON.serialize()
  28875. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  28876. __decorate([
  28877. BABYLON.serialize()
  28878. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  28879. __decorate([
  28880. BABYLON.serialize()
  28881. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  28882. __decorate([
  28883. BABYLON.serialize()
  28884. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  28885. __decorate([
  28886. BABYLON.serialize()
  28887. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  28888. __decorate([
  28889. BABYLON.serialize()
  28890. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  28891. __decorate([
  28892. BABYLON.serialize()
  28893. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  28894. __decorate([
  28895. BABYLON.serialize()
  28896. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  28897. __decorate([
  28898. BABYLON.serialize()
  28899. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  28900. __decorate([
  28901. BABYLON.serialize()
  28902. ], PBRMaterial.prototype, "useParallax", void 0);
  28903. __decorate([
  28904. BABYLON.serialize()
  28905. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  28906. __decorate([
  28907. BABYLON.serialize()
  28908. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  28909. __decorate([
  28910. BABYLON.serialize()
  28911. ], PBRMaterial.prototype, "disableLighting", void 0);
  28912. __decorate([
  28913. BABYLON.serialize()
  28914. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  28915. __decorate([
  28916. BABYLON.serialize()
  28917. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  28918. __decorate([
  28919. BABYLON.serialize()
  28920. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  28921. __decorate([
  28922. BABYLON.serialize()
  28923. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  28924. __decorate([
  28925. BABYLON.serialize()
  28926. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  28927. BABYLON.PBRMaterial = PBRMaterial;
  28928. })(BABYLON || (BABYLON = {}));
  28929. //# sourceMappingURL=babylon.pbrMaterial.js.map
  28930. var BABYLON;
  28931. (function (BABYLON) {
  28932. BABYLON.CameraInputTypes = {};
  28933. var CameraInputsManager = (function () {
  28934. function CameraInputsManager(camera) {
  28935. this.attached = {};
  28936. this.camera = camera;
  28937. this.checkInputs = function () { };
  28938. }
  28939. CameraInputsManager.prototype.add = function (input) {
  28940. var type = input.getSimpleName();
  28941. if (this.attached[type]) {
  28942. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  28943. return;
  28944. }
  28945. this.attached[type] = input;
  28946. input.camera = this.camera;
  28947. //for checkInputs, we are dynamically creating a function
  28948. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  28949. if (input.checkInputs) {
  28950. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  28951. }
  28952. if (this.attachedElement) {
  28953. input.attachControl(this.attachedElement);
  28954. }
  28955. };
  28956. CameraInputsManager.prototype.remove = function (inputToRemove) {
  28957. for (var cam in this.attached) {
  28958. var input = this.attached[cam];
  28959. if (input === inputToRemove) {
  28960. input.detachControl(this.attachedElement);
  28961. delete this.attached[cam];
  28962. this.rebuildInputCheck();
  28963. }
  28964. }
  28965. };
  28966. CameraInputsManager.prototype.removeByType = function (inputType) {
  28967. for (var cam in this.attached) {
  28968. var input = this.attached[cam];
  28969. if (input.getTypeName() === inputType) {
  28970. input.detachControl(this.attachedElement);
  28971. delete this.attached[cam];
  28972. this.rebuildInputCheck();
  28973. }
  28974. }
  28975. };
  28976. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  28977. var current = this.checkInputs;
  28978. return function () {
  28979. current();
  28980. fn();
  28981. };
  28982. };
  28983. CameraInputsManager.prototype.attachInput = function (input) {
  28984. input.attachControl(this.attachedElement, this.noPreventDefault);
  28985. };
  28986. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  28987. if (this.attachedElement) {
  28988. return;
  28989. }
  28990. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  28991. this.attachedElement = element;
  28992. this.noPreventDefault = noPreventDefault;
  28993. for (var cam in this.attached) {
  28994. var input = this.attached[cam];
  28995. this.attached[cam].attachControl(element, noPreventDefault);
  28996. }
  28997. };
  28998. CameraInputsManager.prototype.detachElement = function (element) {
  28999. if (this.attachedElement !== element) {
  29000. return;
  29001. }
  29002. for (var cam in this.attached) {
  29003. var input = this.attached[cam];
  29004. this.attached[cam].detachControl(element);
  29005. }
  29006. this.attachedElement = null;
  29007. };
  29008. CameraInputsManager.prototype.rebuildInputCheck = function () {
  29009. this.checkInputs = function () { };
  29010. for (var cam in this.attached) {
  29011. var input = this.attached[cam];
  29012. if (input.checkInputs) {
  29013. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29014. }
  29015. }
  29016. };
  29017. CameraInputsManager.prototype.clear = function () {
  29018. if (this.attachedElement) {
  29019. this.detachElement(this.attachedElement);
  29020. }
  29021. this.attached = {};
  29022. this.attachedElement = null;
  29023. this.checkInputs = function () { };
  29024. };
  29025. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  29026. var inputs = {};
  29027. for (var cam in this.attached) {
  29028. var input = this.attached[cam];
  29029. var res = BABYLON.SerializationHelper.Serialize(input);
  29030. inputs[input.getTypeName()] = res;
  29031. }
  29032. serializedCamera.inputsmgr = inputs;
  29033. };
  29034. CameraInputsManager.prototype.parse = function (parsedCamera) {
  29035. var parsedInputs = parsedCamera.inputsmgr;
  29036. if (parsedInputs) {
  29037. this.clear();
  29038. for (var n in parsedInputs) {
  29039. var construct = BABYLON.CameraInputTypes[n];
  29040. if (construct) {
  29041. var parsedinput = parsedInputs[n];
  29042. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  29043. this.add(input);
  29044. }
  29045. }
  29046. }
  29047. else {
  29048. //2016-03-08 this part is for managing backward compatibility
  29049. for (var n in this.attached) {
  29050. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  29051. if (construct) {
  29052. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  29053. this.remove(this.attached[n]);
  29054. this.add(input);
  29055. }
  29056. }
  29057. }
  29058. };
  29059. return CameraInputsManager;
  29060. }());
  29061. BABYLON.CameraInputsManager = CameraInputsManager;
  29062. })(BABYLON || (BABYLON = {}));
  29063. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  29064. var BABYLON;
  29065. (function (BABYLON) {
  29066. var FreeCameraMouseInput = (function () {
  29067. function FreeCameraMouseInput(touchEnabled) {
  29068. if (touchEnabled === void 0) { touchEnabled = true; }
  29069. this.touchEnabled = touchEnabled;
  29070. this.buttons = [0, 1, 2];
  29071. this.angularSensibility = 2000.0;
  29072. }
  29073. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  29074. var _this = this;
  29075. var engine = this.camera.getEngine();
  29076. if (!this._pointerInput) {
  29077. this._pointerInput = function (p, s) {
  29078. var evt = p.event;
  29079. if (!_this.touchEnabled && evt.pointerType === "touch") {
  29080. return;
  29081. }
  29082. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  29083. return;
  29084. }
  29085. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  29086. try {
  29087. evt.srcElement.setPointerCapture(evt.pointerId);
  29088. }
  29089. catch (e) {
  29090. //Nothing to do with the error. Execution will continue.
  29091. }
  29092. _this.previousPosition = {
  29093. x: evt.clientX,
  29094. y: evt.clientY
  29095. };
  29096. if (!noPreventDefault) {
  29097. evt.preventDefault();
  29098. element.focus();
  29099. }
  29100. }
  29101. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  29102. try {
  29103. evt.srcElement.releasePointerCapture(evt.pointerId);
  29104. }
  29105. catch (e) {
  29106. //Nothing to do with the error.
  29107. }
  29108. _this.previousPosition = null;
  29109. if (!noPreventDefault) {
  29110. evt.preventDefault();
  29111. }
  29112. }
  29113. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  29114. if (!_this.previousPosition || engine.isPointerLock) {
  29115. return;
  29116. }
  29117. var offsetX = evt.clientX - _this.previousPosition.x;
  29118. var offsetY = evt.clientY - _this.previousPosition.y;
  29119. if (_this.camera.getScene().useRightHandedSystem) {
  29120. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  29121. }
  29122. else {
  29123. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  29124. }
  29125. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  29126. _this.previousPosition = {
  29127. x: evt.clientX,
  29128. y: evt.clientY
  29129. };
  29130. if (!noPreventDefault) {
  29131. evt.preventDefault();
  29132. }
  29133. }
  29134. };
  29135. }
  29136. this._onMouseMove = function (evt) {
  29137. if (!engine.isPointerLock) {
  29138. return;
  29139. }
  29140. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  29141. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  29142. if (_this.camera.getScene().useRightHandedSystem) {
  29143. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  29144. }
  29145. else {
  29146. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  29147. }
  29148. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  29149. _this.previousPosition = null;
  29150. if (!noPreventDefault) {
  29151. evt.preventDefault();
  29152. }
  29153. };
  29154. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  29155. element.addEventListener("mousemove", this._onMouseMove, false);
  29156. };
  29157. FreeCameraMouseInput.prototype.detachControl = function (element) {
  29158. if (this._observer && element) {
  29159. this.camera.getScene().onPointerObservable.remove(this._observer);
  29160. element.removeEventListener("mousemove", this._onMouseMove);
  29161. this._observer = null;
  29162. this._onMouseMove = null;
  29163. this.previousPosition = null;
  29164. }
  29165. };
  29166. FreeCameraMouseInput.prototype.getTypeName = function () {
  29167. return "FreeCameraMouseInput";
  29168. };
  29169. FreeCameraMouseInput.prototype.getSimpleName = function () {
  29170. return "mouse";
  29171. };
  29172. return FreeCameraMouseInput;
  29173. }());
  29174. __decorate([
  29175. BABYLON.serialize()
  29176. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  29177. __decorate([
  29178. BABYLON.serialize()
  29179. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  29180. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  29181. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  29182. })(BABYLON || (BABYLON = {}));
  29183. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  29184. var BABYLON;
  29185. (function (BABYLON) {
  29186. var FreeCameraKeyboardMoveInput = (function () {
  29187. function FreeCameraKeyboardMoveInput() {
  29188. this._keys = [];
  29189. this.keysUp = [38];
  29190. this.keysDown = [40];
  29191. this.keysLeft = [37];
  29192. this.keysRight = [39];
  29193. }
  29194. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  29195. var _this = this;
  29196. if (!this._onKeyDown) {
  29197. element.tabIndex = 1;
  29198. this._onKeyDown = function (evt) {
  29199. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  29200. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  29201. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  29202. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  29203. var index = _this._keys.indexOf(evt.keyCode);
  29204. if (index === -1) {
  29205. _this._keys.push(evt.keyCode);
  29206. }
  29207. if (!noPreventDefault) {
  29208. evt.preventDefault();
  29209. }
  29210. }
  29211. };
  29212. this._onKeyUp = function (evt) {
  29213. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  29214. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  29215. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  29216. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  29217. var index = _this._keys.indexOf(evt.keyCode);
  29218. if (index >= 0) {
  29219. _this._keys.splice(index, 1);
  29220. }
  29221. if (!noPreventDefault) {
  29222. evt.preventDefault();
  29223. }
  29224. }
  29225. };
  29226. element.addEventListener("keydown", this._onKeyDown, false);
  29227. element.addEventListener("keyup", this._onKeyUp, false);
  29228. BABYLON.Tools.RegisterTopRootEvents([
  29229. { name: "blur", handler: this._onLostFocus }
  29230. ]);
  29231. }
  29232. };
  29233. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  29234. if (this._onKeyDown) {
  29235. element.removeEventListener("keydown", this._onKeyDown);
  29236. element.removeEventListener("keyup", this._onKeyUp);
  29237. BABYLON.Tools.UnregisterTopRootEvents([
  29238. { name: "blur", handler: this._onLostFocus }
  29239. ]);
  29240. this._keys = [];
  29241. this._onKeyDown = null;
  29242. this._onKeyUp = null;
  29243. }
  29244. };
  29245. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  29246. if (this._onKeyDown) {
  29247. var camera = this.camera;
  29248. // Keyboard
  29249. for (var index = 0; index < this._keys.length; index++) {
  29250. var keyCode = this._keys[index];
  29251. var speed = camera._computeLocalCameraSpeed();
  29252. if (this.keysLeft.indexOf(keyCode) !== -1) {
  29253. camera._localDirection.copyFromFloats(-speed, 0, 0);
  29254. }
  29255. else if (this.keysUp.indexOf(keyCode) !== -1) {
  29256. camera._localDirection.copyFromFloats(0, 0, speed);
  29257. }
  29258. else if (this.keysRight.indexOf(keyCode) !== -1) {
  29259. camera._localDirection.copyFromFloats(speed, 0, 0);
  29260. }
  29261. else if (this.keysDown.indexOf(keyCode) !== -1) {
  29262. camera._localDirection.copyFromFloats(0, 0, -speed);
  29263. }
  29264. if (camera.getScene().useRightHandedSystem) {
  29265. camera._localDirection.z *= -1;
  29266. }
  29267. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  29268. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  29269. camera.cameraDirection.addInPlace(camera._transformedDirection);
  29270. }
  29271. }
  29272. };
  29273. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  29274. return "FreeCameraKeyboardMoveInput";
  29275. };
  29276. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  29277. this._keys = [];
  29278. };
  29279. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  29280. return "keyboard";
  29281. };
  29282. return FreeCameraKeyboardMoveInput;
  29283. }());
  29284. __decorate([
  29285. BABYLON.serialize()
  29286. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  29287. __decorate([
  29288. BABYLON.serialize()
  29289. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  29290. __decorate([
  29291. BABYLON.serialize()
  29292. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  29293. __decorate([
  29294. BABYLON.serialize()
  29295. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  29296. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  29297. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  29298. })(BABYLON || (BABYLON = {}));
  29299. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  29300. var BABYLON;
  29301. (function (BABYLON) {
  29302. var FreeCameraInputsManager = (function (_super) {
  29303. __extends(FreeCameraInputsManager, _super);
  29304. function FreeCameraInputsManager(camera) {
  29305. return _super.call(this, camera) || this;
  29306. }
  29307. FreeCameraInputsManager.prototype.addKeyboard = function () {
  29308. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  29309. return this;
  29310. };
  29311. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  29312. if (touchEnabled === void 0) { touchEnabled = true; }
  29313. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  29314. return this;
  29315. };
  29316. FreeCameraInputsManager.prototype.addGamepad = function () {
  29317. this.add(new BABYLON.FreeCameraGamepadInput());
  29318. return this;
  29319. };
  29320. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  29321. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  29322. return this;
  29323. };
  29324. FreeCameraInputsManager.prototype.addTouch = function () {
  29325. this.add(new BABYLON.FreeCameraTouchInput());
  29326. return this;
  29327. };
  29328. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  29329. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  29330. return this;
  29331. };
  29332. return FreeCameraInputsManager;
  29333. }(BABYLON.CameraInputsManager));
  29334. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  29335. })(BABYLON || (BABYLON = {}));
  29336. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  29337. /// <reference path="babylon.camera.ts" />
  29338. var BABYLON;
  29339. (function (BABYLON) {
  29340. var TargetCamera = (function (_super) {
  29341. __extends(TargetCamera, _super);
  29342. function TargetCamera(name, position, scene) {
  29343. var _this = _super.call(this, name, position, scene) || this;
  29344. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  29345. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  29346. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  29347. _this.speed = 2.0;
  29348. _this.noRotationConstraint = false;
  29349. _this.lockedTarget = null;
  29350. _this._currentTarget = BABYLON.Vector3.Zero();
  29351. _this._viewMatrix = BABYLON.Matrix.Zero();
  29352. _this._camMatrix = BABYLON.Matrix.Zero();
  29353. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  29354. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  29355. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  29356. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  29357. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  29358. _this._lookAtTemp = BABYLON.Matrix.Zero();
  29359. _this._tempMatrix = BABYLON.Matrix.Zero();
  29360. return _this;
  29361. }
  29362. TargetCamera.prototype.getFrontPosition = function (distance) {
  29363. var direction = this.getTarget().subtract(this.position);
  29364. direction.normalize();
  29365. direction.scaleInPlace(distance);
  29366. return this.globalPosition.add(direction);
  29367. };
  29368. TargetCamera.prototype._getLockedTargetPosition = function () {
  29369. if (!this.lockedTarget) {
  29370. return null;
  29371. }
  29372. if (this.lockedTarget.absolutePosition) {
  29373. this.lockedTarget.computeWorldMatrix();
  29374. }
  29375. return this.lockedTarget.absolutePosition || this.lockedTarget;
  29376. };
  29377. // Cache
  29378. TargetCamera.prototype._initCache = function () {
  29379. _super.prototype._initCache.call(this);
  29380. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29381. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29382. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29383. };
  29384. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  29385. if (!ignoreParentClass) {
  29386. _super.prototype._updateCache.call(this);
  29387. }
  29388. var lockedTargetPosition = this._getLockedTargetPosition();
  29389. if (!lockedTargetPosition) {
  29390. this._cache.lockedTarget = null;
  29391. }
  29392. else {
  29393. if (!this._cache.lockedTarget) {
  29394. this._cache.lockedTarget = lockedTargetPosition.clone();
  29395. }
  29396. else {
  29397. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  29398. }
  29399. }
  29400. this._cache.rotation.copyFrom(this.rotation);
  29401. if (this.rotationQuaternion)
  29402. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29403. };
  29404. // Synchronized
  29405. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  29406. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  29407. return false;
  29408. }
  29409. var lockedTargetPosition = this._getLockedTargetPosition();
  29410. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  29411. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  29412. };
  29413. // Methods
  29414. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  29415. var engine = this.getEngine();
  29416. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  29417. };
  29418. // Target
  29419. TargetCamera.prototype.setTarget = function (target) {
  29420. this.upVector.normalize();
  29421. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  29422. this._camMatrix.invert();
  29423. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  29424. var vDir = target.subtract(this.position);
  29425. if (vDir.x >= 0.0) {
  29426. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  29427. }
  29428. else {
  29429. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  29430. }
  29431. this.rotation.z = 0;
  29432. if (isNaN(this.rotation.x)) {
  29433. this.rotation.x = 0;
  29434. }
  29435. if (isNaN(this.rotation.y)) {
  29436. this.rotation.y = 0;
  29437. }
  29438. if (isNaN(this.rotation.z)) {
  29439. this.rotation.z = 0;
  29440. }
  29441. if (this.rotationQuaternion) {
  29442. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  29443. }
  29444. };
  29445. /**
  29446. * Return the current target position of the camera. This value is expressed in local space.
  29447. */
  29448. TargetCamera.prototype.getTarget = function () {
  29449. return this._currentTarget;
  29450. };
  29451. TargetCamera.prototype._decideIfNeedsToMove = function () {
  29452. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  29453. };
  29454. TargetCamera.prototype._updatePosition = function () {
  29455. if (this.parent) {
  29456. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  29457. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  29458. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  29459. return;
  29460. }
  29461. this.position.addInPlace(this.cameraDirection);
  29462. };
  29463. TargetCamera.prototype._checkInputs = function () {
  29464. var needToMove = this._decideIfNeedsToMove();
  29465. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  29466. // Move
  29467. if (needToMove) {
  29468. this._updatePosition();
  29469. }
  29470. // Rotate
  29471. if (needToRotate) {
  29472. this.rotation.x += this.cameraRotation.x;
  29473. this.rotation.y += this.cameraRotation.y;
  29474. //rotate, if quaternion is set and rotation was used
  29475. if (this.rotationQuaternion) {
  29476. var len = this.rotation.lengthSquared();
  29477. if (len) {
  29478. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  29479. }
  29480. }
  29481. if (!this.noRotationConstraint) {
  29482. var limit = (Math.PI / 2) * 0.95;
  29483. if (this.rotation.x > limit)
  29484. this.rotation.x = limit;
  29485. if (this.rotation.x < -limit)
  29486. this.rotation.x = -limit;
  29487. }
  29488. }
  29489. // Inertia
  29490. if (needToMove) {
  29491. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  29492. this.cameraDirection.x = 0;
  29493. }
  29494. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  29495. this.cameraDirection.y = 0;
  29496. }
  29497. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  29498. this.cameraDirection.z = 0;
  29499. }
  29500. this.cameraDirection.scaleInPlace(this.inertia);
  29501. }
  29502. if (needToRotate) {
  29503. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  29504. this.cameraRotation.x = 0;
  29505. }
  29506. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  29507. this.cameraRotation.y = 0;
  29508. }
  29509. this.cameraRotation.scaleInPlace(this.inertia);
  29510. }
  29511. _super.prototype._checkInputs.call(this);
  29512. };
  29513. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  29514. if (this.rotationQuaternion) {
  29515. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  29516. //update the up vector!
  29517. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  29518. }
  29519. else {
  29520. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  29521. }
  29522. };
  29523. TargetCamera.prototype._getViewMatrix = function () {
  29524. if (!this.lockedTarget) {
  29525. // Compute
  29526. this._updateCameraRotationMatrix();
  29527. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  29528. // Computing target and final matrix
  29529. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  29530. }
  29531. else {
  29532. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  29533. }
  29534. if (this.getScene().useRightHandedSystem) {
  29535. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  29536. }
  29537. else {
  29538. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  29539. }
  29540. return this._viewMatrix;
  29541. };
  29542. /**
  29543. * @override
  29544. * Override Camera.createRigCamera
  29545. */
  29546. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  29547. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29548. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  29549. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  29550. if (!this.rotationQuaternion) {
  29551. this.rotationQuaternion = new BABYLON.Quaternion();
  29552. }
  29553. rigCamera._cameraRigParams = {};
  29554. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  29555. }
  29556. return rigCamera;
  29557. }
  29558. return null;
  29559. };
  29560. /**
  29561. * @override
  29562. * Override Camera._updateRigCameras
  29563. */
  29564. TargetCamera.prototype._updateRigCameras = function () {
  29565. var camLeft = this._rigCameras[0];
  29566. var camRight = this._rigCameras[1];
  29567. switch (this.cameraRigMode) {
  29568. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  29569. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  29570. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  29571. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  29572. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  29573. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  29574. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  29575. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  29576. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  29577. camLeft.setTarget(this.getTarget());
  29578. camRight.setTarget(this.getTarget());
  29579. break;
  29580. case BABYLON.Camera.RIG_MODE_VR:
  29581. if (camLeft.rotationQuaternion) {
  29582. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29583. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29584. }
  29585. else {
  29586. camLeft.rotation.copyFrom(this.rotation);
  29587. camRight.rotation.copyFrom(this.rotation);
  29588. }
  29589. camLeft.position.copyFrom(this.position);
  29590. camRight.position.copyFrom(this.position);
  29591. break;
  29592. }
  29593. _super.prototype._updateRigCameras.call(this);
  29594. };
  29595. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  29596. if (!this._rigCamTransformMatrix) {
  29597. this._rigCamTransformMatrix = new BABYLON.Matrix();
  29598. }
  29599. var target = this.getTarget();
  29600. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  29601. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  29602. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  29603. };
  29604. TargetCamera.prototype.getClassName = function () {
  29605. return "TargetCamera";
  29606. };
  29607. return TargetCamera;
  29608. }(BABYLON.Camera));
  29609. __decorate([
  29610. BABYLON.serializeAsVector3()
  29611. ], TargetCamera.prototype, "rotation", void 0);
  29612. __decorate([
  29613. BABYLON.serialize()
  29614. ], TargetCamera.prototype, "speed", void 0);
  29615. __decorate([
  29616. BABYLON.serializeAsMeshReference("lockedTargetId")
  29617. ], TargetCamera.prototype, "lockedTarget", void 0);
  29618. BABYLON.TargetCamera = TargetCamera;
  29619. })(BABYLON || (BABYLON = {}));
  29620. //# sourceMappingURL=babylon.targetCamera.js.map
  29621. var BABYLON;
  29622. (function (BABYLON) {
  29623. var FreeCamera = (function (_super) {
  29624. __extends(FreeCamera, _super);
  29625. function FreeCamera(name, position, scene) {
  29626. var _this = _super.call(this, name, position, scene) || this;
  29627. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  29628. _this.checkCollisions = false;
  29629. _this.applyGravity = false;
  29630. _this._needMoveForGravity = false;
  29631. _this._oldPosition = BABYLON.Vector3.Zero();
  29632. _this._diffPosition = BABYLON.Vector3.Zero();
  29633. _this._newPosition = BABYLON.Vector3.Zero();
  29634. // Collisions
  29635. _this._collisionMask = -1;
  29636. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  29637. if (collidedMesh === void 0) { collidedMesh = null; }
  29638. //TODO move this to the collision coordinator!
  29639. if (_this.getScene().workerCollisions)
  29640. newPosition.multiplyInPlace(_this._collider.radius);
  29641. var updatePosition = function (newPos) {
  29642. _this._newPosition.copyFrom(newPos);
  29643. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  29644. var oldPosition = _this.position.clone();
  29645. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  29646. _this.position.addInPlace(_this._diffPosition);
  29647. if (_this.onCollide && collidedMesh) {
  29648. _this.onCollide(collidedMesh);
  29649. }
  29650. }
  29651. };
  29652. updatePosition(newPosition);
  29653. };
  29654. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  29655. _this.inputs.addKeyboard().addMouse();
  29656. return _this;
  29657. }
  29658. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  29659. //-- begin properties for backward compatibility for inputs
  29660. get: function () {
  29661. var mouse = this.inputs.attached["mouse"];
  29662. if (mouse)
  29663. return mouse.angularSensibility;
  29664. },
  29665. set: function (value) {
  29666. var mouse = this.inputs.attached["mouse"];
  29667. if (mouse)
  29668. mouse.angularSensibility = value;
  29669. },
  29670. enumerable: true,
  29671. configurable: true
  29672. });
  29673. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  29674. get: function () {
  29675. var keyboard = this.inputs.attached["keyboard"];
  29676. if (keyboard)
  29677. return keyboard.keysUp;
  29678. },
  29679. set: function (value) {
  29680. var keyboard = this.inputs.attached["keyboard"];
  29681. if (keyboard)
  29682. keyboard.keysUp = value;
  29683. },
  29684. enumerable: true,
  29685. configurable: true
  29686. });
  29687. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  29688. get: function () {
  29689. var keyboard = this.inputs.attached["keyboard"];
  29690. if (keyboard)
  29691. return keyboard.keysDown;
  29692. },
  29693. set: function (value) {
  29694. var keyboard = this.inputs.attached["keyboard"];
  29695. if (keyboard)
  29696. keyboard.keysDown = value;
  29697. },
  29698. enumerable: true,
  29699. configurable: true
  29700. });
  29701. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  29702. get: function () {
  29703. var keyboard = this.inputs.attached["keyboard"];
  29704. if (keyboard)
  29705. return keyboard.keysLeft;
  29706. },
  29707. set: function (value) {
  29708. var keyboard = this.inputs.attached["keyboard"];
  29709. if (keyboard)
  29710. keyboard.keysLeft = value;
  29711. },
  29712. enumerable: true,
  29713. configurable: true
  29714. });
  29715. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  29716. get: function () {
  29717. var keyboard = this.inputs.attached["keyboard"];
  29718. if (keyboard)
  29719. return keyboard.keysRight;
  29720. },
  29721. set: function (value) {
  29722. var keyboard = this.inputs.attached["keyboard"];
  29723. if (keyboard)
  29724. keyboard.keysRight = value;
  29725. },
  29726. enumerable: true,
  29727. configurable: true
  29728. });
  29729. // Controls
  29730. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29731. this.inputs.attachElement(element, noPreventDefault);
  29732. };
  29733. FreeCamera.prototype.detachControl = function (element) {
  29734. this.inputs.detachElement(element);
  29735. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  29736. this.cameraRotation = new BABYLON.Vector2(0, 0);
  29737. };
  29738. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  29739. get: function () {
  29740. return this._collisionMask;
  29741. },
  29742. set: function (mask) {
  29743. this._collisionMask = !isNaN(mask) ? mask : -1;
  29744. },
  29745. enumerable: true,
  29746. configurable: true
  29747. });
  29748. FreeCamera.prototype._collideWithWorld = function (velocity) {
  29749. var globalPosition;
  29750. if (this.parent) {
  29751. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  29752. }
  29753. else {
  29754. globalPosition = this.position;
  29755. }
  29756. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  29757. if (!this._collider) {
  29758. this._collider = new BABYLON.Collider();
  29759. }
  29760. this._collider.radius = this.ellipsoid;
  29761. this._collider.collisionMask = this._collisionMask;
  29762. //no need for clone, as long as gravity is not on.
  29763. var actualVelocity = velocity;
  29764. //add gravity to the velocity to prevent the dual-collision checking
  29765. if (this.applyGravity) {
  29766. //this prevents mending with cameraDirection, a global variable of the free camera class.
  29767. actualVelocity = velocity.add(this.getScene().gravity);
  29768. }
  29769. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  29770. };
  29771. FreeCamera.prototype._checkInputs = function () {
  29772. if (!this._localDirection) {
  29773. this._localDirection = BABYLON.Vector3.Zero();
  29774. this._transformedDirection = BABYLON.Vector3.Zero();
  29775. }
  29776. this.inputs.checkInputs();
  29777. _super.prototype._checkInputs.call(this);
  29778. };
  29779. FreeCamera.prototype._decideIfNeedsToMove = function () {
  29780. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  29781. };
  29782. FreeCamera.prototype._updatePosition = function () {
  29783. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  29784. this._collideWithWorld(this.cameraDirection);
  29785. }
  29786. else {
  29787. _super.prototype._updatePosition.call(this);
  29788. }
  29789. };
  29790. FreeCamera.prototype.dispose = function () {
  29791. this.inputs.clear();
  29792. _super.prototype.dispose.call(this);
  29793. };
  29794. FreeCamera.prototype.getClassName = function () {
  29795. return "FreeCamera";
  29796. };
  29797. return FreeCamera;
  29798. }(BABYLON.TargetCamera));
  29799. __decorate([
  29800. BABYLON.serializeAsVector3()
  29801. ], FreeCamera.prototype, "ellipsoid", void 0);
  29802. __decorate([
  29803. BABYLON.serialize()
  29804. ], FreeCamera.prototype, "checkCollisions", void 0);
  29805. __decorate([
  29806. BABYLON.serialize()
  29807. ], FreeCamera.prototype, "applyGravity", void 0);
  29808. BABYLON.FreeCamera = FreeCamera;
  29809. })(BABYLON || (BABYLON = {}));
  29810. //# sourceMappingURL=babylon.freeCamera.js.map
  29811. var BABYLON;
  29812. (function (BABYLON) {
  29813. var ArcRotateCameraKeyboardMoveInput = (function () {
  29814. function ArcRotateCameraKeyboardMoveInput() {
  29815. this._keys = [];
  29816. this.keysUp = [38];
  29817. this.keysDown = [40];
  29818. this.keysLeft = [37];
  29819. this.keysRight = [39];
  29820. }
  29821. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  29822. var _this = this;
  29823. element.tabIndex = 1;
  29824. this._onKeyDown = function (evt) {
  29825. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  29826. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  29827. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  29828. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  29829. var index = _this._keys.indexOf(evt.keyCode);
  29830. if (index === -1) {
  29831. _this._keys.push(evt.keyCode);
  29832. }
  29833. if (evt.preventDefault) {
  29834. if (!noPreventDefault) {
  29835. evt.preventDefault();
  29836. }
  29837. }
  29838. }
  29839. };
  29840. this._onKeyUp = function (evt) {
  29841. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  29842. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  29843. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  29844. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  29845. var index = _this._keys.indexOf(evt.keyCode);
  29846. if (index >= 0) {
  29847. _this._keys.splice(index, 1);
  29848. }
  29849. if (evt.preventDefault) {
  29850. if (!noPreventDefault) {
  29851. evt.preventDefault();
  29852. }
  29853. }
  29854. }
  29855. };
  29856. this._onLostFocus = function () {
  29857. _this._keys = [];
  29858. };
  29859. element.addEventListener("keydown", this._onKeyDown, false);
  29860. element.addEventListener("keyup", this._onKeyUp, false);
  29861. BABYLON.Tools.RegisterTopRootEvents([
  29862. { name: "blur", handler: this._onLostFocus }
  29863. ]);
  29864. };
  29865. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  29866. if (element) {
  29867. element.removeEventListener("keydown", this._onKeyDown);
  29868. element.removeEventListener("keyup", this._onKeyUp);
  29869. }
  29870. BABYLON.Tools.UnregisterTopRootEvents([
  29871. { name: "blur", handler: this._onLostFocus }
  29872. ]);
  29873. this._keys = [];
  29874. this._onKeyDown = null;
  29875. this._onKeyUp = null;
  29876. this._onLostFocus = null;
  29877. };
  29878. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  29879. if (this._onKeyDown) {
  29880. var camera = this.camera;
  29881. for (var index = 0; index < this._keys.length; index++) {
  29882. var keyCode = this._keys[index];
  29883. if (this.keysLeft.indexOf(keyCode) !== -1) {
  29884. camera.inertialAlphaOffset -= 0.01;
  29885. }
  29886. else if (this.keysUp.indexOf(keyCode) !== -1) {
  29887. camera.inertialBetaOffset -= 0.01;
  29888. }
  29889. else if (this.keysRight.indexOf(keyCode) !== -1) {
  29890. camera.inertialAlphaOffset += 0.01;
  29891. }
  29892. else if (this.keysDown.indexOf(keyCode) !== -1) {
  29893. camera.inertialBetaOffset += 0.01;
  29894. }
  29895. }
  29896. }
  29897. };
  29898. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  29899. return "ArcRotateCameraKeyboardMoveInput";
  29900. };
  29901. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  29902. return "keyboard";
  29903. };
  29904. return ArcRotateCameraKeyboardMoveInput;
  29905. }());
  29906. __decorate([
  29907. BABYLON.serialize()
  29908. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  29909. __decorate([
  29910. BABYLON.serialize()
  29911. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  29912. __decorate([
  29913. BABYLON.serialize()
  29914. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  29915. __decorate([
  29916. BABYLON.serialize()
  29917. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  29918. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  29919. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  29920. })(BABYLON || (BABYLON = {}));
  29921. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  29922. var BABYLON;
  29923. (function (BABYLON) {
  29924. var ArcRotateCameraMouseWheelInput = (function () {
  29925. function ArcRotateCameraMouseWheelInput() {
  29926. this.wheelPrecision = 3.0;
  29927. }
  29928. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  29929. var _this = this;
  29930. this._wheel = function (p, s) {
  29931. //sanity check - this should be a PointerWheel event.
  29932. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  29933. return;
  29934. var event = p.event;
  29935. var delta = 0;
  29936. if (event.wheelDelta) {
  29937. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  29938. }
  29939. else if (event.detail) {
  29940. delta = -event.detail / _this.wheelPrecision;
  29941. }
  29942. if (delta)
  29943. _this.camera.inertialRadiusOffset += delta;
  29944. if (event.preventDefault) {
  29945. if (!noPreventDefault) {
  29946. event.preventDefault();
  29947. }
  29948. }
  29949. };
  29950. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  29951. };
  29952. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  29953. if (this._observer && element) {
  29954. this.camera.getScene().onPointerObservable.remove(this._observer);
  29955. this._observer = null;
  29956. this._wheel = null;
  29957. }
  29958. };
  29959. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  29960. return "ArcRotateCameraMouseWheelInput";
  29961. };
  29962. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  29963. return "mousewheel";
  29964. };
  29965. return ArcRotateCameraMouseWheelInput;
  29966. }());
  29967. __decorate([
  29968. BABYLON.serialize()
  29969. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  29970. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  29971. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  29972. })(BABYLON || (BABYLON = {}));
  29973. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  29974. var BABYLON;
  29975. (function (BABYLON) {
  29976. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  29977. var ArcRotateCameraPointersInput = (function () {
  29978. function ArcRotateCameraPointersInput() {
  29979. this.buttons = [0, 1, 2];
  29980. this.angularSensibilityX = 1000.0;
  29981. this.angularSensibilityY = 1000.0;
  29982. this.pinchPrecision = 6.0;
  29983. this.panningSensibility = 50.0;
  29984. this._isPanClick = false;
  29985. this.pinchInwards = true;
  29986. }
  29987. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  29988. var _this = this;
  29989. var engine = this.camera.getEngine();
  29990. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  29991. var pointA, pointB;
  29992. var previousPinchDistance = 0;
  29993. this._pointerInput = function (p, s) {
  29994. var evt = p.event;
  29995. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  29996. return;
  29997. }
  29998. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  29999. try {
  30000. evt.srcElement.setPointerCapture(evt.pointerId);
  30001. }
  30002. catch (e) {
  30003. //Nothing to do with the error. Execution will continue.
  30004. }
  30005. // Manage panning with pan button click
  30006. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  30007. // manage pointers
  30008. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  30009. if (pointA === undefined) {
  30010. pointA = cacheSoloPointer;
  30011. }
  30012. else if (pointB === undefined) {
  30013. pointB = cacheSoloPointer;
  30014. }
  30015. if (!noPreventDefault) {
  30016. evt.preventDefault();
  30017. element.focus();
  30018. }
  30019. }
  30020. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  30021. try {
  30022. evt.srcElement.releasePointerCapture(evt.pointerId);
  30023. }
  30024. catch (e) {
  30025. //Nothing to do with the error.
  30026. }
  30027. cacheSoloPointer = null;
  30028. previousPinchDistance = 0;
  30029. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  30030. //but emptying completly pointers collection is required to fix a bug on iPhone :
  30031. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  30032. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  30033. pointA = pointB = undefined;
  30034. if (!noPreventDefault) {
  30035. evt.preventDefault();
  30036. }
  30037. }
  30038. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  30039. if (!noPreventDefault) {
  30040. evt.preventDefault();
  30041. }
  30042. // One button down
  30043. if (pointA && pointB === undefined) {
  30044. if (_this.panningSensibility !== 0 &&
  30045. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  30046. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  30047. _this.camera
  30048. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  30049. _this.camera
  30050. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  30051. }
  30052. else {
  30053. var offsetX = evt.clientX - cacheSoloPointer.x;
  30054. var offsetY = evt.clientY - cacheSoloPointer.y;
  30055. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30056. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30057. }
  30058. cacheSoloPointer.x = evt.clientX;
  30059. cacheSoloPointer.y = evt.clientY;
  30060. }
  30061. else if (pointA && pointB) {
  30062. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  30063. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  30064. ed.x = evt.clientX;
  30065. ed.y = evt.clientY;
  30066. var direction = _this.pinchInwards ? 1 : -1;
  30067. var distX = pointA.x - pointB.x;
  30068. var distY = pointA.y - pointB.y;
  30069. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  30070. if (previousPinchDistance === 0) {
  30071. previousPinchDistance = pinchSquaredDistance;
  30072. return;
  30073. }
  30074. if (pinchSquaredDistance !== previousPinchDistance) {
  30075. _this.camera
  30076. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  30077. (_this.pinchPrecision *
  30078. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  30079. direction);
  30080. previousPinchDistance = pinchSquaredDistance;
  30081. }
  30082. }
  30083. }
  30084. };
  30085. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  30086. this._onContextMenu = function (evt) {
  30087. evt.preventDefault();
  30088. };
  30089. if (!this.camera._useCtrlForPanning) {
  30090. element.addEventListener("contextmenu", this._onContextMenu, false);
  30091. }
  30092. this._onLostFocus = function () {
  30093. //this._keys = [];
  30094. pointA = pointB = undefined;
  30095. previousPinchDistance = 0;
  30096. cacheSoloPointer = null;
  30097. };
  30098. this._onMouseMove = function (evt) {
  30099. if (!engine.isPointerLock) {
  30100. return;
  30101. }
  30102. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  30103. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  30104. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30105. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30106. if (!noPreventDefault) {
  30107. evt.preventDefault();
  30108. }
  30109. };
  30110. this._onGestureStart = function (e) {
  30111. if (window.MSGesture === undefined) {
  30112. return;
  30113. }
  30114. if (!_this._MSGestureHandler) {
  30115. _this._MSGestureHandler = new MSGesture();
  30116. _this._MSGestureHandler.target = element;
  30117. }
  30118. _this._MSGestureHandler.addPointer(e.pointerId);
  30119. };
  30120. this._onGesture = function (e) {
  30121. _this.camera.radius *= e.scale;
  30122. if (e.preventDefault) {
  30123. if (!noPreventDefault) {
  30124. e.stopPropagation();
  30125. e.preventDefault();
  30126. }
  30127. }
  30128. };
  30129. element.addEventListener("mousemove", this._onMouseMove, false);
  30130. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  30131. element.addEventListener("MSGestureChange", this._onGesture, false);
  30132. element.addEventListener("keydown", this._onKeyDown, false);
  30133. element.addEventListener("keyup", this._onKeyUp, false);
  30134. BABYLON.Tools.RegisterTopRootEvents([
  30135. { name: "blur", handler: this._onLostFocus }
  30136. ]);
  30137. };
  30138. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  30139. if (element && this._observer) {
  30140. this.camera.getScene().onPointerObservable.remove(this._observer);
  30141. this._observer = null;
  30142. element.removeEventListener("contextmenu", this._onContextMenu);
  30143. element.removeEventListener("mousemove", this._onMouseMove);
  30144. element.removeEventListener("MSPointerDown", this._onGestureStart);
  30145. element.removeEventListener("MSGestureChange", this._onGesture);
  30146. element.removeEventListener("keydown", this._onKeyDown);
  30147. element.removeEventListener("keyup", this._onKeyUp);
  30148. this._isPanClick = false;
  30149. this.pinchInwards = true;
  30150. this._onKeyDown = null;
  30151. this._onKeyUp = null;
  30152. this._onMouseMove = null;
  30153. this._onGestureStart = null;
  30154. this._onGesture = null;
  30155. this._MSGestureHandler = null;
  30156. this._onLostFocus = null;
  30157. this._onContextMenu = null;
  30158. }
  30159. BABYLON.Tools.UnregisterTopRootEvents([
  30160. { name: "blur", handler: this._onLostFocus }
  30161. ]);
  30162. };
  30163. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  30164. return "ArcRotateCameraPointersInput";
  30165. };
  30166. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  30167. return "pointers";
  30168. };
  30169. return ArcRotateCameraPointersInput;
  30170. }());
  30171. __decorate([
  30172. BABYLON.serialize()
  30173. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  30174. __decorate([
  30175. BABYLON.serialize()
  30176. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  30177. __decorate([
  30178. BABYLON.serialize()
  30179. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  30180. __decorate([
  30181. BABYLON.serialize()
  30182. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  30183. __decorate([
  30184. BABYLON.serialize()
  30185. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  30186. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  30187. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  30188. })(BABYLON || (BABYLON = {}));
  30189. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  30190. /// <reference path="babylon.targetCamera.ts" />
  30191. /// <reference path="..\Tools\babylon.tools.ts" />
  30192. var BABYLON;
  30193. (function (BABYLON) {
  30194. var ArcRotateCamera = (function (_super) {
  30195. __extends(ArcRotateCamera, _super);
  30196. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  30197. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  30198. _this.inertialAlphaOffset = 0;
  30199. _this.inertialBetaOffset = 0;
  30200. _this.inertialRadiusOffset = 0;
  30201. _this.lowerAlphaLimit = null;
  30202. _this.upperAlphaLimit = null;
  30203. _this.lowerBetaLimit = 0.01;
  30204. _this.upperBetaLimit = Math.PI;
  30205. _this.lowerRadiusLimit = null;
  30206. _this.upperRadiusLimit = null;
  30207. _this.inertialPanningX = 0;
  30208. _this.inertialPanningY = 0;
  30209. //-- end properties for backward compatibility for inputs
  30210. _this.zoomOnFactor = 1;
  30211. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  30212. _this.allowUpsideDown = true;
  30213. _this._viewMatrix = new BABYLON.Matrix();
  30214. // Panning
  30215. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  30216. _this.checkCollisions = false;
  30217. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  30218. _this._previousPosition = BABYLON.Vector3.Zero();
  30219. _this._collisionVelocity = BABYLON.Vector3.Zero();
  30220. _this._newPosition = BABYLON.Vector3.Zero();
  30221. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  30222. if (collidedMesh === void 0) { collidedMesh = null; }
  30223. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  30224. newPosition.multiplyInPlace(_this._collider.radius);
  30225. }
  30226. if (!collidedMesh) {
  30227. _this._previousPosition.copyFrom(_this.position);
  30228. }
  30229. else {
  30230. _this.setPosition(newPosition);
  30231. if (_this.onCollide) {
  30232. _this.onCollide(collidedMesh);
  30233. }
  30234. }
  30235. // Recompute because of constraints
  30236. var cosa = Math.cos(_this.alpha);
  30237. var sina = Math.sin(_this.alpha);
  30238. var cosb = Math.cos(_this.beta);
  30239. var sinb = Math.sin(_this.beta);
  30240. if (sinb === 0) {
  30241. sinb = 0.0001;
  30242. }
  30243. var target = _this._getTargetPosition();
  30244. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  30245. _this.position.copyFrom(_this._newPosition);
  30246. var up = _this.upVector;
  30247. if (_this.allowUpsideDown && _this.beta < 0) {
  30248. up = up.clone();
  30249. up = up.negate();
  30250. }
  30251. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  30252. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  30253. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  30254. _this._collisionTriggered = false;
  30255. };
  30256. if (!target) {
  30257. _this.target = BABYLON.Vector3.Zero();
  30258. }
  30259. else {
  30260. _this.target = target;
  30261. }
  30262. _this.alpha = alpha;
  30263. _this.beta = beta;
  30264. _this.radius = radius;
  30265. _this.getViewMatrix();
  30266. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  30267. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  30268. return _this;
  30269. }
  30270. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  30271. //-- begin properties for backward compatibility for inputs
  30272. get: function () {
  30273. var pointers = this.inputs.attached["pointers"];
  30274. if (pointers)
  30275. return pointers.angularSensibilityX;
  30276. },
  30277. set: function (value) {
  30278. var pointers = this.inputs.attached["pointers"];
  30279. if (pointers) {
  30280. pointers.angularSensibilityX = value;
  30281. }
  30282. },
  30283. enumerable: true,
  30284. configurable: true
  30285. });
  30286. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  30287. get: function () {
  30288. var pointers = this.inputs.attached["pointers"];
  30289. if (pointers)
  30290. return pointers.angularSensibilityY;
  30291. },
  30292. set: function (value) {
  30293. var pointers = this.inputs.attached["pointers"];
  30294. if (pointers) {
  30295. pointers.angularSensibilityY = value;
  30296. }
  30297. },
  30298. enumerable: true,
  30299. configurable: true
  30300. });
  30301. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  30302. get: function () {
  30303. var pointers = this.inputs.attached["pointers"];
  30304. if (pointers)
  30305. return pointers.pinchPrecision;
  30306. },
  30307. set: function (value) {
  30308. var pointers = this.inputs.attached["pointers"];
  30309. if (pointers) {
  30310. pointers.pinchPrecision = value;
  30311. }
  30312. },
  30313. enumerable: true,
  30314. configurable: true
  30315. });
  30316. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  30317. get: function () {
  30318. var pointers = this.inputs.attached["pointers"];
  30319. if (pointers)
  30320. return pointers.panningSensibility;
  30321. },
  30322. set: function (value) {
  30323. var pointers = this.inputs.attached["pointers"];
  30324. if (pointers) {
  30325. pointers.panningSensibility = value;
  30326. }
  30327. },
  30328. enumerable: true,
  30329. configurable: true
  30330. });
  30331. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  30332. get: function () {
  30333. var keyboard = this.inputs.attached["keyboard"];
  30334. if (keyboard)
  30335. return keyboard.keysUp;
  30336. },
  30337. set: function (value) {
  30338. var keyboard = this.inputs.attached["keyboard"];
  30339. if (keyboard)
  30340. keyboard.keysUp = value;
  30341. },
  30342. enumerable: true,
  30343. configurable: true
  30344. });
  30345. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  30346. get: function () {
  30347. var keyboard = this.inputs.attached["keyboard"];
  30348. if (keyboard)
  30349. return keyboard.keysDown;
  30350. },
  30351. set: function (value) {
  30352. var keyboard = this.inputs.attached["keyboard"];
  30353. if (keyboard)
  30354. keyboard.keysDown = value;
  30355. },
  30356. enumerable: true,
  30357. configurable: true
  30358. });
  30359. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  30360. get: function () {
  30361. var keyboard = this.inputs.attached["keyboard"];
  30362. if (keyboard)
  30363. return keyboard.keysLeft;
  30364. },
  30365. set: function (value) {
  30366. var keyboard = this.inputs.attached["keyboard"];
  30367. if (keyboard)
  30368. keyboard.keysLeft = value;
  30369. },
  30370. enumerable: true,
  30371. configurable: true
  30372. });
  30373. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  30374. get: function () {
  30375. var keyboard = this.inputs.attached["keyboard"];
  30376. if (keyboard)
  30377. return keyboard.keysRight;
  30378. },
  30379. set: function (value) {
  30380. var keyboard = this.inputs.attached["keyboard"];
  30381. if (keyboard)
  30382. keyboard.keysRight = value;
  30383. },
  30384. enumerable: true,
  30385. configurable: true
  30386. });
  30387. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  30388. get: function () {
  30389. var mousewheel = this.inputs.attached["mousewheel"];
  30390. if (mousewheel)
  30391. return mousewheel.wheelPrecision;
  30392. },
  30393. set: function (value) {
  30394. var mousewheel = this.inputs.attached["mousewheel"];
  30395. if (mousewheel)
  30396. mousewheel.wheelPrecision = value;
  30397. },
  30398. enumerable: true,
  30399. configurable: true
  30400. });
  30401. // Cache
  30402. ArcRotateCamera.prototype._initCache = function () {
  30403. _super.prototype._initCache.call(this);
  30404. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30405. this._cache.alpha = undefined;
  30406. this._cache.beta = undefined;
  30407. this._cache.radius = undefined;
  30408. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  30409. };
  30410. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  30411. if (!ignoreParentClass) {
  30412. _super.prototype._updateCache.call(this);
  30413. }
  30414. this._cache.target.copyFrom(this._getTargetPosition());
  30415. this._cache.alpha = this.alpha;
  30416. this._cache.beta = this.beta;
  30417. this._cache.radius = this.radius;
  30418. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  30419. };
  30420. ArcRotateCamera.prototype._getTargetPosition = function () {
  30421. if (this.target.getAbsolutePosition) {
  30422. var pos = this.target.getAbsolutePosition();
  30423. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  30424. }
  30425. return this.target;
  30426. };
  30427. // Synchronized
  30428. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  30429. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  30430. return false;
  30431. return this._cache.target.equals(this.target)
  30432. && this._cache.alpha === this.alpha
  30433. && this._cache.beta === this.beta
  30434. && this._cache.radius === this.radius
  30435. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  30436. };
  30437. // Methods
  30438. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  30439. var _this = this;
  30440. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  30441. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  30442. this._useCtrlForPanning = useCtrlForPanning;
  30443. this._panningMouseButton = panningMouseButton;
  30444. this.inputs.attachElement(element, noPreventDefault);
  30445. this._reset = function () {
  30446. _this.inertialAlphaOffset = 0;
  30447. _this.inertialBetaOffset = 0;
  30448. _this.inertialRadiusOffset = 0;
  30449. };
  30450. };
  30451. ArcRotateCamera.prototype.detachControl = function (element) {
  30452. this.inputs.detachElement(element);
  30453. if (this._reset) {
  30454. this._reset();
  30455. }
  30456. };
  30457. ArcRotateCamera.prototype._checkInputs = function () {
  30458. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  30459. if (this._collisionTriggered) {
  30460. return;
  30461. }
  30462. this.inputs.checkInputs();
  30463. // Inertia
  30464. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  30465. if (this.getScene().useRightHandedSystem) {
  30466. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  30467. }
  30468. else {
  30469. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  30470. }
  30471. this.beta += this.inertialBetaOffset;
  30472. this.radius -= this.inertialRadiusOffset;
  30473. this.inertialAlphaOffset *= this.inertia;
  30474. this.inertialBetaOffset *= this.inertia;
  30475. this.inertialRadiusOffset *= this.inertia;
  30476. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  30477. this.inertialAlphaOffset = 0;
  30478. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  30479. this.inertialBetaOffset = 0;
  30480. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  30481. this.inertialRadiusOffset = 0;
  30482. }
  30483. // Panning inertia
  30484. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  30485. if (!this._localDirection) {
  30486. this._localDirection = BABYLON.Vector3.Zero();
  30487. this._transformedDirection = BABYLON.Vector3.Zero();
  30488. }
  30489. this.inertialPanningX *= this.inertia;
  30490. this.inertialPanningY *= this.inertia;
  30491. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  30492. this.inertialPanningX = 0;
  30493. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  30494. this.inertialPanningY = 0;
  30495. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  30496. this._localDirection.multiplyInPlace(this.panningAxis);
  30497. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  30498. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  30499. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  30500. if (!this.panningAxis.y) {
  30501. this._transformedDirection.y = 0;
  30502. }
  30503. if (!this.target.getAbsolutePosition) {
  30504. this.target.addInPlace(this._transformedDirection);
  30505. }
  30506. }
  30507. // Limits
  30508. this._checkLimits();
  30509. _super.prototype._checkInputs.call(this);
  30510. };
  30511. ArcRotateCamera.prototype._checkLimits = function () {
  30512. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  30513. if (this.allowUpsideDown && this.beta > Math.PI) {
  30514. this.beta = this.beta - (2 * Math.PI);
  30515. }
  30516. }
  30517. else {
  30518. if (this.beta < this.lowerBetaLimit) {
  30519. this.beta = this.lowerBetaLimit;
  30520. }
  30521. }
  30522. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  30523. if (this.allowUpsideDown && this.beta < -Math.PI) {
  30524. this.beta = this.beta + (2 * Math.PI);
  30525. }
  30526. }
  30527. else {
  30528. if (this.beta > this.upperBetaLimit) {
  30529. this.beta = this.upperBetaLimit;
  30530. }
  30531. }
  30532. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  30533. this.alpha = this.lowerAlphaLimit;
  30534. }
  30535. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  30536. this.alpha = this.upperAlphaLimit;
  30537. }
  30538. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  30539. this.radius = this.lowerRadiusLimit;
  30540. }
  30541. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  30542. this.radius = this.upperRadiusLimit;
  30543. }
  30544. };
  30545. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  30546. var radiusv3 = this.position.subtract(this._getTargetPosition());
  30547. this.radius = radiusv3.length();
  30548. // Alpha
  30549. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  30550. if (radiusv3.z < 0) {
  30551. this.alpha = 2 * Math.PI - this.alpha;
  30552. }
  30553. // Beta
  30554. this.beta = Math.acos(radiusv3.y / this.radius);
  30555. this._checkLimits();
  30556. };
  30557. ArcRotateCamera.prototype.setPosition = function (position) {
  30558. if (this.position.equals(position)) {
  30559. return;
  30560. }
  30561. this.position.copyFrom(position);
  30562. this.rebuildAnglesAndRadius();
  30563. };
  30564. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  30565. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  30566. if (allowSamePosition === void 0) { allowSamePosition = false; }
  30567. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  30568. return;
  30569. }
  30570. if (toBoundingCenter && target.getBoundingInfo) {
  30571. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  30572. }
  30573. else {
  30574. this._targetBoundingCenter = null;
  30575. }
  30576. this.target = target;
  30577. this.rebuildAnglesAndRadius();
  30578. };
  30579. ArcRotateCamera.prototype._getViewMatrix = function () {
  30580. // Compute
  30581. var cosa = Math.cos(this.alpha);
  30582. var sina = Math.sin(this.alpha);
  30583. var cosb = Math.cos(this.beta);
  30584. var sinb = Math.sin(this.beta);
  30585. if (sinb === 0) {
  30586. sinb = 0.0001;
  30587. }
  30588. var target = this._getTargetPosition();
  30589. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  30590. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  30591. if (!this._collider) {
  30592. this._collider = new BABYLON.Collider();
  30593. }
  30594. this._collider.radius = this.collisionRadius;
  30595. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  30596. this._collisionTriggered = true;
  30597. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  30598. }
  30599. else {
  30600. this.position.copyFrom(this._newPosition);
  30601. var up = this.upVector;
  30602. if (this.allowUpsideDown && sinb < 0) {
  30603. up = up.clone();
  30604. up = up.negate();
  30605. }
  30606. if (this.getScene().useRightHandedSystem) {
  30607. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  30608. }
  30609. else {
  30610. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  30611. }
  30612. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  30613. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  30614. }
  30615. this._currentTarget = target;
  30616. return this._viewMatrix;
  30617. };
  30618. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  30619. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  30620. meshes = meshes || this.getScene().meshes;
  30621. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  30622. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  30623. this.radius = distance * this.zoomOnFactor;
  30624. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  30625. };
  30626. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  30627. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  30628. var meshesOrMinMaxVector;
  30629. var distance;
  30630. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  30631. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  30632. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  30633. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  30634. }
  30635. else {
  30636. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  30637. distance = meshesOrMinMaxVectorAndDistance.distance;
  30638. }
  30639. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  30640. if (!doNotUpdateMaxZ) {
  30641. this.maxZ = distance * 2;
  30642. }
  30643. };
  30644. /**
  30645. * @override
  30646. * Override Camera.createRigCamera
  30647. */
  30648. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  30649. var alphaShift;
  30650. switch (this.cameraRigMode) {
  30651. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30652. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30653. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30654. case BABYLON.Camera.RIG_MODE_VR:
  30655. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  30656. break;
  30657. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30658. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  30659. break;
  30660. }
  30661. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  30662. rigCam._cameraRigParams = {};
  30663. return rigCam;
  30664. };
  30665. /**
  30666. * @override
  30667. * Override Camera._updateRigCameras
  30668. */
  30669. ArcRotateCamera.prototype._updateRigCameras = function () {
  30670. var camLeft = this._rigCameras[0];
  30671. var camRight = this._rigCameras[1];
  30672. camLeft.beta = camRight.beta = this.beta;
  30673. camLeft.radius = camRight.radius = this.radius;
  30674. switch (this.cameraRigMode) {
  30675. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30676. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30677. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30678. case BABYLON.Camera.RIG_MODE_VR:
  30679. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  30680. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  30681. break;
  30682. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30683. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  30684. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  30685. break;
  30686. }
  30687. _super.prototype._updateRigCameras.call(this);
  30688. };
  30689. ArcRotateCamera.prototype.dispose = function () {
  30690. this.inputs.clear();
  30691. _super.prototype.dispose.call(this);
  30692. };
  30693. ArcRotateCamera.prototype.getClassName = function () {
  30694. return "ArcRotateCamera";
  30695. };
  30696. return ArcRotateCamera;
  30697. }(BABYLON.TargetCamera));
  30698. __decorate([
  30699. BABYLON.serialize()
  30700. ], ArcRotateCamera.prototype, "alpha", void 0);
  30701. __decorate([
  30702. BABYLON.serialize()
  30703. ], ArcRotateCamera.prototype, "beta", void 0);
  30704. __decorate([
  30705. BABYLON.serialize()
  30706. ], ArcRotateCamera.prototype, "radius", void 0);
  30707. __decorate([
  30708. BABYLON.serializeAsVector3()
  30709. ], ArcRotateCamera.prototype, "target", void 0);
  30710. __decorate([
  30711. BABYLON.serialize()
  30712. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  30713. __decorate([
  30714. BABYLON.serialize()
  30715. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  30716. __decorate([
  30717. BABYLON.serialize()
  30718. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  30719. __decorate([
  30720. BABYLON.serialize()
  30721. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  30722. __decorate([
  30723. BABYLON.serialize()
  30724. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  30725. __decorate([
  30726. BABYLON.serialize()
  30727. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  30728. __decorate([
  30729. BABYLON.serialize()
  30730. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  30731. __decorate([
  30732. BABYLON.serialize()
  30733. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  30734. __decorate([
  30735. BABYLON.serialize()
  30736. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  30737. __decorate([
  30738. BABYLON.serialize()
  30739. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  30740. __decorate([
  30741. BABYLON.serialize()
  30742. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  30743. __decorate([
  30744. BABYLON.serialize()
  30745. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  30746. __decorate([
  30747. BABYLON.serialize()
  30748. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  30749. BABYLON.ArcRotateCamera = ArcRotateCamera;
  30750. })(BABYLON || (BABYLON = {}));
  30751. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  30752. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  30753. var BABYLON;
  30754. (function (BABYLON) {
  30755. var ArcRotateCameraInputsManager = (function (_super) {
  30756. __extends(ArcRotateCameraInputsManager, _super);
  30757. function ArcRotateCameraInputsManager(camera) {
  30758. return _super.call(this, camera) || this;
  30759. }
  30760. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  30761. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  30762. return this;
  30763. };
  30764. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  30765. this.add(new BABYLON.ArcRotateCameraPointersInput());
  30766. return this;
  30767. };
  30768. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  30769. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  30770. return this;
  30771. };
  30772. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  30773. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  30774. return this;
  30775. };
  30776. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  30777. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  30778. return this;
  30779. };
  30780. return ArcRotateCameraInputsManager;
  30781. }(BABYLON.CameraInputsManager));
  30782. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  30783. })(BABYLON || (BABYLON = {}));
  30784. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  30785. var BABYLON;
  30786. (function (BABYLON) {
  30787. var HemisphericLight = (function (_super) {
  30788. __extends(HemisphericLight, _super);
  30789. /**
  30790. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  30791. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  30792. * The HemisphericLight can't cast shadows.
  30793. * Documentation : http://doc.babylonjs.com/tutorials/lights
  30794. */
  30795. function HemisphericLight(name, direction, scene) {
  30796. var _this = _super.call(this, name, scene) || this;
  30797. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  30798. _this.direction = direction;
  30799. return _this;
  30800. }
  30801. /**
  30802. * Returns the string "HemisphericLight".
  30803. */
  30804. HemisphericLight.prototype.getClassName = function () {
  30805. return "HemisphericLight";
  30806. };
  30807. /**
  30808. * Sets the HemisphericLight direction towards the passed target (Vector3).
  30809. * Returns the updated direction.
  30810. */
  30811. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  30812. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  30813. return this.direction;
  30814. };
  30815. HemisphericLight.prototype.getShadowGenerator = function () {
  30816. return null;
  30817. };
  30818. /**
  30819. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  30820. * Returns the HemisphericLight.
  30821. */
  30822. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  30823. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  30824. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0);
  30825. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  30826. return this;
  30827. };
  30828. HemisphericLight.prototype._getWorldMatrix = function () {
  30829. if (!this._worldMatrix) {
  30830. this._worldMatrix = BABYLON.Matrix.Identity();
  30831. }
  30832. return this._worldMatrix;
  30833. };
  30834. /**
  30835. * Returns the integer 3.
  30836. */
  30837. HemisphericLight.prototype.getTypeID = function () {
  30838. return 3;
  30839. };
  30840. return HemisphericLight;
  30841. }(BABYLON.Light));
  30842. __decorate([
  30843. BABYLON.serializeAsColor3()
  30844. ], HemisphericLight.prototype, "groundColor", void 0);
  30845. __decorate([
  30846. BABYLON.serializeAsVector3()
  30847. ], HemisphericLight.prototype, "direction", void 0);
  30848. BABYLON.HemisphericLight = HemisphericLight;
  30849. })(BABYLON || (BABYLON = {}));
  30850. //# sourceMappingURL=babylon.hemisphericLight.js.map
  30851. var BABYLON;
  30852. (function (BABYLON) {
  30853. var PointLight = (function (_super) {
  30854. __extends(PointLight, _super);
  30855. /**
  30856. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  30857. * A PointLight emits the light in every direction.
  30858. * It can cast shadows.
  30859. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  30860. * ```javascript
  30861. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  30862. * ```
  30863. * Documentation : http://doc.babylonjs.com/tutorials/lights
  30864. */
  30865. function PointLight(name, position, scene) {
  30866. var _this = _super.call(this, name, scene) || this;
  30867. _this.position = position;
  30868. return _this;
  30869. }
  30870. /**
  30871. * Returns the string "PointLight"
  30872. */
  30873. PointLight.prototype.getClassName = function () {
  30874. return "PointLight";
  30875. };
  30876. /**
  30877. * Returns a Vector3, the PointLight absolute position in the World.
  30878. */
  30879. PointLight.prototype.getAbsolutePosition = function () {
  30880. return this.transformedPosition ? this.transformedPosition : this.position;
  30881. };
  30882. /**
  30883. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  30884. */
  30885. PointLight.prototype.computeTransformedPosition = function () {
  30886. if (this.parent && this.parent.getWorldMatrix) {
  30887. if (!this.transformedPosition) {
  30888. this.transformedPosition = BABYLON.Vector3.Zero();
  30889. }
  30890. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  30891. return true;
  30892. }
  30893. return false;
  30894. };
  30895. /**
  30896. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  30897. * Returns the PointLight.
  30898. */
  30899. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  30900. if (this.parent && this.parent.getWorldMatrix) {
  30901. this.computeTransformedPosition();
  30902. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0);
  30903. return this;
  30904. }
  30905. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  30906. return this;
  30907. };
  30908. /**
  30909. * Boolean : returns true by default.
  30910. */
  30911. PointLight.prototype.needCube = function () {
  30912. return true;
  30913. };
  30914. /**
  30915. * Boolean : returns false by default.
  30916. */
  30917. PointLight.prototype.needRefreshPerFrame = function () {
  30918. return false;
  30919. };
  30920. /**
  30921. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  30922. */
  30923. PointLight.prototype.getShadowDirection = function (faceIndex) {
  30924. switch (faceIndex) {
  30925. case 0:
  30926. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  30927. case 1:
  30928. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  30929. case 2:
  30930. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  30931. case 3:
  30932. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  30933. case 4:
  30934. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  30935. case 5:
  30936. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  30937. }
  30938. return BABYLON.Vector3.Zero();
  30939. };
  30940. /**
  30941. * Return the depth scale used for the shadow map.
  30942. */
  30943. PointLight.prototype.getDepthScale = function () {
  30944. return 30.0;
  30945. };
  30946. /**
  30947. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  30948. * - fov = PI / 2
  30949. * - aspect ratio : 1.0
  30950. * - z-near and far equal to the active camera minZ and maxZ.
  30951. * Returns the PointLight.
  30952. */
  30953. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  30954. if (this.customProjectionMatrixBuilder) {
  30955. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  30956. }
  30957. else {
  30958. var activeCamera = this.getScene().activeCamera;
  30959. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  30960. }
  30961. return this;
  30962. };
  30963. PointLight.prototype._getWorldMatrix = function () {
  30964. if (!this._worldMatrix) {
  30965. this._worldMatrix = BABYLON.Matrix.Identity();
  30966. }
  30967. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  30968. return this._worldMatrix;
  30969. };
  30970. /**
  30971. * Returns the integer 0.
  30972. */
  30973. PointLight.prototype.getTypeID = function () {
  30974. return 0;
  30975. };
  30976. return PointLight;
  30977. }(BABYLON.Light));
  30978. __decorate([
  30979. BABYLON.serializeAsVector3()
  30980. ], PointLight.prototype, "position", void 0);
  30981. __decorate([
  30982. BABYLON.serialize()
  30983. ], PointLight.prototype, "shadowMinZ", void 0);
  30984. __decorate([
  30985. BABYLON.serialize()
  30986. ], PointLight.prototype, "shadowMaxZ", void 0);
  30987. BABYLON.PointLight = PointLight;
  30988. })(BABYLON || (BABYLON = {}));
  30989. //# sourceMappingURL=babylon.pointLight.js.map
  30990. /// <reference path="babylon.light.ts" />
  30991. var BABYLON;
  30992. (function (BABYLON) {
  30993. var DirectionalLight = (function (_super) {
  30994. __extends(DirectionalLight, _super);
  30995. /**
  30996. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  30997. * The directional light is emitted from everywhere in the given direction.
  30998. * It can cast shawdows.
  30999. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31000. */
  31001. function DirectionalLight(name, direction, scene) {
  31002. var _this = _super.call(this, name, scene) || this;
  31003. _this.shadowOrthoScale = 0.5;
  31004. _this.autoUpdateExtends = true;
  31005. // Cache
  31006. _this._orthoLeft = Number.MAX_VALUE;
  31007. _this._orthoRight = Number.MIN_VALUE;
  31008. _this._orthoTop = Number.MIN_VALUE;
  31009. _this._orthoBottom = Number.MAX_VALUE;
  31010. _this.position = direction.scale(-1.0);
  31011. _this.direction = direction;
  31012. return _this;
  31013. }
  31014. /**
  31015. * Returns the string "DirectionalLight".
  31016. */
  31017. DirectionalLight.prototype.getClassName = function () {
  31018. return "DirectionalLight";
  31019. };
  31020. /**
  31021. * Returns the DirectionalLight absolute position in the World.
  31022. */
  31023. DirectionalLight.prototype.getAbsolutePosition = function () {
  31024. return this.transformedPosition ? this.transformedPosition : this.position;
  31025. };
  31026. /**
  31027. * Sets the DirectionalLight direction toward the passed target (Vector3).
  31028. * Returns the updated DirectionalLight direction (Vector3).
  31029. */
  31030. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  31031. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  31032. return this.direction;
  31033. };
  31034. /**
  31035. * Return the depth scale used for the shadow map.
  31036. */
  31037. DirectionalLight.prototype.getDepthScale = function () {
  31038. return 30.0;
  31039. };
  31040. /**
  31041. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  31042. * Returns the DirectionalLight.
  31043. */
  31044. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  31045. if (this.customProjectionMatrixBuilder) {
  31046. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  31047. }
  31048. else {
  31049. var activeCamera = this.getScene().activeCamera;
  31050. // Check extends
  31051. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  31052. var tempVector3 = BABYLON.Vector3.Zero();
  31053. this._orthoLeft = Number.MAX_VALUE;
  31054. this._orthoRight = Number.MIN_VALUE;
  31055. this._orthoTop = Number.MIN_VALUE;
  31056. this._orthoBottom = Number.MAX_VALUE;
  31057. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  31058. var mesh = renderList[meshIndex];
  31059. if (!mesh) {
  31060. continue;
  31061. }
  31062. var boundingInfo = mesh.getBoundingInfo();
  31063. if (!boundingInfo) {
  31064. continue;
  31065. }
  31066. var boundingBox = boundingInfo.boundingBox;
  31067. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  31068. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  31069. if (tempVector3.x < this._orthoLeft)
  31070. this._orthoLeft = tempVector3.x;
  31071. if (tempVector3.y < this._orthoBottom)
  31072. this._orthoBottom = tempVector3.y;
  31073. if (tempVector3.x > this._orthoRight)
  31074. this._orthoRight = tempVector3.x;
  31075. if (tempVector3.y > this._orthoTop)
  31076. this._orthoTop = tempVector3.y;
  31077. }
  31078. }
  31079. }
  31080. var xOffset = this._orthoRight - this._orthoLeft;
  31081. var yOffset = this._orthoTop - this._orthoBottom;
  31082. 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);
  31083. }
  31084. return this;
  31085. };
  31086. /**
  31087. * Boolean : true by default.
  31088. */
  31089. DirectionalLight.prototype.needRefreshPerFrame = function () {
  31090. return true;
  31091. };
  31092. /**
  31093. * Boolean : false by default.
  31094. */
  31095. DirectionalLight.prototype.needCube = function () {
  31096. return false;
  31097. };
  31098. /**
  31099. * Returns the light direction (Vector3) for any passed face index.
  31100. */
  31101. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  31102. return this.direction;
  31103. };
  31104. /**
  31105. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  31106. */
  31107. DirectionalLight.prototype.computeTransformedPosition = function () {
  31108. if (this.parent && this.parent.getWorldMatrix) {
  31109. if (!this.transformedPosition) {
  31110. this.transformedPosition = BABYLON.Vector3.Zero();
  31111. }
  31112. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  31113. return true;
  31114. }
  31115. return false;
  31116. };
  31117. /**
  31118. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  31119. * Returns the DirectionalLight.
  31120. */
  31121. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  31122. if (this.parent && this.parent.getWorldMatrix) {
  31123. if (!this._transformedDirection) {
  31124. this._transformedDirection = BABYLON.Vector3.Zero();
  31125. }
  31126. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  31127. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  31128. return this;
  31129. }
  31130. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  31131. return this;
  31132. };
  31133. DirectionalLight.prototype._getWorldMatrix = function () {
  31134. if (!this._worldMatrix) {
  31135. this._worldMatrix = BABYLON.Matrix.Identity();
  31136. }
  31137. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  31138. return this._worldMatrix;
  31139. };
  31140. /**
  31141. * Returns the integer 1.
  31142. */
  31143. DirectionalLight.prototype.getTypeID = function () {
  31144. return 1;
  31145. };
  31146. return DirectionalLight;
  31147. }(BABYLON.Light));
  31148. __decorate([
  31149. BABYLON.serializeAsVector3()
  31150. ], DirectionalLight.prototype, "position", void 0);
  31151. __decorate([
  31152. BABYLON.serializeAsVector3()
  31153. ], DirectionalLight.prototype, "direction", void 0);
  31154. __decorate([
  31155. BABYLON.serialize()
  31156. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  31157. __decorate([
  31158. BABYLON.serialize()
  31159. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  31160. __decorate([
  31161. BABYLON.serialize()
  31162. ], DirectionalLight.prototype, "shadowMinZ", void 0);
  31163. __decorate([
  31164. BABYLON.serialize()
  31165. ], DirectionalLight.prototype, "shadowMaxZ", void 0);
  31166. BABYLON.DirectionalLight = DirectionalLight;
  31167. })(BABYLON || (BABYLON = {}));
  31168. //# sourceMappingURL=babylon.directionalLight.js.map
  31169. var BABYLON;
  31170. (function (BABYLON) {
  31171. var SpotLight = (function (_super) {
  31172. __extends(SpotLight, _super);
  31173. /**
  31174. * Creates a SpotLight object in the scene with the passed parameters :
  31175. * - `position` (Vector3) is the initial SpotLight position,
  31176. * - `direction` (Vector3) is the initial SpotLight direction,
  31177. * - `angle` (float, in radians) is the spot light cone angle,
  31178. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  31179. * A spot light is a simply light oriented cone.
  31180. * It can cast shadows.
  31181. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31182. */
  31183. function SpotLight(name, position, direction, angle, exponent, scene) {
  31184. var _this = _super.call(this, name, scene) || this;
  31185. _this.position = position;
  31186. _this.direction = direction;
  31187. _this.angle = angle;
  31188. _this.exponent = exponent;
  31189. return _this;
  31190. }
  31191. /**
  31192. * Returns the string "SpotLight".
  31193. */
  31194. SpotLight.prototype.getClassName = function () {
  31195. return "SpotLight";
  31196. };
  31197. /**
  31198. * Returns the SpotLight absolute position in the World (Vector3).
  31199. */
  31200. SpotLight.prototype.getAbsolutePosition = function () {
  31201. return this.transformedPosition ? this.transformedPosition : this.position;
  31202. };
  31203. /**
  31204. * Return the depth scale used for the shadow map.
  31205. */
  31206. SpotLight.prototype.getDepthScale = function () {
  31207. return 30.0;
  31208. };
  31209. /**
  31210. * 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.
  31211. * Returns the SpotLight.
  31212. */
  31213. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  31214. if (this.customProjectionMatrixBuilder) {
  31215. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  31216. }
  31217. else {
  31218. var activeCamera = this.getScene().activeCamera;
  31219. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  31220. }
  31221. return this;
  31222. };
  31223. /**
  31224. * Boolean : false by default.
  31225. */
  31226. SpotLight.prototype.needCube = function () {
  31227. return false;
  31228. };
  31229. /**
  31230. * Boolean : false by default.
  31231. */
  31232. SpotLight.prototype.needRefreshPerFrame = function () {
  31233. return false;
  31234. };
  31235. /**
  31236. * Returns the SpotLight direction (Vector3) for any passed face index.
  31237. */
  31238. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  31239. return this.direction;
  31240. };
  31241. /**
  31242. * Updates the SpotLight direction towards the passed target (Vector3).
  31243. * Returns the updated direction.
  31244. */
  31245. SpotLight.prototype.setDirectionToTarget = function (target) {
  31246. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  31247. return this.direction;
  31248. };
  31249. /**
  31250. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  31251. */
  31252. SpotLight.prototype.computeTransformedPosition = function () {
  31253. if (this.parent && this.parent.getWorldMatrix) {
  31254. if (!this.transformedPosition) {
  31255. this.transformedPosition = BABYLON.Vector3.Zero();
  31256. }
  31257. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  31258. return true;
  31259. }
  31260. return false;
  31261. };
  31262. /**
  31263. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  31264. * Return the SpotLight.
  31265. */
  31266. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  31267. var normalizeDirection;
  31268. if (this.parent && this.parent.getWorldMatrix) {
  31269. if (!this._transformedDirection) {
  31270. this._transformedDirection = BABYLON.Vector3.Zero();
  31271. }
  31272. this.computeTransformedPosition();
  31273. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  31274. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  31275. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  31276. }
  31277. else {
  31278. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  31279. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  31280. }
  31281. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  31282. return this;
  31283. };
  31284. SpotLight.prototype._getWorldMatrix = function () {
  31285. if (!this._worldMatrix) {
  31286. this._worldMatrix = BABYLON.Matrix.Identity();
  31287. }
  31288. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  31289. return this._worldMatrix;
  31290. };
  31291. /**
  31292. * Returns the integer 2.
  31293. */
  31294. SpotLight.prototype.getTypeID = function () {
  31295. return 2;
  31296. };
  31297. /**
  31298. * Returns the SpotLight rotation (Vector3).
  31299. */
  31300. SpotLight.prototype.getRotation = function () {
  31301. this.direction.normalize();
  31302. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  31303. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  31304. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  31305. };
  31306. return SpotLight;
  31307. }(BABYLON.Light));
  31308. __decorate([
  31309. BABYLON.serializeAsVector3()
  31310. ], SpotLight.prototype, "position", void 0);
  31311. __decorate([
  31312. BABYLON.serializeAsVector3()
  31313. ], SpotLight.prototype, "direction", void 0);
  31314. __decorate([
  31315. BABYLON.serialize()
  31316. ], SpotLight.prototype, "angle", void 0);
  31317. __decorate([
  31318. BABYLON.serialize()
  31319. ], SpotLight.prototype, "exponent", void 0);
  31320. __decorate([
  31321. BABYLON.serialize()
  31322. ], SpotLight.prototype, "shadowMinZ", void 0);
  31323. __decorate([
  31324. BABYLON.serialize()
  31325. ], SpotLight.prototype, "shadowMaxZ", void 0);
  31326. BABYLON.SpotLight = SpotLight;
  31327. })(BABYLON || (BABYLON = {}));
  31328. //# sourceMappingURL=babylon.spotLight.js.map
  31329. var BABYLON;
  31330. (function (BABYLON) {
  31331. var AnimationRange = (function () {
  31332. function AnimationRange(name, from, to) {
  31333. this.name = name;
  31334. this.from = from;
  31335. this.to = to;
  31336. }
  31337. AnimationRange.prototype.clone = function () {
  31338. return new AnimationRange(this.name, this.from, this.to);
  31339. };
  31340. return AnimationRange;
  31341. }());
  31342. BABYLON.AnimationRange = AnimationRange;
  31343. /**
  31344. * Composed of a frame, and an action function
  31345. */
  31346. var AnimationEvent = (function () {
  31347. function AnimationEvent(frame, action, onlyOnce) {
  31348. this.frame = frame;
  31349. this.action = action;
  31350. this.onlyOnce = onlyOnce;
  31351. this.isDone = false;
  31352. }
  31353. return AnimationEvent;
  31354. }());
  31355. BABYLON.AnimationEvent = AnimationEvent;
  31356. var PathCursor = (function () {
  31357. function PathCursor(path) {
  31358. this.path = path;
  31359. this._onchange = new Array();
  31360. this.value = 0;
  31361. this.animations = new Array();
  31362. }
  31363. PathCursor.prototype.getPoint = function () {
  31364. var point = this.path.getPointAtLengthPosition(this.value);
  31365. return new BABYLON.Vector3(point.x, 0, point.y);
  31366. };
  31367. PathCursor.prototype.moveAhead = function (step) {
  31368. if (step === void 0) { step = 0.002; }
  31369. this.move(step);
  31370. return this;
  31371. };
  31372. PathCursor.prototype.moveBack = function (step) {
  31373. if (step === void 0) { step = 0.002; }
  31374. this.move(-step);
  31375. return this;
  31376. };
  31377. PathCursor.prototype.move = function (step) {
  31378. if (Math.abs(step) > 1) {
  31379. throw "step size should be less than 1.";
  31380. }
  31381. this.value += step;
  31382. this.ensureLimits();
  31383. this.raiseOnChange();
  31384. return this;
  31385. };
  31386. PathCursor.prototype.ensureLimits = function () {
  31387. while (this.value > 1) {
  31388. this.value -= 1;
  31389. }
  31390. while (this.value < 0) {
  31391. this.value += 1;
  31392. }
  31393. return this;
  31394. };
  31395. // used by animation engine
  31396. PathCursor.prototype.markAsDirty = function (propertyName) {
  31397. this.ensureLimits();
  31398. this.raiseOnChange();
  31399. return this;
  31400. };
  31401. PathCursor.prototype.raiseOnChange = function () {
  31402. var _this = this;
  31403. this._onchange.forEach(function (f) { return f(_this); });
  31404. return this;
  31405. };
  31406. PathCursor.prototype.onchange = function (f) {
  31407. this._onchange.push(f);
  31408. return this;
  31409. };
  31410. return PathCursor;
  31411. }());
  31412. BABYLON.PathCursor = PathCursor;
  31413. var Animation = (function () {
  31414. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  31415. this.name = name;
  31416. this.targetProperty = targetProperty;
  31417. this.framePerSecond = framePerSecond;
  31418. this.dataType = dataType;
  31419. this.loopMode = loopMode;
  31420. this.enableBlending = enableBlending;
  31421. this._offsetsCache = {};
  31422. this._highLimitsCache = {};
  31423. this._stopped = false;
  31424. this._blendingFactor = 0;
  31425. // The set of event that will be linked to this animation
  31426. this._events = new Array();
  31427. this.allowMatricesInterpolation = false;
  31428. this.blendingSpeed = 0.01;
  31429. this._ranges = {};
  31430. this.targetPropertyPath = targetProperty.split(".");
  31431. this.dataType = dataType;
  31432. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  31433. }
  31434. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  31435. var dataType = undefined;
  31436. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  31437. dataType = Animation.ANIMATIONTYPE_FLOAT;
  31438. }
  31439. else if (from instanceof BABYLON.Quaternion) {
  31440. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  31441. }
  31442. else if (from instanceof BABYLON.Vector3) {
  31443. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  31444. }
  31445. else if (from instanceof BABYLON.Vector2) {
  31446. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  31447. }
  31448. else if (from instanceof BABYLON.Color3) {
  31449. dataType = Animation.ANIMATIONTYPE_COLOR3;
  31450. }
  31451. else if (from instanceof BABYLON.Size) {
  31452. dataType = Animation.ANIMATIONTYPE_SIZE;
  31453. }
  31454. if (dataType == undefined) {
  31455. return null;
  31456. }
  31457. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  31458. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  31459. animation.setKeys(keys);
  31460. if (easingFunction !== undefined) {
  31461. animation.setEasingFunction(easingFunction);
  31462. }
  31463. return animation;
  31464. };
  31465. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  31466. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  31467. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  31468. };
  31469. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  31470. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  31471. node.animations.push(animation);
  31472. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  31473. };
  31474. // Methods
  31475. /**
  31476. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31477. */
  31478. Animation.prototype.toString = function (fullDetails) {
  31479. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  31480. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  31481. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  31482. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  31483. if (fullDetails) {
  31484. ret += ", Ranges: {";
  31485. var first = true;
  31486. for (var name in this._ranges) {
  31487. if (first) {
  31488. ret += ", ";
  31489. first = false;
  31490. }
  31491. ret += name;
  31492. }
  31493. ret += "}";
  31494. }
  31495. return ret;
  31496. };
  31497. /**
  31498. * Add an event to this animation.
  31499. */
  31500. Animation.prototype.addEvent = function (event) {
  31501. this._events.push(event);
  31502. };
  31503. /**
  31504. * Remove all events found at the given frame
  31505. * @param frame
  31506. */
  31507. Animation.prototype.removeEvents = function (frame) {
  31508. for (var index = 0; index < this._events.length; index++) {
  31509. if (this._events[index].frame === frame) {
  31510. this._events.splice(index, 1);
  31511. index--;
  31512. }
  31513. }
  31514. };
  31515. Animation.prototype.createRange = function (name, from, to) {
  31516. // check name not already in use; could happen for bones after serialized
  31517. if (!this._ranges[name]) {
  31518. this._ranges[name] = new AnimationRange(name, from, to);
  31519. }
  31520. };
  31521. Animation.prototype.deleteRange = function (name, deleteFrames) {
  31522. if (deleteFrames === void 0) { deleteFrames = true; }
  31523. if (this._ranges[name]) {
  31524. if (deleteFrames) {
  31525. var from = this._ranges[name].from;
  31526. var to = this._ranges[name].to;
  31527. // this loop MUST go high to low for multiple splices to work
  31528. for (var key = this._keys.length - 1; key >= 0; key--) {
  31529. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  31530. this._keys.splice(key, 1);
  31531. }
  31532. }
  31533. }
  31534. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  31535. }
  31536. };
  31537. Animation.prototype.getRange = function (name) {
  31538. return this._ranges[name];
  31539. };
  31540. Animation.prototype.reset = function () {
  31541. this._offsetsCache = {};
  31542. this._highLimitsCache = {};
  31543. this.currentFrame = 0;
  31544. this._blendingFactor = 0;
  31545. this._originalBlendValue = null;
  31546. };
  31547. Animation.prototype.isStopped = function () {
  31548. return this._stopped;
  31549. };
  31550. Animation.prototype.getKeys = function () {
  31551. return this._keys;
  31552. };
  31553. Animation.prototype.getHighestFrame = function () {
  31554. var ret = 0;
  31555. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  31556. if (ret < this._keys[key].frame) {
  31557. ret = this._keys[key].frame;
  31558. }
  31559. }
  31560. return ret;
  31561. };
  31562. Animation.prototype.getEasingFunction = function () {
  31563. return this._easingFunction;
  31564. };
  31565. Animation.prototype.setEasingFunction = function (easingFunction) {
  31566. this._easingFunction = easingFunction;
  31567. };
  31568. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  31569. return startValue + (endValue - startValue) * gradient;
  31570. };
  31571. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  31572. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  31573. };
  31574. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  31575. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  31576. };
  31577. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  31578. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  31579. };
  31580. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  31581. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  31582. };
  31583. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  31584. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  31585. };
  31586. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  31587. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  31588. };
  31589. Animation.prototype.clone = function () {
  31590. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  31591. clone.enableBlending = this.enableBlending;
  31592. clone.blendingSpeed = this.blendingSpeed;
  31593. if (this._keys) {
  31594. clone.setKeys(this._keys);
  31595. }
  31596. if (this._ranges) {
  31597. clone._ranges = {};
  31598. for (var name in this._ranges) {
  31599. clone._ranges[name] = this._ranges[name].clone();
  31600. }
  31601. }
  31602. return clone;
  31603. };
  31604. Animation.prototype.setKeys = function (values) {
  31605. this._keys = values.slice(0);
  31606. this._offsetsCache = {};
  31607. this._highLimitsCache = {};
  31608. };
  31609. Animation.prototype._getKeyValue = function (value) {
  31610. if (typeof value === "function") {
  31611. return value();
  31612. }
  31613. return value;
  31614. };
  31615. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  31616. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  31617. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  31618. }
  31619. this.currentFrame = currentFrame;
  31620. // Try to get a hash to find the right key
  31621. var startKey = 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));
  31622. if (this._keys[startKey].frame >= currentFrame) {
  31623. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  31624. startKey--;
  31625. }
  31626. }
  31627. for (var key = startKey; key < this._keys.length; key++) {
  31628. if (this._keys[key + 1].frame >= currentFrame) {
  31629. var startValue = this._getKeyValue(this._keys[key].value);
  31630. var endValue = this._getKeyValue(this._keys[key + 1].value);
  31631. // gradient : percent of currentFrame between the frame inf and the frame sup
  31632. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  31633. // check for easingFunction and correction of gradient
  31634. if (this._easingFunction != null) {
  31635. gradient = this._easingFunction.ease(gradient);
  31636. }
  31637. switch (this.dataType) {
  31638. // Float
  31639. case Animation.ANIMATIONTYPE_FLOAT:
  31640. switch (loopMode) {
  31641. case Animation.ANIMATIONLOOPMODE_CYCLE:
  31642. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  31643. return this.floatInterpolateFunction(startValue, endValue, gradient);
  31644. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  31645. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  31646. }
  31647. break;
  31648. // Quaternion
  31649. case Animation.ANIMATIONTYPE_QUATERNION:
  31650. var quaternion = null;
  31651. switch (loopMode) {
  31652. case Animation.ANIMATIONLOOPMODE_CYCLE:
  31653. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  31654. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  31655. break;
  31656. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  31657. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  31658. break;
  31659. }
  31660. return quaternion;
  31661. // Vector3
  31662. case Animation.ANIMATIONTYPE_VECTOR3:
  31663. switch (loopMode) {
  31664. case Animation.ANIMATIONLOOPMODE_CYCLE:
  31665. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  31666. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  31667. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  31668. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  31669. }
  31670. // Vector2
  31671. case Animation.ANIMATIONTYPE_VECTOR2:
  31672. switch (loopMode) {
  31673. case Animation.ANIMATIONLOOPMODE_CYCLE:
  31674. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  31675. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  31676. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  31677. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  31678. }
  31679. // Size
  31680. case Animation.ANIMATIONTYPE_SIZE:
  31681. switch (loopMode) {
  31682. case Animation.ANIMATIONLOOPMODE_CYCLE:
  31683. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  31684. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  31685. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  31686. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  31687. }
  31688. // Color3
  31689. case Animation.ANIMATIONTYPE_COLOR3:
  31690. switch (loopMode) {
  31691. case Animation.ANIMATIONLOOPMODE_CYCLE:
  31692. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  31693. return this.color3InterpolateFunction(startValue, endValue, gradient);
  31694. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  31695. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  31696. }
  31697. // Matrix
  31698. case Animation.ANIMATIONTYPE_MATRIX:
  31699. switch (loopMode) {
  31700. case Animation.ANIMATIONLOOPMODE_CYCLE:
  31701. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  31702. if (this.allowMatricesInterpolation) {
  31703. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  31704. }
  31705. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  31706. return startValue;
  31707. }
  31708. default:
  31709. break;
  31710. }
  31711. break;
  31712. }
  31713. }
  31714. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  31715. };
  31716. Animation.prototype.setValue = function (currentValue, blend) {
  31717. if (blend === void 0) { blend = false; }
  31718. // Set value
  31719. var path;
  31720. var destination;
  31721. if (this.targetPropertyPath.length > 1) {
  31722. var property = this._target[this.targetPropertyPath[0]];
  31723. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  31724. property = property[this.targetPropertyPath[index]];
  31725. }
  31726. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  31727. destination = property;
  31728. }
  31729. else {
  31730. path = this.targetPropertyPath[0];
  31731. destination = this._target;
  31732. }
  31733. // Blending
  31734. if (this.enableBlending && this._blendingFactor <= 1.0) {
  31735. if (!this._originalBlendValue) {
  31736. if (destination[path].clone) {
  31737. this._originalBlendValue = destination[path].clone();
  31738. }
  31739. else {
  31740. this._originalBlendValue = destination[path];
  31741. }
  31742. }
  31743. if (this._originalBlendValue.prototype) {
  31744. if (this._originalBlendValue.prototype.Lerp) {
  31745. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  31746. }
  31747. else {
  31748. destination[path] = currentValue;
  31749. }
  31750. }
  31751. else if (this._originalBlendValue.m) {
  31752. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  31753. }
  31754. else {
  31755. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  31756. }
  31757. this._blendingFactor += this.blendingSpeed;
  31758. }
  31759. else {
  31760. destination[path] = currentValue;
  31761. }
  31762. if (this._target.markAsDirty) {
  31763. this._target.markAsDirty(this.targetProperty);
  31764. }
  31765. };
  31766. Animation.prototype.goToFrame = function (frame) {
  31767. if (frame < this._keys[0].frame) {
  31768. frame = this._keys[0].frame;
  31769. }
  31770. else if (frame > this._keys[this._keys.length - 1].frame) {
  31771. frame = this._keys[this._keys.length - 1].frame;
  31772. }
  31773. var currentValue = this._interpolate(frame, 0, this.loopMode);
  31774. this.setValue(currentValue);
  31775. };
  31776. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  31777. if (blend === void 0) { blend = false; }
  31778. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  31779. this._stopped = true;
  31780. return false;
  31781. }
  31782. var returnValue = true;
  31783. // Adding a start key at frame 0 if missing
  31784. if (this._keys[0].frame !== 0) {
  31785. var newKey = { frame: 0, value: this._keys[0].value };
  31786. this._keys.splice(0, 0, newKey);
  31787. }
  31788. // Check limits
  31789. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  31790. from = this._keys[0].frame;
  31791. }
  31792. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  31793. to = this._keys[this._keys.length - 1].frame;
  31794. }
  31795. //to and from cannot be the same key
  31796. if (from === to) {
  31797. from++;
  31798. }
  31799. // Compute ratio
  31800. var range = to - from;
  31801. var offsetValue;
  31802. // ratio represents the frame delta between from and to
  31803. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  31804. var highLimitValue = 0;
  31805. if (ratio > range && !loop) {
  31806. returnValue = false;
  31807. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  31808. }
  31809. else {
  31810. // Get max value if required
  31811. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  31812. var keyOffset = to.toString() + from.toString();
  31813. if (!this._offsetsCache[keyOffset]) {
  31814. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  31815. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  31816. switch (this.dataType) {
  31817. // Float
  31818. case Animation.ANIMATIONTYPE_FLOAT:
  31819. this._offsetsCache[keyOffset] = toValue - fromValue;
  31820. break;
  31821. // Quaternion
  31822. case Animation.ANIMATIONTYPE_QUATERNION:
  31823. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  31824. break;
  31825. // Vector3
  31826. case Animation.ANIMATIONTYPE_VECTOR3:
  31827. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  31828. // Vector2
  31829. case Animation.ANIMATIONTYPE_VECTOR2:
  31830. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  31831. // Size
  31832. case Animation.ANIMATIONTYPE_SIZE:
  31833. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  31834. // Color3
  31835. case Animation.ANIMATIONTYPE_COLOR3:
  31836. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  31837. default:
  31838. break;
  31839. }
  31840. this._highLimitsCache[keyOffset] = toValue;
  31841. }
  31842. highLimitValue = this._highLimitsCache[keyOffset];
  31843. offsetValue = this._offsetsCache[keyOffset];
  31844. }
  31845. }
  31846. if (offsetValue === undefined) {
  31847. switch (this.dataType) {
  31848. // Float
  31849. case Animation.ANIMATIONTYPE_FLOAT:
  31850. offsetValue = 0;
  31851. break;
  31852. // Quaternion
  31853. case Animation.ANIMATIONTYPE_QUATERNION:
  31854. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  31855. break;
  31856. // Vector3
  31857. case Animation.ANIMATIONTYPE_VECTOR3:
  31858. offsetValue = BABYLON.Vector3.Zero();
  31859. break;
  31860. // Vector2
  31861. case Animation.ANIMATIONTYPE_VECTOR2:
  31862. offsetValue = BABYLON.Vector2.Zero();
  31863. break;
  31864. // Size
  31865. case Animation.ANIMATIONTYPE_SIZE:
  31866. offsetValue = BABYLON.Size.Zero();
  31867. break;
  31868. // Color3
  31869. case Animation.ANIMATIONTYPE_COLOR3:
  31870. offsetValue = BABYLON.Color3.Black();
  31871. }
  31872. }
  31873. // Compute value
  31874. var repeatCount = (ratio / range) >> 0;
  31875. var currentFrame = returnValue ? from + ratio % range : to;
  31876. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  31877. // Set value
  31878. this.setValue(currentValue);
  31879. // Check events
  31880. for (var index = 0; index < this._events.length; index++) {
  31881. if (currentFrame >= this._events[index].frame) {
  31882. var event = this._events[index];
  31883. if (!event.isDone) {
  31884. // If event should be done only once, remove it.
  31885. if (event.onlyOnce) {
  31886. this._events.splice(index, 1);
  31887. index--;
  31888. }
  31889. event.isDone = true;
  31890. event.action();
  31891. } // Don't do anything if the event has already be done.
  31892. }
  31893. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  31894. // reset event, the animation is looping
  31895. this._events[index].isDone = false;
  31896. }
  31897. }
  31898. if (!returnValue) {
  31899. this._stopped = true;
  31900. }
  31901. return returnValue;
  31902. };
  31903. Animation.prototype.serialize = function () {
  31904. var serializationObject = {};
  31905. serializationObject.name = this.name;
  31906. serializationObject.property = this.targetProperty;
  31907. serializationObject.framePerSecond = this.framePerSecond;
  31908. serializationObject.dataType = this.dataType;
  31909. serializationObject.loopBehavior = this.loopMode;
  31910. serializationObject.enableBlending = this.enableBlending;
  31911. serializationObject.blendingSpeed = this.blendingSpeed;
  31912. var dataType = this.dataType;
  31913. serializationObject.keys = [];
  31914. var keys = this.getKeys();
  31915. for (var index = 0; index < keys.length; index++) {
  31916. var animationKey = keys[index];
  31917. var key = {};
  31918. key.frame = animationKey.frame;
  31919. switch (dataType) {
  31920. case Animation.ANIMATIONTYPE_FLOAT:
  31921. key.values = [animationKey.value];
  31922. break;
  31923. case Animation.ANIMATIONTYPE_QUATERNION:
  31924. case Animation.ANIMATIONTYPE_MATRIX:
  31925. case Animation.ANIMATIONTYPE_VECTOR3:
  31926. case Animation.ANIMATIONTYPE_COLOR3:
  31927. key.values = animationKey.value.asArray();
  31928. break;
  31929. }
  31930. serializationObject.keys.push(key);
  31931. }
  31932. serializationObject.ranges = [];
  31933. for (var name in this._ranges) {
  31934. var range = {};
  31935. range.name = name;
  31936. range.from = this._ranges[name].from;
  31937. range.to = this._ranges[name].to;
  31938. serializationObject.ranges.push(range);
  31939. }
  31940. return serializationObject;
  31941. };
  31942. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  31943. get: function () {
  31944. return Animation._ANIMATIONTYPE_FLOAT;
  31945. },
  31946. enumerable: true,
  31947. configurable: true
  31948. });
  31949. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  31950. get: function () {
  31951. return Animation._ANIMATIONTYPE_VECTOR3;
  31952. },
  31953. enumerable: true,
  31954. configurable: true
  31955. });
  31956. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  31957. get: function () {
  31958. return Animation._ANIMATIONTYPE_VECTOR2;
  31959. },
  31960. enumerable: true,
  31961. configurable: true
  31962. });
  31963. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  31964. get: function () {
  31965. return Animation._ANIMATIONTYPE_SIZE;
  31966. },
  31967. enumerable: true,
  31968. configurable: true
  31969. });
  31970. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  31971. get: function () {
  31972. return Animation._ANIMATIONTYPE_QUATERNION;
  31973. },
  31974. enumerable: true,
  31975. configurable: true
  31976. });
  31977. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  31978. get: function () {
  31979. return Animation._ANIMATIONTYPE_MATRIX;
  31980. },
  31981. enumerable: true,
  31982. configurable: true
  31983. });
  31984. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  31985. get: function () {
  31986. return Animation._ANIMATIONTYPE_COLOR3;
  31987. },
  31988. enumerable: true,
  31989. configurable: true
  31990. });
  31991. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  31992. get: function () {
  31993. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  31994. },
  31995. enumerable: true,
  31996. configurable: true
  31997. });
  31998. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  31999. get: function () {
  32000. return Animation._ANIMATIONLOOPMODE_CYCLE;
  32001. },
  32002. enumerable: true,
  32003. configurable: true
  32004. });
  32005. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  32006. get: function () {
  32007. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  32008. },
  32009. enumerable: true,
  32010. configurable: true
  32011. });
  32012. Animation.Parse = function (parsedAnimation) {
  32013. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  32014. var dataType = parsedAnimation.dataType;
  32015. var keys = [];
  32016. var data;
  32017. var index;
  32018. if (parsedAnimation.enableBlending) {
  32019. animation.enableBlending = parsedAnimation.enableBlending;
  32020. }
  32021. if (parsedAnimation.blendingSpeed) {
  32022. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  32023. }
  32024. for (index = 0; index < parsedAnimation.keys.length; index++) {
  32025. var key = parsedAnimation.keys[index];
  32026. switch (dataType) {
  32027. case Animation.ANIMATIONTYPE_FLOAT:
  32028. data = key.values[0];
  32029. break;
  32030. case Animation.ANIMATIONTYPE_QUATERNION:
  32031. data = BABYLON.Quaternion.FromArray(key.values);
  32032. break;
  32033. case Animation.ANIMATIONTYPE_MATRIX:
  32034. data = BABYLON.Matrix.FromArray(key.values);
  32035. break;
  32036. case Animation.ANIMATIONTYPE_COLOR3:
  32037. data = BABYLON.Color3.FromArray(key.values);
  32038. break;
  32039. case Animation.ANIMATIONTYPE_VECTOR3:
  32040. default:
  32041. data = BABYLON.Vector3.FromArray(key.values);
  32042. break;
  32043. }
  32044. keys.push({
  32045. frame: key.frame,
  32046. value: data
  32047. });
  32048. }
  32049. animation.setKeys(keys);
  32050. if (parsedAnimation.ranges) {
  32051. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  32052. data = parsedAnimation.ranges[index];
  32053. animation.createRange(data.name, data.from, data.to);
  32054. }
  32055. }
  32056. return animation;
  32057. };
  32058. Animation.AppendSerializedAnimations = function (source, destination) {
  32059. if (source.animations) {
  32060. destination.animations = [];
  32061. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  32062. var animation = source.animations[animationIndex];
  32063. destination.animations.push(animation.serialize());
  32064. }
  32065. }
  32066. };
  32067. return Animation;
  32068. }());
  32069. // Statics
  32070. Animation._ANIMATIONTYPE_FLOAT = 0;
  32071. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  32072. Animation._ANIMATIONTYPE_QUATERNION = 2;
  32073. Animation._ANIMATIONTYPE_MATRIX = 3;
  32074. Animation._ANIMATIONTYPE_COLOR3 = 4;
  32075. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  32076. Animation._ANIMATIONTYPE_SIZE = 6;
  32077. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  32078. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  32079. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  32080. BABYLON.Animation = Animation;
  32081. })(BABYLON || (BABYLON = {}));
  32082. //# sourceMappingURL=babylon.animation.js.map
  32083. var BABYLON;
  32084. (function (BABYLON) {
  32085. var Animatable = (function () {
  32086. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  32087. if (fromFrame === void 0) { fromFrame = 0; }
  32088. if (toFrame === void 0) { toFrame = 100; }
  32089. if (loopAnimation === void 0) { loopAnimation = false; }
  32090. if (speedRatio === void 0) { speedRatio = 1.0; }
  32091. this.target = target;
  32092. this.fromFrame = fromFrame;
  32093. this.toFrame = toFrame;
  32094. this.loopAnimation = loopAnimation;
  32095. this.speedRatio = speedRatio;
  32096. this.onAnimationEnd = onAnimationEnd;
  32097. this._animations = new Array();
  32098. this._paused = false;
  32099. this.animationStarted = false;
  32100. if (animations) {
  32101. this.appendAnimations(target, animations);
  32102. }
  32103. this._scene = scene;
  32104. scene._activeAnimatables.push(this);
  32105. }
  32106. // Methods
  32107. Animatable.prototype.getAnimations = function () {
  32108. return this._animations;
  32109. };
  32110. Animatable.prototype.appendAnimations = function (target, animations) {
  32111. for (var index = 0; index < animations.length; index++) {
  32112. var animation = animations[index];
  32113. animation._target = target;
  32114. this._animations.push(animation);
  32115. }
  32116. };
  32117. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  32118. var animations = this._animations;
  32119. for (var index = 0; index < animations.length; index++) {
  32120. if (animations[index].targetProperty === property) {
  32121. return animations[index];
  32122. }
  32123. }
  32124. return null;
  32125. };
  32126. Animatable.prototype.reset = function () {
  32127. var animations = this._animations;
  32128. for (var index = 0; index < animations.length; index++) {
  32129. animations[index].reset();
  32130. }
  32131. this._localDelayOffset = null;
  32132. this._pausedDelay = null;
  32133. };
  32134. Animatable.prototype.enableBlending = function (blendingSpeed) {
  32135. var animations = this._animations;
  32136. for (var index = 0; index < animations.length; index++) {
  32137. animations[index].enableBlending = true;
  32138. animations[index].blendingSpeed = blendingSpeed;
  32139. }
  32140. };
  32141. Animatable.prototype.disableBlending = function () {
  32142. var animations = this._animations;
  32143. for (var index = 0; index < animations.length; index++) {
  32144. animations[index].enableBlending = false;
  32145. }
  32146. };
  32147. Animatable.prototype.goToFrame = function (frame) {
  32148. var animations = this._animations;
  32149. if (animations[0]) {
  32150. var fps = animations[0].framePerSecond;
  32151. var currentFrame = animations[0].currentFrame;
  32152. var adjustTime = frame - currentFrame;
  32153. var delay = adjustTime * 1000 / fps;
  32154. this._localDelayOffset -= delay;
  32155. }
  32156. for (var index = 0; index < animations.length; index++) {
  32157. animations[index].goToFrame(frame);
  32158. }
  32159. };
  32160. Animatable.prototype.pause = function () {
  32161. if (this._paused) {
  32162. return;
  32163. }
  32164. this._paused = true;
  32165. };
  32166. Animatable.prototype.restart = function () {
  32167. this._paused = false;
  32168. };
  32169. Animatable.prototype.stop = function (animationName) {
  32170. if (animationName) {
  32171. var idx = this._scene._activeAnimatables.indexOf(this);
  32172. if (idx > -1) {
  32173. var animations = this._animations;
  32174. for (var index = animations.length - 1; index >= 0; index--) {
  32175. if (typeof animationName === "string" && animations[index].name != animationName) {
  32176. continue;
  32177. }
  32178. animations[index].reset();
  32179. animations.splice(index, 1);
  32180. }
  32181. if (animations.length == 0) {
  32182. this._scene._activeAnimatables.splice(idx, 1);
  32183. if (this.onAnimationEnd) {
  32184. this.onAnimationEnd();
  32185. }
  32186. }
  32187. }
  32188. }
  32189. else {
  32190. var index = this._scene._activeAnimatables.indexOf(this);
  32191. if (index > -1) {
  32192. this._scene._activeAnimatables.splice(index, 1);
  32193. var animations = this._animations;
  32194. for (var index = 0; index < animations.length; index++) {
  32195. animations[index].reset();
  32196. }
  32197. if (this.onAnimationEnd) {
  32198. this.onAnimationEnd();
  32199. }
  32200. }
  32201. }
  32202. };
  32203. Animatable.prototype._animate = function (delay) {
  32204. if (this._paused) {
  32205. this.animationStarted = false;
  32206. if (!this._pausedDelay) {
  32207. this._pausedDelay = delay;
  32208. }
  32209. return true;
  32210. }
  32211. if (!this._localDelayOffset) {
  32212. this._localDelayOffset = delay;
  32213. }
  32214. else if (this._pausedDelay) {
  32215. this._localDelayOffset += delay - this._pausedDelay;
  32216. this._pausedDelay = null;
  32217. }
  32218. // Animating
  32219. var running = false;
  32220. var animations = this._animations;
  32221. var index;
  32222. for (index = 0; index < animations.length; index++) {
  32223. var animation = animations[index];
  32224. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  32225. running = running || isRunning;
  32226. }
  32227. this.animationStarted = running;
  32228. if (!running) {
  32229. // Remove from active animatables
  32230. index = this._scene._activeAnimatables.indexOf(this);
  32231. this._scene._activeAnimatables.splice(index, 1);
  32232. }
  32233. if (!running && this.onAnimationEnd) {
  32234. this.onAnimationEnd();
  32235. this.onAnimationEnd = null;
  32236. }
  32237. return running;
  32238. };
  32239. return Animatable;
  32240. }());
  32241. BABYLON.Animatable = Animatable;
  32242. })(BABYLON || (BABYLON = {}));
  32243. //# sourceMappingURL=babylon.animatable.js.map
  32244. var BABYLON;
  32245. (function (BABYLON) {
  32246. var EasingFunction = (function () {
  32247. function EasingFunction() {
  32248. // Properties
  32249. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  32250. }
  32251. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  32252. get: function () {
  32253. return EasingFunction._EASINGMODE_EASEIN;
  32254. },
  32255. enumerable: true,
  32256. configurable: true
  32257. });
  32258. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  32259. get: function () {
  32260. return EasingFunction._EASINGMODE_EASEOUT;
  32261. },
  32262. enumerable: true,
  32263. configurable: true
  32264. });
  32265. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  32266. get: function () {
  32267. return EasingFunction._EASINGMODE_EASEINOUT;
  32268. },
  32269. enumerable: true,
  32270. configurable: true
  32271. });
  32272. EasingFunction.prototype.setEasingMode = function (easingMode) {
  32273. var n = Math.min(Math.max(easingMode, 0), 2);
  32274. this._easingMode = n;
  32275. };
  32276. EasingFunction.prototype.getEasingMode = function () {
  32277. return this._easingMode;
  32278. };
  32279. EasingFunction.prototype.easeInCore = function (gradient) {
  32280. throw new Error('You must implement this method');
  32281. };
  32282. EasingFunction.prototype.ease = function (gradient) {
  32283. switch (this._easingMode) {
  32284. case EasingFunction.EASINGMODE_EASEIN:
  32285. return this.easeInCore(gradient);
  32286. case EasingFunction.EASINGMODE_EASEOUT:
  32287. return (1 - this.easeInCore(1 - gradient));
  32288. }
  32289. if (gradient >= 0.5) {
  32290. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  32291. }
  32292. return (this.easeInCore(gradient * 2) * 0.5);
  32293. };
  32294. return EasingFunction;
  32295. }());
  32296. //Statics
  32297. EasingFunction._EASINGMODE_EASEIN = 0;
  32298. EasingFunction._EASINGMODE_EASEOUT = 1;
  32299. EasingFunction._EASINGMODE_EASEINOUT = 2;
  32300. BABYLON.EasingFunction = EasingFunction;
  32301. var CircleEase = (function (_super) {
  32302. __extends(CircleEase, _super);
  32303. function CircleEase() {
  32304. return _super !== null && _super.apply(this, arguments) || this;
  32305. }
  32306. CircleEase.prototype.easeInCore = function (gradient) {
  32307. gradient = Math.max(0, Math.min(1, gradient));
  32308. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  32309. };
  32310. return CircleEase;
  32311. }(EasingFunction));
  32312. BABYLON.CircleEase = CircleEase;
  32313. var BackEase = (function (_super) {
  32314. __extends(BackEase, _super);
  32315. function BackEase(amplitude) {
  32316. if (amplitude === void 0) { amplitude = 1; }
  32317. var _this = _super.call(this) || this;
  32318. _this.amplitude = amplitude;
  32319. return _this;
  32320. }
  32321. BackEase.prototype.easeInCore = function (gradient) {
  32322. var num = Math.max(0, this.amplitude);
  32323. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  32324. };
  32325. return BackEase;
  32326. }(EasingFunction));
  32327. BABYLON.BackEase = BackEase;
  32328. var BounceEase = (function (_super) {
  32329. __extends(BounceEase, _super);
  32330. function BounceEase(bounces, bounciness) {
  32331. if (bounces === void 0) { bounces = 3; }
  32332. if (bounciness === void 0) { bounciness = 2; }
  32333. var _this = _super.call(this) || this;
  32334. _this.bounces = bounces;
  32335. _this.bounciness = bounciness;
  32336. return _this;
  32337. }
  32338. BounceEase.prototype.easeInCore = function (gradient) {
  32339. var y = Math.max(0.0, this.bounces);
  32340. var bounciness = this.bounciness;
  32341. if (bounciness <= 1.0) {
  32342. bounciness = 1.001;
  32343. }
  32344. var num9 = Math.pow(bounciness, y);
  32345. var num5 = 1.0 - bounciness;
  32346. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  32347. var num15 = gradient * num4;
  32348. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  32349. var num3 = Math.floor(num65);
  32350. var num13 = num3 + 1.0;
  32351. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  32352. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  32353. var num7 = (num8 + num12) * 0.5;
  32354. var num6 = gradient - num7;
  32355. var num2 = num7 - num8;
  32356. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  32357. };
  32358. return BounceEase;
  32359. }(EasingFunction));
  32360. BABYLON.BounceEase = BounceEase;
  32361. var CubicEase = (function (_super) {
  32362. __extends(CubicEase, _super);
  32363. function CubicEase() {
  32364. return _super !== null && _super.apply(this, arguments) || this;
  32365. }
  32366. CubicEase.prototype.easeInCore = function (gradient) {
  32367. return (gradient * gradient * gradient);
  32368. };
  32369. return CubicEase;
  32370. }(EasingFunction));
  32371. BABYLON.CubicEase = CubicEase;
  32372. var ElasticEase = (function (_super) {
  32373. __extends(ElasticEase, _super);
  32374. function ElasticEase(oscillations, springiness) {
  32375. if (oscillations === void 0) { oscillations = 3; }
  32376. if (springiness === void 0) { springiness = 3; }
  32377. var _this = _super.call(this) || this;
  32378. _this.oscillations = oscillations;
  32379. _this.springiness = springiness;
  32380. return _this;
  32381. }
  32382. ElasticEase.prototype.easeInCore = function (gradient) {
  32383. var num2;
  32384. var num3 = Math.max(0.0, this.oscillations);
  32385. var num = Math.max(0.0, this.springiness);
  32386. if (num == 0) {
  32387. num2 = gradient;
  32388. }
  32389. else {
  32390. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  32391. }
  32392. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  32393. };
  32394. return ElasticEase;
  32395. }(EasingFunction));
  32396. BABYLON.ElasticEase = ElasticEase;
  32397. var ExponentialEase = (function (_super) {
  32398. __extends(ExponentialEase, _super);
  32399. function ExponentialEase(exponent) {
  32400. if (exponent === void 0) { exponent = 2; }
  32401. var _this = _super.call(this) || this;
  32402. _this.exponent = exponent;
  32403. return _this;
  32404. }
  32405. ExponentialEase.prototype.easeInCore = function (gradient) {
  32406. if (this.exponent <= 0) {
  32407. return gradient;
  32408. }
  32409. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  32410. };
  32411. return ExponentialEase;
  32412. }(EasingFunction));
  32413. BABYLON.ExponentialEase = ExponentialEase;
  32414. var PowerEase = (function (_super) {
  32415. __extends(PowerEase, _super);
  32416. function PowerEase(power) {
  32417. if (power === void 0) { power = 2; }
  32418. var _this = _super.call(this) || this;
  32419. _this.power = power;
  32420. return _this;
  32421. }
  32422. PowerEase.prototype.easeInCore = function (gradient) {
  32423. var y = Math.max(0.0, this.power);
  32424. return Math.pow(gradient, y);
  32425. };
  32426. return PowerEase;
  32427. }(EasingFunction));
  32428. BABYLON.PowerEase = PowerEase;
  32429. var QuadraticEase = (function (_super) {
  32430. __extends(QuadraticEase, _super);
  32431. function QuadraticEase() {
  32432. return _super !== null && _super.apply(this, arguments) || this;
  32433. }
  32434. QuadraticEase.prototype.easeInCore = function (gradient) {
  32435. return (gradient * gradient);
  32436. };
  32437. return QuadraticEase;
  32438. }(EasingFunction));
  32439. BABYLON.QuadraticEase = QuadraticEase;
  32440. var QuarticEase = (function (_super) {
  32441. __extends(QuarticEase, _super);
  32442. function QuarticEase() {
  32443. return _super !== null && _super.apply(this, arguments) || this;
  32444. }
  32445. QuarticEase.prototype.easeInCore = function (gradient) {
  32446. return (gradient * gradient * gradient * gradient);
  32447. };
  32448. return QuarticEase;
  32449. }(EasingFunction));
  32450. BABYLON.QuarticEase = QuarticEase;
  32451. var QuinticEase = (function (_super) {
  32452. __extends(QuinticEase, _super);
  32453. function QuinticEase() {
  32454. return _super !== null && _super.apply(this, arguments) || this;
  32455. }
  32456. QuinticEase.prototype.easeInCore = function (gradient) {
  32457. return (gradient * gradient * gradient * gradient * gradient);
  32458. };
  32459. return QuinticEase;
  32460. }(EasingFunction));
  32461. BABYLON.QuinticEase = QuinticEase;
  32462. var SineEase = (function (_super) {
  32463. __extends(SineEase, _super);
  32464. function SineEase() {
  32465. return _super !== null && _super.apply(this, arguments) || this;
  32466. }
  32467. SineEase.prototype.easeInCore = function (gradient) {
  32468. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  32469. };
  32470. return SineEase;
  32471. }(EasingFunction));
  32472. BABYLON.SineEase = SineEase;
  32473. var BezierCurveEase = (function (_super) {
  32474. __extends(BezierCurveEase, _super);
  32475. function BezierCurveEase(x1, y1, x2, y2) {
  32476. if (x1 === void 0) { x1 = 0; }
  32477. if (y1 === void 0) { y1 = 0; }
  32478. if (x2 === void 0) { x2 = 1; }
  32479. if (y2 === void 0) { y2 = 1; }
  32480. var _this = _super.call(this) || this;
  32481. _this.x1 = x1;
  32482. _this.y1 = y1;
  32483. _this.x2 = x2;
  32484. _this.y2 = y2;
  32485. return _this;
  32486. }
  32487. BezierCurveEase.prototype.easeInCore = function (gradient) {
  32488. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  32489. };
  32490. return BezierCurveEase;
  32491. }(EasingFunction));
  32492. BABYLON.BezierCurveEase = BezierCurveEase;
  32493. })(BABYLON || (BABYLON = {}));
  32494. //# sourceMappingURL=babylon.easing.js.map
  32495. var BABYLON;
  32496. (function (BABYLON) {
  32497. var Condition = (function () {
  32498. function Condition(actionManager) {
  32499. this._actionManager = actionManager;
  32500. }
  32501. Condition.prototype.isValid = function () {
  32502. return true;
  32503. };
  32504. Condition.prototype._getProperty = function (propertyPath) {
  32505. return this._actionManager._getProperty(propertyPath);
  32506. };
  32507. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  32508. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32509. };
  32510. Condition.prototype.serialize = function () {
  32511. };
  32512. Condition.prototype._serialize = function (serializedCondition) {
  32513. return {
  32514. type: 2,
  32515. children: [],
  32516. name: serializedCondition.name,
  32517. properties: serializedCondition.properties
  32518. };
  32519. };
  32520. return Condition;
  32521. }());
  32522. BABYLON.Condition = Condition;
  32523. var ValueCondition = (function (_super) {
  32524. __extends(ValueCondition, _super);
  32525. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  32526. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  32527. var _this = _super.call(this, actionManager) || this;
  32528. _this.propertyPath = propertyPath;
  32529. _this.value = value;
  32530. _this.operator = operator;
  32531. _this._target = target;
  32532. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  32533. _this._property = _this._getProperty(_this.propertyPath);
  32534. return _this;
  32535. }
  32536. Object.defineProperty(ValueCondition, "IsEqual", {
  32537. get: function () {
  32538. return ValueCondition._IsEqual;
  32539. },
  32540. enumerable: true,
  32541. configurable: true
  32542. });
  32543. Object.defineProperty(ValueCondition, "IsDifferent", {
  32544. get: function () {
  32545. return ValueCondition._IsDifferent;
  32546. },
  32547. enumerable: true,
  32548. configurable: true
  32549. });
  32550. Object.defineProperty(ValueCondition, "IsGreater", {
  32551. get: function () {
  32552. return ValueCondition._IsGreater;
  32553. },
  32554. enumerable: true,
  32555. configurable: true
  32556. });
  32557. Object.defineProperty(ValueCondition, "IsLesser", {
  32558. get: function () {
  32559. return ValueCondition._IsLesser;
  32560. },
  32561. enumerable: true,
  32562. configurable: true
  32563. });
  32564. // Methods
  32565. ValueCondition.prototype.isValid = function () {
  32566. switch (this.operator) {
  32567. case ValueCondition.IsGreater:
  32568. return this._effectiveTarget[this._property] > this.value;
  32569. case ValueCondition.IsLesser:
  32570. return this._effectiveTarget[this._property] < this.value;
  32571. case ValueCondition.IsEqual:
  32572. case ValueCondition.IsDifferent:
  32573. var check;
  32574. if (this.value.equals) {
  32575. check = this.value.equals(this._effectiveTarget[this._property]);
  32576. }
  32577. else {
  32578. check = this.value === this._effectiveTarget[this._property];
  32579. }
  32580. return this.operator === ValueCondition.IsEqual ? check : !check;
  32581. }
  32582. return false;
  32583. };
  32584. ValueCondition.prototype.serialize = function () {
  32585. return this._serialize({
  32586. name: "ValueCondition",
  32587. properties: [
  32588. BABYLON.Action._GetTargetProperty(this._target),
  32589. { name: "propertyPath", value: this.propertyPath },
  32590. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32591. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  32592. ]
  32593. });
  32594. };
  32595. ValueCondition.GetOperatorName = function (operator) {
  32596. switch (operator) {
  32597. case ValueCondition._IsEqual: return "IsEqual";
  32598. case ValueCondition._IsDifferent: return "IsDifferent";
  32599. case ValueCondition._IsGreater: return "IsGreater";
  32600. case ValueCondition._IsLesser: return "IsLesser";
  32601. default: return "";
  32602. }
  32603. };
  32604. return ValueCondition;
  32605. }(Condition));
  32606. // Statics
  32607. ValueCondition._IsEqual = 0;
  32608. ValueCondition._IsDifferent = 1;
  32609. ValueCondition._IsGreater = 2;
  32610. ValueCondition._IsLesser = 3;
  32611. BABYLON.ValueCondition = ValueCondition;
  32612. var PredicateCondition = (function (_super) {
  32613. __extends(PredicateCondition, _super);
  32614. function PredicateCondition(actionManager, predicate) {
  32615. var _this = _super.call(this, actionManager) || this;
  32616. _this.predicate = predicate;
  32617. return _this;
  32618. }
  32619. PredicateCondition.prototype.isValid = function () {
  32620. return this.predicate();
  32621. };
  32622. return PredicateCondition;
  32623. }(Condition));
  32624. BABYLON.PredicateCondition = PredicateCondition;
  32625. var StateCondition = (function (_super) {
  32626. __extends(StateCondition, _super);
  32627. function StateCondition(actionManager, target, value) {
  32628. var _this = _super.call(this, actionManager) || this;
  32629. _this.value = value;
  32630. _this._target = target;
  32631. return _this;
  32632. }
  32633. // Methods
  32634. StateCondition.prototype.isValid = function () {
  32635. return this._target.state === this.value;
  32636. };
  32637. StateCondition.prototype.serialize = function () {
  32638. return this._serialize({
  32639. name: "StateCondition",
  32640. properties: [
  32641. BABYLON.Action._GetTargetProperty(this._target),
  32642. { name: "value", value: this.value }
  32643. ]
  32644. });
  32645. };
  32646. return StateCondition;
  32647. }(Condition));
  32648. BABYLON.StateCondition = StateCondition;
  32649. })(BABYLON || (BABYLON = {}));
  32650. //# sourceMappingURL=babylon.condition.js.map
  32651. var BABYLON;
  32652. (function (BABYLON) {
  32653. var Action = (function () {
  32654. function Action(triggerOptions, condition) {
  32655. this.triggerOptions = triggerOptions;
  32656. if (triggerOptions.parameter) {
  32657. this.trigger = triggerOptions.trigger;
  32658. this._triggerParameter = triggerOptions.parameter;
  32659. }
  32660. else {
  32661. this.trigger = triggerOptions;
  32662. }
  32663. this._nextActiveAction = this;
  32664. this._condition = condition;
  32665. }
  32666. // Methods
  32667. Action.prototype._prepare = function () {
  32668. };
  32669. Action.prototype.getTriggerParameter = function () {
  32670. return this._triggerParameter;
  32671. };
  32672. Action.prototype._executeCurrent = function (evt) {
  32673. if (this._nextActiveAction._condition) {
  32674. var condition = this._nextActiveAction._condition;
  32675. var currentRenderId = this._actionManager.getScene().getRenderId();
  32676. // We cache the current evaluation for the current frame
  32677. if (condition._evaluationId === currentRenderId) {
  32678. if (!condition._currentResult) {
  32679. return;
  32680. }
  32681. }
  32682. else {
  32683. condition._evaluationId = currentRenderId;
  32684. if (!condition.isValid()) {
  32685. condition._currentResult = false;
  32686. return;
  32687. }
  32688. condition._currentResult = true;
  32689. }
  32690. }
  32691. this._nextActiveAction.execute(evt);
  32692. this.skipToNextActiveAction();
  32693. };
  32694. Action.prototype.execute = function (evt) {
  32695. };
  32696. Action.prototype.skipToNextActiveAction = function () {
  32697. if (this._nextActiveAction._child) {
  32698. if (!this._nextActiveAction._child._actionManager) {
  32699. this._nextActiveAction._child._actionManager = this._actionManager;
  32700. }
  32701. this._nextActiveAction = this._nextActiveAction._child;
  32702. }
  32703. else {
  32704. this._nextActiveAction = this;
  32705. }
  32706. };
  32707. Action.prototype.then = function (action) {
  32708. this._child = action;
  32709. action._actionManager = this._actionManager;
  32710. action._prepare();
  32711. return action;
  32712. };
  32713. Action.prototype._getProperty = function (propertyPath) {
  32714. return this._actionManager._getProperty(propertyPath);
  32715. };
  32716. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  32717. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32718. };
  32719. Action.prototype.serialize = function (parent) {
  32720. };
  32721. // Called by BABYLON.Action objects in serialize(...). Internal use
  32722. Action.prototype._serialize = function (serializedAction, parent) {
  32723. var serializationObject = {
  32724. type: 1,
  32725. children: [],
  32726. name: serializedAction.name,
  32727. properties: serializedAction.properties || []
  32728. };
  32729. // Serialize child
  32730. if (this._child) {
  32731. this._child.serialize(serializationObject);
  32732. }
  32733. // Check if "this" has a condition
  32734. if (this._condition) {
  32735. var serializedCondition = this._condition.serialize();
  32736. serializedCondition.children.push(serializationObject);
  32737. if (parent) {
  32738. parent.children.push(serializedCondition);
  32739. }
  32740. return serializedCondition;
  32741. }
  32742. if (parent) {
  32743. parent.children.push(serializationObject);
  32744. }
  32745. return serializationObject;
  32746. };
  32747. return Action;
  32748. }());
  32749. Action._SerializeValueAsString = function (value) {
  32750. if (typeof value === "number") {
  32751. return value.toString();
  32752. }
  32753. if (typeof value === "boolean") {
  32754. return value ? "true" : "false";
  32755. }
  32756. if (value instanceof BABYLON.Vector2) {
  32757. return value.x + ", " + value.y;
  32758. }
  32759. if (value instanceof BABYLON.Vector3) {
  32760. return value.x + ", " + value.y + ", " + value.z;
  32761. }
  32762. if (value instanceof BABYLON.Color3) {
  32763. return value.r + ", " + value.g + ", " + value.b;
  32764. }
  32765. if (value instanceof BABYLON.Color4) {
  32766. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  32767. }
  32768. return value; // string
  32769. };
  32770. Action._GetTargetProperty = function (target) {
  32771. return {
  32772. name: "target",
  32773. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  32774. : target instanceof BABYLON.Light ? "LightProperties"
  32775. : target instanceof BABYLON.Camera ? "CameraProperties"
  32776. : "SceneProperties",
  32777. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  32778. };
  32779. };
  32780. BABYLON.Action = Action;
  32781. })(BABYLON || (BABYLON = {}));
  32782. //# sourceMappingURL=babylon.action.js.map
  32783. var BABYLON;
  32784. (function (BABYLON) {
  32785. /**
  32786. * ActionEvent is the event beint sent when an action is triggered.
  32787. */
  32788. var ActionEvent = (function () {
  32789. /**
  32790. * @constructor
  32791. * @param source The mesh or sprite that triggered the action.
  32792. * @param pointerX The X mouse cursor position at the time of the event
  32793. * @param pointerY The Y mouse cursor position at the time of the event
  32794. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  32795. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  32796. */
  32797. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  32798. this.source = source;
  32799. this.pointerX = pointerX;
  32800. this.pointerY = pointerY;
  32801. this.meshUnderPointer = meshUnderPointer;
  32802. this.sourceEvent = sourceEvent;
  32803. this.additionalData = additionalData;
  32804. }
  32805. /**
  32806. * Helper function to auto-create an ActionEvent from a source mesh.
  32807. * @param source The source mesh that triggered the event
  32808. * @param evt {Event} The original (browser) event
  32809. */
  32810. ActionEvent.CreateNew = function (source, evt, additionalData) {
  32811. var scene = source.getScene();
  32812. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32813. };
  32814. /**
  32815. * Helper function to auto-create an ActionEvent from a source mesh.
  32816. * @param source The source sprite that triggered the event
  32817. * @param scene Scene associated with the sprite
  32818. * @param evt {Event} The original (browser) event
  32819. */
  32820. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  32821. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32822. };
  32823. /**
  32824. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  32825. * @param scene the scene where the event occurred
  32826. * @param evt {Event} The original (browser) event
  32827. */
  32828. ActionEvent.CreateNewFromScene = function (scene, evt) {
  32829. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  32830. };
  32831. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  32832. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  32833. };
  32834. return ActionEvent;
  32835. }());
  32836. BABYLON.ActionEvent = ActionEvent;
  32837. /**
  32838. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  32839. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  32840. */
  32841. var ActionManager = (function () {
  32842. function ActionManager(scene) {
  32843. // Members
  32844. this.actions = new Array();
  32845. this.hoverCursor = '';
  32846. this._scene = scene;
  32847. scene._actionManagers.push(this);
  32848. }
  32849. Object.defineProperty(ActionManager, "NothingTrigger", {
  32850. get: function () {
  32851. return ActionManager._NothingTrigger;
  32852. },
  32853. enumerable: true,
  32854. configurable: true
  32855. });
  32856. Object.defineProperty(ActionManager, "OnPickTrigger", {
  32857. get: function () {
  32858. return ActionManager._OnPickTrigger;
  32859. },
  32860. enumerable: true,
  32861. configurable: true
  32862. });
  32863. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  32864. get: function () {
  32865. return ActionManager._OnLeftPickTrigger;
  32866. },
  32867. enumerable: true,
  32868. configurable: true
  32869. });
  32870. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  32871. get: function () {
  32872. return ActionManager._OnRightPickTrigger;
  32873. },
  32874. enumerable: true,
  32875. configurable: true
  32876. });
  32877. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  32878. get: function () {
  32879. return ActionManager._OnCenterPickTrigger;
  32880. },
  32881. enumerable: true,
  32882. configurable: true
  32883. });
  32884. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  32885. get: function () {
  32886. return ActionManager._OnPickDownTrigger;
  32887. },
  32888. enumerable: true,
  32889. configurable: true
  32890. });
  32891. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  32892. get: function () {
  32893. return ActionManager._OnDoublePickTrigger;
  32894. },
  32895. enumerable: true,
  32896. configurable: true
  32897. });
  32898. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  32899. get: function () {
  32900. return ActionManager._OnPickUpTrigger;
  32901. },
  32902. enumerable: true,
  32903. configurable: true
  32904. });
  32905. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  32906. /// This trigger will only be raised if you also declared a OnPickDown
  32907. get: function () {
  32908. return ActionManager._OnPickOutTrigger;
  32909. },
  32910. enumerable: true,
  32911. configurable: true
  32912. });
  32913. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  32914. get: function () {
  32915. return ActionManager._OnLongPressTrigger;
  32916. },
  32917. enumerable: true,
  32918. configurable: true
  32919. });
  32920. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  32921. get: function () {
  32922. return ActionManager._OnPointerOverTrigger;
  32923. },
  32924. enumerable: true,
  32925. configurable: true
  32926. });
  32927. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  32928. get: function () {
  32929. return ActionManager._OnPointerOutTrigger;
  32930. },
  32931. enumerable: true,
  32932. configurable: true
  32933. });
  32934. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  32935. get: function () {
  32936. return ActionManager._OnEveryFrameTrigger;
  32937. },
  32938. enumerable: true,
  32939. configurable: true
  32940. });
  32941. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  32942. get: function () {
  32943. return ActionManager._OnIntersectionEnterTrigger;
  32944. },
  32945. enumerable: true,
  32946. configurable: true
  32947. });
  32948. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  32949. get: function () {
  32950. return ActionManager._OnIntersectionExitTrigger;
  32951. },
  32952. enumerable: true,
  32953. configurable: true
  32954. });
  32955. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  32956. get: function () {
  32957. return ActionManager._OnKeyDownTrigger;
  32958. },
  32959. enumerable: true,
  32960. configurable: true
  32961. });
  32962. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  32963. get: function () {
  32964. return ActionManager._OnKeyUpTrigger;
  32965. },
  32966. enumerable: true,
  32967. configurable: true
  32968. });
  32969. // Methods
  32970. ActionManager.prototype.dispose = function () {
  32971. var index = this._scene._actionManagers.indexOf(this);
  32972. for (var i = 0; i < this.actions.length; i++) {
  32973. var action = this.actions[i];
  32974. ActionManager.Triggers[action.trigger]--;
  32975. if (ActionManager.Triggers[action.trigger] === 0) {
  32976. delete ActionManager.Triggers[action.trigger];
  32977. }
  32978. }
  32979. if (index > -1) {
  32980. this._scene._actionManagers.splice(index, 1);
  32981. }
  32982. };
  32983. ActionManager.prototype.getScene = function () {
  32984. return this._scene;
  32985. };
  32986. /**
  32987. * Does this action manager handles actions of any of the given triggers
  32988. * @param {number[]} triggers - the triggers to be tested
  32989. * @return {boolean} whether one (or more) of the triggers is handeled
  32990. */
  32991. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  32992. for (var index = 0; index < this.actions.length; index++) {
  32993. var action = this.actions[index];
  32994. if (triggers.indexOf(action.trigger) > -1) {
  32995. return true;
  32996. }
  32997. }
  32998. return false;
  32999. };
  33000. /**
  33001. * Does this action manager handles actions of a given trigger
  33002. * @param {number} trigger - the trigger to be tested
  33003. * @return {boolean} whether the trigger is handeled
  33004. */
  33005. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  33006. for (var index = 0; index < this.actions.length; index++) {
  33007. var action = this.actions[index];
  33008. if (action.trigger === trigger) {
  33009. return true;
  33010. }
  33011. }
  33012. return false;
  33013. };
  33014. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  33015. /**
  33016. * Does this action manager has pointer triggers
  33017. * @return {boolean} whether or not it has pointer triggers
  33018. */
  33019. get: function () {
  33020. for (var index = 0; index < this.actions.length; index++) {
  33021. var action = this.actions[index];
  33022. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  33023. return true;
  33024. }
  33025. }
  33026. return false;
  33027. },
  33028. enumerable: true,
  33029. configurable: true
  33030. });
  33031. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  33032. /**
  33033. * Does this action manager has pick triggers
  33034. * @return {boolean} whether or not it has pick triggers
  33035. */
  33036. get: function () {
  33037. for (var index = 0; index < this.actions.length; index++) {
  33038. var action = this.actions[index];
  33039. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  33040. return true;
  33041. }
  33042. }
  33043. return false;
  33044. },
  33045. enumerable: true,
  33046. configurable: true
  33047. });
  33048. Object.defineProperty(ActionManager, "HasTriggers", {
  33049. /**
  33050. * Does exist one action manager with at least one trigger
  33051. * @return {boolean} whether or not it exists one action manager with one trigger
  33052. **/
  33053. get: function () {
  33054. for (var t in ActionManager.Triggers) {
  33055. if (ActionManager.Triggers.hasOwnProperty(t)) {
  33056. return true;
  33057. }
  33058. }
  33059. return false;
  33060. },
  33061. enumerable: true,
  33062. configurable: true
  33063. });
  33064. Object.defineProperty(ActionManager, "HasPickTriggers", {
  33065. /**
  33066. * Does exist one action manager with at least one pick trigger
  33067. * @return {boolean} whether or not it exists one action manager with one pick trigger
  33068. **/
  33069. get: function () {
  33070. for (var t in ActionManager.Triggers) {
  33071. if (ActionManager.Triggers.hasOwnProperty(t)) {
  33072. var t_int = parseInt(t);
  33073. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  33074. return true;
  33075. }
  33076. }
  33077. }
  33078. return false;
  33079. },
  33080. enumerable: true,
  33081. configurable: true
  33082. });
  33083. /**
  33084. * Does exist one action manager that handles actions of a given trigger
  33085. * @param {number} trigger - the trigger to be tested
  33086. * @return {boolean} whether the trigger is handeled by at least one action manager
  33087. **/
  33088. ActionManager.HasSpecificTrigger = function (trigger) {
  33089. for (var t in ActionManager.Triggers) {
  33090. if (ActionManager.Triggers.hasOwnProperty(t)) {
  33091. var t_int = parseInt(t);
  33092. if (t_int === trigger) {
  33093. return true;
  33094. }
  33095. }
  33096. }
  33097. return false;
  33098. };
  33099. /**
  33100. * Registers an action to this action manager
  33101. * @param {BABYLON.Action} action - the action to be registered
  33102. * @return {BABYLON.Action} the action amended (prepared) after registration
  33103. */
  33104. ActionManager.prototype.registerAction = function (action) {
  33105. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  33106. if (this.getScene().actionManager !== this) {
  33107. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  33108. return null;
  33109. }
  33110. }
  33111. this.actions.push(action);
  33112. if (ActionManager.Triggers[action.trigger]) {
  33113. ActionManager.Triggers[action.trigger]++;
  33114. }
  33115. else {
  33116. ActionManager.Triggers[action.trigger] = 1;
  33117. }
  33118. action._actionManager = this;
  33119. action._prepare();
  33120. return action;
  33121. };
  33122. /**
  33123. * Process a specific trigger
  33124. * @param {number} trigger - the trigger to process
  33125. * @param evt {BABYLON.ActionEvent} the event details to be processed
  33126. */
  33127. ActionManager.prototype.processTrigger = function (trigger, evt) {
  33128. for (var index = 0; index < this.actions.length; index++) {
  33129. var action = this.actions[index];
  33130. if (action.trigger === trigger) {
  33131. if (trigger === ActionManager.OnKeyUpTrigger
  33132. || trigger === ActionManager.OnKeyDownTrigger) {
  33133. var parameter = action.getTriggerParameter();
  33134. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  33135. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  33136. var actualkey = String.fromCharCode(unicode).toLowerCase();
  33137. if (actualkey !== parameter.toLowerCase()) {
  33138. continue;
  33139. }
  33140. }
  33141. }
  33142. action._executeCurrent(evt);
  33143. }
  33144. }
  33145. };
  33146. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  33147. var properties = propertyPath.split(".");
  33148. for (var index = 0; index < properties.length - 1; index++) {
  33149. target = target[properties[index]];
  33150. }
  33151. return target;
  33152. };
  33153. ActionManager.prototype._getProperty = function (propertyPath) {
  33154. var properties = propertyPath.split(".");
  33155. return properties[properties.length - 1];
  33156. };
  33157. ActionManager.prototype.serialize = function (name) {
  33158. var root = {
  33159. children: [],
  33160. name: name,
  33161. type: 3,
  33162. properties: [] // Empty for root but required
  33163. };
  33164. for (var i = 0; i < this.actions.length; i++) {
  33165. var triggerObject = {
  33166. type: 0,
  33167. children: [],
  33168. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  33169. properties: []
  33170. };
  33171. var triggerOptions = this.actions[i].triggerOptions;
  33172. if (triggerOptions && typeof triggerOptions !== "number") {
  33173. if (triggerOptions.parameter instanceof BABYLON.Node) {
  33174. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  33175. }
  33176. else {
  33177. var parameter = {};
  33178. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  33179. if (triggerOptions.parameter.mesh) {
  33180. parameter._meshId = triggerOptions.parameter.mesh.id;
  33181. }
  33182. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  33183. }
  33184. }
  33185. // Serialize child action, recursively
  33186. this.actions[i].serialize(triggerObject);
  33187. // Add serialized trigger
  33188. root.children.push(triggerObject);
  33189. }
  33190. return root;
  33191. };
  33192. ActionManager.Parse = function (parsedActions, object, scene) {
  33193. var actionManager = new BABYLON.ActionManager(scene);
  33194. if (object === null)
  33195. scene.actionManager = actionManager;
  33196. else
  33197. object.actionManager = actionManager;
  33198. // instanciate a new object
  33199. var instanciate = function (name, params) {
  33200. var newInstance = Object.create(BABYLON[name].prototype);
  33201. newInstance.constructor.apply(newInstance, params);
  33202. return newInstance;
  33203. };
  33204. var parseParameter = function (name, value, target, propertyPath) {
  33205. if (propertyPath === null) {
  33206. // String, boolean or float
  33207. var floatValue = parseFloat(value);
  33208. if (value === "true" || value === "false")
  33209. return value === "true";
  33210. else
  33211. return isNaN(floatValue) ? value : floatValue;
  33212. }
  33213. var effectiveTarget = propertyPath.split(".");
  33214. var values = value.split(",");
  33215. // Get effective Target
  33216. for (var i = 0; i < effectiveTarget.length; i++) {
  33217. target = target[effectiveTarget[i]];
  33218. }
  33219. // Return appropriate value with its type
  33220. if (typeof (target) === "boolean")
  33221. return values[0] === "true";
  33222. if (typeof (target) === "string")
  33223. return values[0];
  33224. // Parameters with multiple values such as Vector3 etc.
  33225. var split = new Array();
  33226. for (var i = 0; i < values.length; i++)
  33227. split.push(parseFloat(values[i]));
  33228. if (target instanceof BABYLON.Vector3)
  33229. return BABYLON.Vector3.FromArray(split);
  33230. if (target instanceof BABYLON.Vector4)
  33231. return BABYLON.Vector4.FromArray(split);
  33232. if (target instanceof BABYLON.Color3)
  33233. return BABYLON.Color3.FromArray(split);
  33234. if (target instanceof BABYLON.Color4)
  33235. return BABYLON.Color4.FromArray(split);
  33236. return parseFloat(values[0]);
  33237. };
  33238. // traverse graph per trigger
  33239. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  33240. if (combineArray === void 0) { combineArray = null; }
  33241. if (parsedAction.detached)
  33242. return;
  33243. var parameters = new Array();
  33244. var target = null;
  33245. var propertyPath = null;
  33246. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  33247. // Parameters
  33248. if (parsedAction.type === 2)
  33249. parameters.push(actionManager);
  33250. else
  33251. parameters.push(trigger);
  33252. if (combine) {
  33253. var actions = new Array();
  33254. for (var j = 0; j < parsedAction.combine.length; j++) {
  33255. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  33256. }
  33257. parameters.push(actions);
  33258. }
  33259. else {
  33260. for (var i = 0; i < parsedAction.properties.length; i++) {
  33261. var value = parsedAction.properties[i].value;
  33262. var name = parsedAction.properties[i].name;
  33263. var targetType = parsedAction.properties[i].targetType;
  33264. if (name === "target")
  33265. if (targetType !== null && targetType === "SceneProperties")
  33266. value = target = scene;
  33267. else
  33268. value = target = scene.getNodeByName(value);
  33269. else if (name === "parent")
  33270. value = scene.getNodeByName(value);
  33271. else if (name === "sound")
  33272. value = scene.getSoundByName(value);
  33273. else if (name !== "propertyPath") {
  33274. if (parsedAction.type === 2 && name === "operator")
  33275. value = BABYLON.ValueCondition[value];
  33276. else
  33277. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  33278. }
  33279. else {
  33280. propertyPath = value;
  33281. }
  33282. parameters.push(value);
  33283. }
  33284. }
  33285. if (combineArray === null) {
  33286. parameters.push(condition);
  33287. }
  33288. else {
  33289. parameters.push(null);
  33290. }
  33291. // If interpolate value action
  33292. if (parsedAction.name === "InterpolateValueAction") {
  33293. var param = parameters[parameters.length - 2];
  33294. parameters[parameters.length - 1] = param;
  33295. parameters[parameters.length - 2] = condition;
  33296. }
  33297. // Action or condition(s) and not CombineAction
  33298. var newAction = instanciate(parsedAction.name, parameters);
  33299. if (newAction instanceof BABYLON.Condition && condition !== null) {
  33300. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  33301. if (action)
  33302. action.then(nothing);
  33303. else
  33304. actionManager.registerAction(nothing);
  33305. action = nothing;
  33306. }
  33307. if (combineArray === null) {
  33308. if (newAction instanceof BABYLON.Condition) {
  33309. condition = newAction;
  33310. newAction = action;
  33311. }
  33312. else {
  33313. condition = null;
  33314. if (action)
  33315. action.then(newAction);
  33316. else
  33317. actionManager.registerAction(newAction);
  33318. }
  33319. }
  33320. else {
  33321. combineArray.push(newAction);
  33322. }
  33323. for (var i = 0; i < parsedAction.children.length; i++)
  33324. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  33325. };
  33326. // triggers
  33327. for (var i = 0; i < parsedActions.children.length; i++) {
  33328. var triggerParams;
  33329. var trigger = parsedActions.children[i];
  33330. if (trigger.properties.length > 0) {
  33331. var param = trigger.properties[0].value;
  33332. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  33333. if (value._meshId) {
  33334. value.mesh = scene.getMeshByID(value._meshId);
  33335. }
  33336. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  33337. }
  33338. else
  33339. triggerParams = BABYLON.ActionManager[trigger.name];
  33340. for (var j = 0; j < trigger.children.length; j++) {
  33341. if (!trigger.detached)
  33342. traverse(trigger.children[j], triggerParams, null, null);
  33343. }
  33344. }
  33345. };
  33346. ActionManager.GetTriggerName = function (trigger) {
  33347. switch (trigger) {
  33348. case 0: return "NothingTrigger";
  33349. case 1: return "OnPickTrigger";
  33350. case 2: return "OnLeftPickTrigger";
  33351. case 3: return "OnRightPickTrigger";
  33352. case 4: return "OnCenterPickTrigger";
  33353. case 5: return "OnPickDownTrigger";
  33354. case 6: return "OnPickUpTrigger";
  33355. case 7: return "OnLongPressTrigger";
  33356. case 8: return "OnPointerOverTrigger";
  33357. case 9: return "OnPointerOutTrigger";
  33358. case 10: return "OnEveryFrameTrigger";
  33359. case 11: return "OnIntersectionEnterTrigger";
  33360. case 12: return "OnIntersectionExitTrigger";
  33361. case 13: return "OnKeyDownTrigger";
  33362. case 14: return "OnKeyUpTrigger";
  33363. case 15: return "OnPickOutTrigger";
  33364. default: return "";
  33365. }
  33366. };
  33367. return ActionManager;
  33368. }());
  33369. // Statics
  33370. ActionManager._NothingTrigger = 0;
  33371. ActionManager._OnPickTrigger = 1;
  33372. ActionManager._OnLeftPickTrigger = 2;
  33373. ActionManager._OnRightPickTrigger = 3;
  33374. ActionManager._OnCenterPickTrigger = 4;
  33375. ActionManager._OnPickDownTrigger = 5;
  33376. ActionManager._OnDoublePickTrigger = 6;
  33377. ActionManager._OnPickUpTrigger = 7;
  33378. ActionManager._OnLongPressTrigger = 8;
  33379. ActionManager._OnPointerOverTrigger = 9;
  33380. ActionManager._OnPointerOutTrigger = 10;
  33381. ActionManager._OnEveryFrameTrigger = 11;
  33382. ActionManager._OnIntersectionEnterTrigger = 12;
  33383. ActionManager._OnIntersectionExitTrigger = 13;
  33384. ActionManager._OnKeyDownTrigger = 14;
  33385. ActionManager._OnKeyUpTrigger = 15;
  33386. ActionManager._OnPickOutTrigger = 16;
  33387. ActionManager.Triggers = {};
  33388. BABYLON.ActionManager = ActionManager;
  33389. })(BABYLON || (BABYLON = {}));
  33390. //# sourceMappingURL=babylon.actionManager.js.map
  33391. var BABYLON;
  33392. (function (BABYLON) {
  33393. var InterpolateValueAction = (function (_super) {
  33394. __extends(InterpolateValueAction, _super);
  33395. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  33396. if (duration === void 0) { duration = 1000; }
  33397. var _this = _super.call(this, triggerOptions, condition) || this;
  33398. _this.propertyPath = propertyPath;
  33399. _this.value = value;
  33400. _this.duration = duration;
  33401. _this.stopOtherAnimations = stopOtherAnimations;
  33402. _this.onInterpolationDone = onInterpolationDone;
  33403. _this._target = _this._effectiveTarget = target;
  33404. return _this;
  33405. }
  33406. InterpolateValueAction.prototype._prepare = function () {
  33407. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33408. this._property = this._getProperty(this.propertyPath);
  33409. };
  33410. InterpolateValueAction.prototype.execute = function () {
  33411. var scene = this._actionManager.getScene();
  33412. var keys = [
  33413. {
  33414. frame: 0,
  33415. value: this._effectiveTarget[this._property]
  33416. }, {
  33417. frame: 100,
  33418. value: this.value
  33419. }
  33420. ];
  33421. var dataType;
  33422. if (typeof this.value === "number") {
  33423. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  33424. }
  33425. else if (this.value instanceof BABYLON.Color3) {
  33426. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  33427. }
  33428. else if (this.value instanceof BABYLON.Vector3) {
  33429. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  33430. }
  33431. else if (this.value instanceof BABYLON.Matrix) {
  33432. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  33433. }
  33434. else if (this.value instanceof BABYLON.Quaternion) {
  33435. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  33436. }
  33437. else {
  33438. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  33439. return;
  33440. }
  33441. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  33442. animation.setKeys(keys);
  33443. if (this.stopOtherAnimations) {
  33444. scene.stopAnimation(this._effectiveTarget);
  33445. }
  33446. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  33447. };
  33448. InterpolateValueAction.prototype.serialize = function (parent) {
  33449. return _super.prototype._serialize.call(this, {
  33450. name: "InterpolateValueAction",
  33451. properties: [
  33452. BABYLON.Action._GetTargetProperty(this._target),
  33453. { name: "propertyPath", value: this.propertyPath },
  33454. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33455. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  33456. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  33457. ]
  33458. }, parent);
  33459. };
  33460. return InterpolateValueAction;
  33461. }(BABYLON.Action));
  33462. BABYLON.InterpolateValueAction = InterpolateValueAction;
  33463. })(BABYLON || (BABYLON = {}));
  33464. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  33465. var BABYLON;
  33466. (function (BABYLON) {
  33467. var SwitchBooleanAction = (function (_super) {
  33468. __extends(SwitchBooleanAction, _super);
  33469. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  33470. var _this = _super.call(this, triggerOptions, condition) || this;
  33471. _this.propertyPath = propertyPath;
  33472. _this._target = _this._effectiveTarget = target;
  33473. return _this;
  33474. }
  33475. SwitchBooleanAction.prototype._prepare = function () {
  33476. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33477. this._property = this._getProperty(this.propertyPath);
  33478. };
  33479. SwitchBooleanAction.prototype.execute = function () {
  33480. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  33481. };
  33482. SwitchBooleanAction.prototype.serialize = function (parent) {
  33483. return _super.prototype._serialize.call(this, {
  33484. name: "SwitchBooleanAction",
  33485. properties: [
  33486. BABYLON.Action._GetTargetProperty(this._target),
  33487. { name: "propertyPath", value: this.propertyPath }
  33488. ]
  33489. }, parent);
  33490. };
  33491. return SwitchBooleanAction;
  33492. }(BABYLON.Action));
  33493. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  33494. var SetStateAction = (function (_super) {
  33495. __extends(SetStateAction, _super);
  33496. function SetStateAction(triggerOptions, target, value, condition) {
  33497. var _this = _super.call(this, triggerOptions, condition) || this;
  33498. _this.value = value;
  33499. _this._target = target;
  33500. return _this;
  33501. }
  33502. SetStateAction.prototype.execute = function () {
  33503. this._target.state = this.value;
  33504. };
  33505. SetStateAction.prototype.serialize = function (parent) {
  33506. return _super.prototype._serialize.call(this, {
  33507. name: "SetStateAction",
  33508. properties: [
  33509. BABYLON.Action._GetTargetProperty(this._target),
  33510. { name: "value", value: this.value }
  33511. ]
  33512. }, parent);
  33513. };
  33514. return SetStateAction;
  33515. }(BABYLON.Action));
  33516. BABYLON.SetStateAction = SetStateAction;
  33517. var SetValueAction = (function (_super) {
  33518. __extends(SetValueAction, _super);
  33519. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  33520. var _this = _super.call(this, triggerOptions, condition) || this;
  33521. _this.propertyPath = propertyPath;
  33522. _this.value = value;
  33523. _this._target = _this._effectiveTarget = target;
  33524. return _this;
  33525. }
  33526. SetValueAction.prototype._prepare = function () {
  33527. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33528. this._property = this._getProperty(this.propertyPath);
  33529. };
  33530. SetValueAction.prototype.execute = function () {
  33531. this._effectiveTarget[this._property] = this.value;
  33532. if (this._target.markAsDirty) {
  33533. this._target.markAsDirty(this._property);
  33534. }
  33535. };
  33536. SetValueAction.prototype.serialize = function (parent) {
  33537. return _super.prototype._serialize.call(this, {
  33538. name: "SetValueAction",
  33539. properties: [
  33540. BABYLON.Action._GetTargetProperty(this._target),
  33541. { name: "propertyPath", value: this.propertyPath },
  33542. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33543. ]
  33544. }, parent);
  33545. };
  33546. return SetValueAction;
  33547. }(BABYLON.Action));
  33548. BABYLON.SetValueAction = SetValueAction;
  33549. var IncrementValueAction = (function (_super) {
  33550. __extends(IncrementValueAction, _super);
  33551. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  33552. var _this = _super.call(this, triggerOptions, condition) || this;
  33553. _this.propertyPath = propertyPath;
  33554. _this.value = value;
  33555. _this._target = _this._effectiveTarget = target;
  33556. return _this;
  33557. }
  33558. IncrementValueAction.prototype._prepare = function () {
  33559. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33560. this._property = this._getProperty(this.propertyPath);
  33561. if (typeof this._effectiveTarget[this._property] !== "number") {
  33562. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  33563. }
  33564. };
  33565. IncrementValueAction.prototype.execute = function () {
  33566. this._effectiveTarget[this._property] += this.value;
  33567. if (this._target.markAsDirty) {
  33568. this._target.markAsDirty(this._property);
  33569. }
  33570. };
  33571. IncrementValueAction.prototype.serialize = function (parent) {
  33572. return _super.prototype._serialize.call(this, {
  33573. name: "IncrementValueAction",
  33574. properties: [
  33575. BABYLON.Action._GetTargetProperty(this._target),
  33576. { name: "propertyPath", value: this.propertyPath },
  33577. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33578. ]
  33579. }, parent);
  33580. };
  33581. return IncrementValueAction;
  33582. }(BABYLON.Action));
  33583. BABYLON.IncrementValueAction = IncrementValueAction;
  33584. var PlayAnimationAction = (function (_super) {
  33585. __extends(PlayAnimationAction, _super);
  33586. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  33587. var _this = _super.call(this, triggerOptions, condition) || this;
  33588. _this.from = from;
  33589. _this.to = to;
  33590. _this.loop = loop;
  33591. _this._target = target;
  33592. return _this;
  33593. }
  33594. PlayAnimationAction.prototype._prepare = function () {
  33595. };
  33596. PlayAnimationAction.prototype.execute = function () {
  33597. var scene = this._actionManager.getScene();
  33598. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  33599. };
  33600. PlayAnimationAction.prototype.serialize = function (parent) {
  33601. return _super.prototype._serialize.call(this, {
  33602. name: "PlayAnimationAction",
  33603. properties: [
  33604. BABYLON.Action._GetTargetProperty(this._target),
  33605. { name: "from", value: String(this.from) },
  33606. { name: "to", value: String(this.to) },
  33607. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  33608. ]
  33609. }, parent);
  33610. };
  33611. return PlayAnimationAction;
  33612. }(BABYLON.Action));
  33613. BABYLON.PlayAnimationAction = PlayAnimationAction;
  33614. var StopAnimationAction = (function (_super) {
  33615. __extends(StopAnimationAction, _super);
  33616. function StopAnimationAction(triggerOptions, target, condition) {
  33617. var _this = _super.call(this, triggerOptions, condition) || this;
  33618. _this._target = target;
  33619. return _this;
  33620. }
  33621. StopAnimationAction.prototype._prepare = function () {
  33622. };
  33623. StopAnimationAction.prototype.execute = function () {
  33624. var scene = this._actionManager.getScene();
  33625. scene.stopAnimation(this._target);
  33626. };
  33627. StopAnimationAction.prototype.serialize = function (parent) {
  33628. return _super.prototype._serialize.call(this, {
  33629. name: "StopAnimationAction",
  33630. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  33631. }, parent);
  33632. };
  33633. return StopAnimationAction;
  33634. }(BABYLON.Action));
  33635. BABYLON.StopAnimationAction = StopAnimationAction;
  33636. var DoNothingAction = (function (_super) {
  33637. __extends(DoNothingAction, _super);
  33638. function DoNothingAction(triggerOptions, condition) {
  33639. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  33640. return _super.call(this, triggerOptions, condition) || this;
  33641. }
  33642. DoNothingAction.prototype.execute = function () {
  33643. };
  33644. DoNothingAction.prototype.serialize = function (parent) {
  33645. return _super.prototype._serialize.call(this, {
  33646. name: "DoNothingAction",
  33647. properties: []
  33648. }, parent);
  33649. };
  33650. return DoNothingAction;
  33651. }(BABYLON.Action));
  33652. BABYLON.DoNothingAction = DoNothingAction;
  33653. var CombineAction = (function (_super) {
  33654. __extends(CombineAction, _super);
  33655. function CombineAction(triggerOptions, children, condition) {
  33656. var _this = _super.call(this, triggerOptions, condition) || this;
  33657. _this.children = children;
  33658. return _this;
  33659. }
  33660. CombineAction.prototype._prepare = function () {
  33661. for (var index = 0; index < this.children.length; index++) {
  33662. this.children[index]._actionManager = this._actionManager;
  33663. this.children[index]._prepare();
  33664. }
  33665. };
  33666. CombineAction.prototype.execute = function (evt) {
  33667. for (var index = 0; index < this.children.length; index++) {
  33668. this.children[index].execute(evt);
  33669. }
  33670. };
  33671. CombineAction.prototype.serialize = function (parent) {
  33672. var serializationObject = _super.prototype._serialize.call(this, {
  33673. name: "CombineAction",
  33674. properties: [],
  33675. combine: []
  33676. }, parent);
  33677. for (var i = 0; i < this.children.length; i++) {
  33678. serializationObject.combine.push(this.children[i].serialize(null));
  33679. }
  33680. return serializationObject;
  33681. };
  33682. return CombineAction;
  33683. }(BABYLON.Action));
  33684. BABYLON.CombineAction = CombineAction;
  33685. var ExecuteCodeAction = (function (_super) {
  33686. __extends(ExecuteCodeAction, _super);
  33687. function ExecuteCodeAction(triggerOptions, func, condition) {
  33688. var _this = _super.call(this, triggerOptions, condition) || this;
  33689. _this.func = func;
  33690. return _this;
  33691. }
  33692. ExecuteCodeAction.prototype.execute = function (evt) {
  33693. this.func(evt);
  33694. };
  33695. return ExecuteCodeAction;
  33696. }(BABYLON.Action));
  33697. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  33698. var SetParentAction = (function (_super) {
  33699. __extends(SetParentAction, _super);
  33700. function SetParentAction(triggerOptions, target, parent, condition) {
  33701. var _this = _super.call(this, triggerOptions, condition) || this;
  33702. _this._target = target;
  33703. _this._parent = parent;
  33704. return _this;
  33705. }
  33706. SetParentAction.prototype._prepare = function () {
  33707. };
  33708. SetParentAction.prototype.execute = function () {
  33709. if (this._target.parent === this._parent) {
  33710. return;
  33711. }
  33712. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  33713. invertParentWorldMatrix.invert();
  33714. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  33715. this._target.parent = this._parent;
  33716. };
  33717. SetParentAction.prototype.serialize = function (parent) {
  33718. return _super.prototype._serialize.call(this, {
  33719. name: "SetParentAction",
  33720. properties: [
  33721. BABYLON.Action._GetTargetProperty(this._target),
  33722. BABYLON.Action._GetTargetProperty(this._parent),
  33723. ]
  33724. }, parent);
  33725. };
  33726. return SetParentAction;
  33727. }(BABYLON.Action));
  33728. BABYLON.SetParentAction = SetParentAction;
  33729. var PlaySoundAction = (function (_super) {
  33730. __extends(PlaySoundAction, _super);
  33731. function PlaySoundAction(triggerOptions, sound, condition) {
  33732. var _this = _super.call(this, triggerOptions, condition) || this;
  33733. _this._sound = sound;
  33734. return _this;
  33735. }
  33736. PlaySoundAction.prototype._prepare = function () {
  33737. };
  33738. PlaySoundAction.prototype.execute = function () {
  33739. if (this._sound !== undefined)
  33740. this._sound.play();
  33741. };
  33742. PlaySoundAction.prototype.serialize = function (parent) {
  33743. return _super.prototype._serialize.call(this, {
  33744. name: "PlaySoundAction",
  33745. properties: [{ name: "sound", value: this._sound.name }]
  33746. }, parent);
  33747. };
  33748. return PlaySoundAction;
  33749. }(BABYLON.Action));
  33750. BABYLON.PlaySoundAction = PlaySoundAction;
  33751. var StopSoundAction = (function (_super) {
  33752. __extends(StopSoundAction, _super);
  33753. function StopSoundAction(triggerOptions, sound, condition) {
  33754. var _this = _super.call(this, triggerOptions, condition) || this;
  33755. _this._sound = sound;
  33756. return _this;
  33757. }
  33758. StopSoundAction.prototype._prepare = function () {
  33759. };
  33760. StopSoundAction.prototype.execute = function () {
  33761. if (this._sound !== undefined)
  33762. this._sound.stop();
  33763. };
  33764. StopSoundAction.prototype.serialize = function (parent) {
  33765. return _super.prototype._serialize.call(this, {
  33766. name: "StopSoundAction",
  33767. properties: [{ name: "sound", value: this._sound.name }]
  33768. }, parent);
  33769. };
  33770. return StopSoundAction;
  33771. }(BABYLON.Action));
  33772. BABYLON.StopSoundAction = StopSoundAction;
  33773. })(BABYLON || (BABYLON = {}));
  33774. //# sourceMappingURL=babylon.directActions.js.map
  33775. var BABYLON;
  33776. (function (BABYLON) {
  33777. var SpriteManager = (function () {
  33778. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  33779. if (epsilon === void 0) { epsilon = 0.01; }
  33780. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33781. this.name = name;
  33782. this.sprites = new Array();
  33783. this.renderingGroupId = 0;
  33784. this.layerMask = 0x0FFFFFFF;
  33785. this.fogEnabled = true;
  33786. this.isPickable = false;
  33787. /**
  33788. * An event triggered when the manager is disposed.
  33789. * @type {BABYLON.Observable}
  33790. */
  33791. this.onDisposeObservable = new BABYLON.Observable();
  33792. this._vertexBuffers = {};
  33793. this._capacity = capacity;
  33794. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  33795. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33796. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33797. if (cellSize.width && cellSize.height) {
  33798. this.cellWidth = cellSize.width;
  33799. this.cellHeight = cellSize.height;
  33800. }
  33801. else if (cellSize !== undefined) {
  33802. this.cellWidth = cellSize;
  33803. this.cellHeight = cellSize;
  33804. }
  33805. else {
  33806. return;
  33807. }
  33808. this._epsilon = epsilon;
  33809. this._scene = scene;
  33810. this._scene.spriteManagers.push(this);
  33811. var indices = [];
  33812. var index = 0;
  33813. for (var count = 0; count < capacity; count++) {
  33814. indices.push(index);
  33815. indices.push(index + 1);
  33816. indices.push(index + 2);
  33817. indices.push(index);
  33818. indices.push(index + 2);
  33819. indices.push(index + 3);
  33820. index += 4;
  33821. }
  33822. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  33823. // VBO
  33824. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  33825. this._vertexData = new Float32Array(capacity * 16 * 4);
  33826. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  33827. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  33828. var options = this._buffer.createVertexBuffer("options", 4, 4);
  33829. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  33830. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  33831. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  33832. this._vertexBuffers["options"] = options;
  33833. this._vertexBuffers["cellInfo"] = cellInfo;
  33834. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  33835. // Effects
  33836. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  33837. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  33838. }
  33839. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  33840. set: function (callback) {
  33841. if (this._onDisposeObserver) {
  33842. this.onDisposeObservable.remove(this._onDisposeObserver);
  33843. }
  33844. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  33845. },
  33846. enumerable: true,
  33847. configurable: true
  33848. });
  33849. Object.defineProperty(SpriteManager.prototype, "texture", {
  33850. get: function () {
  33851. return this._spriteTexture;
  33852. },
  33853. set: function (value) {
  33854. this._spriteTexture = value;
  33855. },
  33856. enumerable: true,
  33857. configurable: true
  33858. });
  33859. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  33860. var arrayOffset = index * 16;
  33861. if (offsetX === 0)
  33862. offsetX = this._epsilon;
  33863. else if (offsetX === 1)
  33864. offsetX = 1 - this._epsilon;
  33865. if (offsetY === 0)
  33866. offsetY = this._epsilon;
  33867. else if (offsetY === 1)
  33868. offsetY = 1 - this._epsilon;
  33869. this._vertexData[arrayOffset] = sprite.position.x;
  33870. this._vertexData[arrayOffset + 1] = sprite.position.y;
  33871. this._vertexData[arrayOffset + 2] = sprite.position.z;
  33872. this._vertexData[arrayOffset + 3] = sprite.angle;
  33873. this._vertexData[arrayOffset + 4] = sprite.width;
  33874. this._vertexData[arrayOffset + 5] = sprite.height;
  33875. this._vertexData[arrayOffset + 6] = offsetX;
  33876. this._vertexData[arrayOffset + 7] = offsetY;
  33877. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  33878. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  33879. var offset = (sprite.cellIndex / rowSize) >> 0;
  33880. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  33881. this._vertexData[arrayOffset + 11] = offset;
  33882. // Color
  33883. this._vertexData[arrayOffset + 12] = sprite.color.r;
  33884. this._vertexData[arrayOffset + 13] = sprite.color.g;
  33885. this._vertexData[arrayOffset + 14] = sprite.color.b;
  33886. this._vertexData[arrayOffset + 15] = sprite.color.a;
  33887. };
  33888. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  33889. var count = Math.min(this._capacity, this.sprites.length);
  33890. var min = BABYLON.Vector3.Zero();
  33891. var max = BABYLON.Vector3.Zero();
  33892. var distance = Number.MAX_VALUE;
  33893. var currentSprite;
  33894. var cameraSpacePosition = BABYLON.Vector3.Zero();
  33895. var cameraView = camera.getViewMatrix();
  33896. for (var index = 0; index < count; index++) {
  33897. var sprite = this.sprites[index];
  33898. if (!sprite) {
  33899. continue;
  33900. }
  33901. if (predicate) {
  33902. if (!predicate(sprite)) {
  33903. continue;
  33904. }
  33905. }
  33906. else if (!sprite.isPickable) {
  33907. continue;
  33908. }
  33909. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  33910. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  33911. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  33912. if (ray.intersectsBoxMinMax(min, max)) {
  33913. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  33914. if (distance > currentDistance) {
  33915. distance = currentDistance;
  33916. currentSprite = sprite;
  33917. if (fastCheck) {
  33918. break;
  33919. }
  33920. }
  33921. }
  33922. }
  33923. if (currentSprite) {
  33924. var result = new BABYLON.PickingInfo();
  33925. result.hit = true;
  33926. result.pickedSprite = currentSprite;
  33927. result.distance = distance;
  33928. return result;
  33929. }
  33930. return null;
  33931. };
  33932. SpriteManager.prototype.render = function () {
  33933. // Check
  33934. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  33935. return;
  33936. var engine = this._scene.getEngine();
  33937. var baseSize = this._spriteTexture.getBaseSize();
  33938. // Sprites
  33939. var deltaTime = engine.getDeltaTime();
  33940. var max = Math.min(this._capacity, this.sprites.length);
  33941. var rowSize = baseSize.width / this.cellWidth;
  33942. var offset = 0;
  33943. for (var index = 0; index < max; index++) {
  33944. var sprite = this.sprites[index];
  33945. if (!sprite) {
  33946. continue;
  33947. }
  33948. sprite._animate(deltaTime);
  33949. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  33950. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  33951. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  33952. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  33953. }
  33954. this._buffer.update(this._vertexData);
  33955. // Render
  33956. var effect = this._effectBase;
  33957. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  33958. effect = this._effectFog;
  33959. }
  33960. engine.enableEffect(effect);
  33961. var viewMatrix = this._scene.getViewMatrix();
  33962. effect.setTexture("diffuseSampler", this._spriteTexture);
  33963. effect.setMatrix("view", viewMatrix);
  33964. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  33965. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  33966. // Fog
  33967. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  33968. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  33969. effect.setColor3("vFogColor", this._scene.fogColor);
  33970. }
  33971. // VBOs
  33972. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33973. // Draw order
  33974. engine.setDepthFunctionToLessOrEqual();
  33975. effect.setBool("alphaTest", true);
  33976. engine.setColorWrite(false);
  33977. engine.draw(true, 0, max * 6);
  33978. engine.setColorWrite(true);
  33979. effect.setBool("alphaTest", false);
  33980. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  33981. engine.draw(true, 0, max * 6);
  33982. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33983. };
  33984. SpriteManager.prototype.dispose = function () {
  33985. if (this._buffer) {
  33986. this._buffer.dispose();
  33987. this._buffer = null;
  33988. }
  33989. if (this._indexBuffer) {
  33990. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33991. this._indexBuffer = null;
  33992. }
  33993. if (this._spriteTexture) {
  33994. this._spriteTexture.dispose();
  33995. this._spriteTexture = null;
  33996. }
  33997. // Remove from scene
  33998. var index = this._scene.spriteManagers.indexOf(this);
  33999. this._scene.spriteManagers.splice(index, 1);
  34000. // Callback
  34001. this.onDisposeObservable.notifyObservers(this);
  34002. this.onDisposeObservable.clear();
  34003. };
  34004. return SpriteManager;
  34005. }());
  34006. BABYLON.SpriteManager = SpriteManager;
  34007. })(BABYLON || (BABYLON = {}));
  34008. //# sourceMappingURL=babylon.spriteManager.js.map
  34009. var BABYLON;
  34010. (function (BABYLON) {
  34011. var Sprite = (function () {
  34012. function Sprite(name, manager) {
  34013. this.name = name;
  34014. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  34015. this.width = 1.0;
  34016. this.height = 1.0;
  34017. this.angle = 0;
  34018. this.cellIndex = 0;
  34019. this.invertU = 0;
  34020. this.invertV = 0;
  34021. this.animations = new Array();
  34022. this.isPickable = false;
  34023. this._animationStarted = false;
  34024. this._loopAnimation = false;
  34025. this._fromIndex = 0;
  34026. this._toIndex = 0;
  34027. this._delay = 0;
  34028. this._direction = 1;
  34029. this._frameCount = 0;
  34030. this._time = 0;
  34031. this._manager = manager;
  34032. this._manager.sprites.push(this);
  34033. this.position = BABYLON.Vector3.Zero();
  34034. }
  34035. Object.defineProperty(Sprite.prototype, "size", {
  34036. get: function () {
  34037. return this.width;
  34038. },
  34039. set: function (value) {
  34040. this.width = value;
  34041. this.height = value;
  34042. },
  34043. enumerable: true,
  34044. configurable: true
  34045. });
  34046. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  34047. this._fromIndex = from;
  34048. this._toIndex = to;
  34049. this._loopAnimation = loop;
  34050. this._delay = delay;
  34051. this._animationStarted = true;
  34052. this._direction = from < to ? 1 : -1;
  34053. this.cellIndex = from;
  34054. this._time = 0;
  34055. this._onAnimationEnd = onAnimationEnd;
  34056. };
  34057. Sprite.prototype.stopAnimation = function () {
  34058. this._animationStarted = false;
  34059. };
  34060. Sprite.prototype._animate = function (deltaTime) {
  34061. if (!this._animationStarted)
  34062. return;
  34063. this._time += deltaTime;
  34064. if (this._time > this._delay) {
  34065. this._time = this._time % this._delay;
  34066. this.cellIndex += this._direction;
  34067. if (this.cellIndex === this._toIndex) {
  34068. if (this._loopAnimation) {
  34069. this.cellIndex = this._fromIndex;
  34070. }
  34071. else {
  34072. this._animationStarted = false;
  34073. if (this._onAnimationEnd) {
  34074. this._onAnimationEnd();
  34075. }
  34076. if (this.disposeWhenFinishedAnimating) {
  34077. this.dispose();
  34078. }
  34079. }
  34080. }
  34081. }
  34082. };
  34083. Sprite.prototype.dispose = function () {
  34084. for (var i = 0; i < this._manager.sprites.length; i++) {
  34085. if (this._manager.sprites[i] == this) {
  34086. this._manager.sprites.splice(i, 1);
  34087. }
  34088. }
  34089. };
  34090. return Sprite;
  34091. }());
  34092. BABYLON.Sprite = Sprite;
  34093. })(BABYLON || (BABYLON = {}));
  34094. //# sourceMappingURL=babylon.sprite.js.map
  34095. var BABYLON;
  34096. (function (BABYLON) {
  34097. var IntersectionInfo = (function () {
  34098. function IntersectionInfo(bu, bv, distance) {
  34099. this.bu = bu;
  34100. this.bv = bv;
  34101. this.distance = distance;
  34102. this.faceId = 0;
  34103. this.subMeshId = 0;
  34104. }
  34105. return IntersectionInfo;
  34106. }());
  34107. BABYLON.IntersectionInfo = IntersectionInfo;
  34108. var PickingInfo = (function () {
  34109. function PickingInfo() {
  34110. this.hit = false;
  34111. this.distance = 0;
  34112. this.pickedPoint = null;
  34113. this.pickedMesh = null;
  34114. this.bu = 0;
  34115. this.bv = 0;
  34116. this.faceId = -1;
  34117. this.subMeshId = 0;
  34118. this.pickedSprite = null;
  34119. }
  34120. // Methods
  34121. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  34122. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  34123. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  34124. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34125. return null;
  34126. }
  34127. var indices = this.pickedMesh.getIndices();
  34128. var result;
  34129. if (useVerticesNormals) {
  34130. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34131. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  34132. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  34133. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  34134. normal0 = normal0.scale(this.bu);
  34135. normal1 = normal1.scale(this.bv);
  34136. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  34137. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  34138. }
  34139. else {
  34140. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34141. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  34142. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  34143. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  34144. var p1p2 = vertex1.subtract(vertex2);
  34145. var p3p2 = vertex3.subtract(vertex2);
  34146. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  34147. }
  34148. if (useWorldCoordinates) {
  34149. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  34150. }
  34151. return BABYLON.Vector3.Normalize(result);
  34152. };
  34153. PickingInfo.prototype.getTextureCoordinates = function () {
  34154. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34155. return null;
  34156. }
  34157. var indices = this.pickedMesh.getIndices();
  34158. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34159. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  34160. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  34161. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  34162. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  34163. uv1 = uv1.scale(this.bu);
  34164. uv2 = uv2.scale(this.bv);
  34165. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  34166. };
  34167. return PickingInfo;
  34168. }());
  34169. BABYLON.PickingInfo = PickingInfo;
  34170. })(BABYLON || (BABYLON = {}));
  34171. //# sourceMappingURL=babylon.pickingInfo.js.map
  34172. var BABYLON;
  34173. (function (BABYLON) {
  34174. var Ray = (function () {
  34175. function Ray(origin, direction, length) {
  34176. if (length === void 0) { length = Number.MAX_VALUE; }
  34177. this.origin = origin;
  34178. this.direction = direction;
  34179. this.length = length;
  34180. }
  34181. // Methods
  34182. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  34183. var d = 0.0;
  34184. var maxValue = Number.MAX_VALUE;
  34185. var inv;
  34186. var min;
  34187. var max;
  34188. var temp;
  34189. if (Math.abs(this.direction.x) < 0.0000001) {
  34190. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  34191. return false;
  34192. }
  34193. }
  34194. else {
  34195. inv = 1.0 / this.direction.x;
  34196. min = (minimum.x - this.origin.x) * inv;
  34197. max = (maximum.x - this.origin.x) * inv;
  34198. if (max === -Infinity) {
  34199. max = Infinity;
  34200. }
  34201. if (min > max) {
  34202. temp = min;
  34203. min = max;
  34204. max = temp;
  34205. }
  34206. d = Math.max(min, d);
  34207. maxValue = Math.min(max, maxValue);
  34208. if (d > maxValue) {
  34209. return false;
  34210. }
  34211. }
  34212. if (Math.abs(this.direction.y) < 0.0000001) {
  34213. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  34214. return false;
  34215. }
  34216. }
  34217. else {
  34218. inv = 1.0 / this.direction.y;
  34219. min = (minimum.y - this.origin.y) * inv;
  34220. max = (maximum.y - this.origin.y) * inv;
  34221. if (max === -Infinity) {
  34222. max = Infinity;
  34223. }
  34224. if (min > max) {
  34225. temp = min;
  34226. min = max;
  34227. max = temp;
  34228. }
  34229. d = Math.max(min, d);
  34230. maxValue = Math.min(max, maxValue);
  34231. if (d > maxValue) {
  34232. return false;
  34233. }
  34234. }
  34235. if (Math.abs(this.direction.z) < 0.0000001) {
  34236. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  34237. return false;
  34238. }
  34239. }
  34240. else {
  34241. inv = 1.0 / this.direction.z;
  34242. min = (minimum.z - this.origin.z) * inv;
  34243. max = (maximum.z - this.origin.z) * inv;
  34244. if (max === -Infinity) {
  34245. max = Infinity;
  34246. }
  34247. if (min > max) {
  34248. temp = min;
  34249. min = max;
  34250. max = temp;
  34251. }
  34252. d = Math.max(min, d);
  34253. maxValue = Math.min(max, maxValue);
  34254. if (d > maxValue) {
  34255. return false;
  34256. }
  34257. }
  34258. return true;
  34259. };
  34260. Ray.prototype.intersectsBox = function (box) {
  34261. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  34262. };
  34263. Ray.prototype.intersectsSphere = function (sphere) {
  34264. var x = sphere.center.x - this.origin.x;
  34265. var y = sphere.center.y - this.origin.y;
  34266. var z = sphere.center.z - this.origin.z;
  34267. var pyth = (x * x) + (y * y) + (z * z);
  34268. var rr = sphere.radius * sphere.radius;
  34269. if (pyth <= rr) {
  34270. return true;
  34271. }
  34272. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  34273. if (dot < 0.0) {
  34274. return false;
  34275. }
  34276. var temp = pyth - (dot * dot);
  34277. return temp <= rr;
  34278. };
  34279. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  34280. if (!this._edge1) {
  34281. this._edge1 = BABYLON.Vector3.Zero();
  34282. this._edge2 = BABYLON.Vector3.Zero();
  34283. this._pvec = BABYLON.Vector3.Zero();
  34284. this._tvec = BABYLON.Vector3.Zero();
  34285. this._qvec = BABYLON.Vector3.Zero();
  34286. }
  34287. vertex1.subtractToRef(vertex0, this._edge1);
  34288. vertex2.subtractToRef(vertex0, this._edge2);
  34289. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  34290. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  34291. if (det === 0) {
  34292. return null;
  34293. }
  34294. var invdet = 1 / det;
  34295. this.origin.subtractToRef(vertex0, this._tvec);
  34296. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  34297. if (bu < 0 || bu > 1.0) {
  34298. return null;
  34299. }
  34300. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  34301. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  34302. if (bv < 0 || bu + bv > 1.0) {
  34303. return null;
  34304. }
  34305. //check if the distance is longer than the predefined length.
  34306. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  34307. if (distance > this.length) {
  34308. return null;
  34309. }
  34310. return new BABYLON.IntersectionInfo(bu, bv, distance);
  34311. };
  34312. Ray.prototype.intersectsPlane = function (plane) {
  34313. var distance;
  34314. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  34315. if (Math.abs(result1) < 9.99999997475243E-07) {
  34316. return null;
  34317. }
  34318. else {
  34319. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  34320. distance = (-plane.d - result2) / result1;
  34321. if (distance < 0.0) {
  34322. if (distance < -9.99999997475243E-07) {
  34323. return null;
  34324. }
  34325. else {
  34326. return 0;
  34327. }
  34328. }
  34329. return distance;
  34330. }
  34331. };
  34332. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  34333. var tm = BABYLON.Tmp.Matrix[0];
  34334. mesh.getWorldMatrix().invertToRef(tm);
  34335. if (this._tmpRay) {
  34336. Ray.TransformToRef(this, tm, this._tmpRay);
  34337. }
  34338. else {
  34339. this._tmpRay = Ray.Transform(this, tm);
  34340. }
  34341. return mesh.intersects(this._tmpRay, fastCheck);
  34342. };
  34343. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  34344. if (results) {
  34345. results.length = 0;
  34346. }
  34347. else {
  34348. results = [];
  34349. }
  34350. for (var i = 0; i < meshes.length; i++) {
  34351. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  34352. if (pickInfo.hit) {
  34353. results.push(pickInfo);
  34354. }
  34355. }
  34356. results.sort(this._comparePickingInfo);
  34357. return results;
  34358. };
  34359. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  34360. if (pickingInfoA.distance < pickingInfoB.distance) {
  34361. return -1;
  34362. }
  34363. else if (pickingInfoA.distance > pickingInfoB.distance) {
  34364. return 1;
  34365. }
  34366. else {
  34367. return 0;
  34368. }
  34369. };
  34370. /**
  34371. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  34372. * @param sega the first point of the segment to test the intersection against
  34373. * @param segb the second point of the segment to test the intersection against
  34374. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  34375. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  34376. */
  34377. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  34378. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  34379. var u = segb.subtract(sega);
  34380. var v = rsegb.subtract(this.origin);
  34381. var w = sega.subtract(this.origin);
  34382. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  34383. var b = BABYLON.Vector3.Dot(u, v);
  34384. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  34385. var d = BABYLON.Vector3.Dot(u, w);
  34386. var e = BABYLON.Vector3.Dot(v, w);
  34387. var D = a * c - b * b; // always >= 0
  34388. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  34389. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  34390. // compute the line parameters of the two closest points
  34391. if (D < Ray.smallnum) {
  34392. sN = 0.0; // force using point P0 on segment S1
  34393. sD = 1.0; // to prevent possible division by 0.0 later
  34394. tN = e;
  34395. tD = c;
  34396. }
  34397. else {
  34398. sN = (b * e - c * d);
  34399. tN = (a * e - b * d);
  34400. if (sN < 0.0) {
  34401. sN = 0.0;
  34402. tN = e;
  34403. tD = c;
  34404. }
  34405. else if (sN > sD) {
  34406. sN = sD;
  34407. tN = e + b;
  34408. tD = c;
  34409. }
  34410. }
  34411. if (tN < 0.0) {
  34412. tN = 0.0;
  34413. // recompute sc for this edge
  34414. if (-d < 0.0) {
  34415. sN = 0.0;
  34416. }
  34417. else if (-d > a)
  34418. sN = sD;
  34419. else {
  34420. sN = -d;
  34421. sD = a;
  34422. }
  34423. }
  34424. else if (tN > tD) {
  34425. tN = tD;
  34426. // recompute sc for this edge
  34427. if ((-d + b) < 0.0) {
  34428. sN = 0;
  34429. }
  34430. else if ((-d + b) > a) {
  34431. sN = sD;
  34432. }
  34433. else {
  34434. sN = (-d + b);
  34435. sD = a;
  34436. }
  34437. }
  34438. // finally do the division to get sc and tc
  34439. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  34440. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  34441. // get the difference of the two closest points
  34442. var qtc = v.multiplyByFloats(tc, tc, tc);
  34443. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  34444. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  34445. if (isIntersected) {
  34446. return qtc.length();
  34447. }
  34448. return -1;
  34449. };
  34450. // Statics
  34451. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  34452. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  34453. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  34454. var direction = end.subtract(start);
  34455. direction.normalize();
  34456. return new Ray(start, direction);
  34457. };
  34458. /**
  34459. * 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
  34460. * transformed to the given world matrix.
  34461. * @param origin The origin point
  34462. * @param end The end point
  34463. * @param world a matrix to transform the ray to. Default is the identity matrix.
  34464. */
  34465. Ray.CreateNewFromTo = function (origin, end, world) {
  34466. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  34467. var direction = end.subtract(origin);
  34468. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  34469. direction.normalize();
  34470. return Ray.Transform(new Ray(origin, direction, length), world);
  34471. };
  34472. Ray.Transform = function (ray, matrix) {
  34473. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  34474. Ray.TransformToRef(ray, matrix, result);
  34475. return result;
  34476. };
  34477. Ray.TransformToRef = function (ray, matrix, result) {
  34478. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  34479. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  34480. result.length = ray.length;
  34481. var dir = result.direction;
  34482. var len = dir.length();
  34483. if (!(len === 0 || len === 1)) {
  34484. var num = 1.0 / len;
  34485. dir.x *= num;
  34486. dir.y *= num;
  34487. dir.z *= num;
  34488. result.length *= len;
  34489. }
  34490. };
  34491. return Ray;
  34492. }());
  34493. Ray.smallnum = 0.00000001;
  34494. Ray.rayl = 10e8;
  34495. BABYLON.Ray = Ray;
  34496. })(BABYLON || (BABYLON = {}));
  34497. //# sourceMappingURL=babylon.ray.js.map
  34498. var BABYLON;
  34499. (function (BABYLON) {
  34500. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  34501. if (boxMin.x > sphereCenter.x + sphereRadius)
  34502. return false;
  34503. if (sphereCenter.x - sphereRadius > boxMax.x)
  34504. return false;
  34505. if (boxMin.y > sphereCenter.y + sphereRadius)
  34506. return false;
  34507. if (sphereCenter.y - sphereRadius > boxMax.y)
  34508. return false;
  34509. if (boxMin.z > sphereCenter.z + sphereRadius)
  34510. return false;
  34511. if (sphereCenter.z - sphereRadius > boxMax.z)
  34512. return false;
  34513. return true;
  34514. };
  34515. var getLowestRoot = (function () {
  34516. var result = { root: 0, found: false };
  34517. return function (a, b, c, maxR) {
  34518. result.root = 0;
  34519. result.found = false;
  34520. var determinant = b * b - 4.0 * a * c;
  34521. if (determinant < 0)
  34522. return result;
  34523. var sqrtD = Math.sqrt(determinant);
  34524. var r1 = (-b - sqrtD) / (2.0 * a);
  34525. var r2 = (-b + sqrtD) / (2.0 * a);
  34526. if (r1 > r2) {
  34527. var temp = r2;
  34528. r2 = r1;
  34529. r1 = temp;
  34530. }
  34531. if (r1 > 0 && r1 < maxR) {
  34532. result.root = r1;
  34533. result.found = true;
  34534. return result;
  34535. }
  34536. if (r2 > 0 && r2 < maxR) {
  34537. result.root = r2;
  34538. result.found = true;
  34539. return result;
  34540. }
  34541. return result;
  34542. };
  34543. })();
  34544. var Collider = (function () {
  34545. function Collider() {
  34546. this.radius = new BABYLON.Vector3(1, 1, 1);
  34547. this.retry = 0;
  34548. this.basePointWorld = BABYLON.Vector3.Zero();
  34549. this.velocityWorld = BABYLON.Vector3.Zero();
  34550. this.normalizedVelocity = BABYLON.Vector3.Zero();
  34551. this._collisionPoint = BABYLON.Vector3.Zero();
  34552. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  34553. this._tempVector = BABYLON.Vector3.Zero();
  34554. this._tempVector2 = BABYLON.Vector3.Zero();
  34555. this._tempVector3 = BABYLON.Vector3.Zero();
  34556. this._tempVector4 = BABYLON.Vector3.Zero();
  34557. this._edge = BABYLON.Vector3.Zero();
  34558. this._baseToVertex = BABYLON.Vector3.Zero();
  34559. this._destinationPoint = BABYLON.Vector3.Zero();
  34560. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  34561. this._displacementVector = BABYLON.Vector3.Zero();
  34562. this._collisionMask = -1;
  34563. }
  34564. Object.defineProperty(Collider.prototype, "collisionMask", {
  34565. get: function () {
  34566. return this._collisionMask;
  34567. },
  34568. set: function (mask) {
  34569. this._collisionMask = !isNaN(mask) ? mask : -1;
  34570. },
  34571. enumerable: true,
  34572. configurable: true
  34573. });
  34574. // Methods
  34575. Collider.prototype._initialize = function (source, dir, e) {
  34576. this.velocity = dir;
  34577. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  34578. this.basePoint = source;
  34579. source.multiplyToRef(this.radius, this.basePointWorld);
  34580. dir.multiplyToRef(this.radius, this.velocityWorld);
  34581. this.velocityWorldLength = this.velocityWorld.length();
  34582. this.epsilon = e;
  34583. this.collisionFound = false;
  34584. };
  34585. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  34586. pa.subtractToRef(point, this._tempVector);
  34587. pb.subtractToRef(point, this._tempVector2);
  34588. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  34589. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  34590. if (d < 0)
  34591. return false;
  34592. pc.subtractToRef(point, this._tempVector3);
  34593. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  34594. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  34595. if (d < 0)
  34596. return false;
  34597. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  34598. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  34599. return d >= 0;
  34600. };
  34601. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  34602. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  34603. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  34604. if (distance > this.velocityWorldLength + max + sphereRadius) {
  34605. return false;
  34606. }
  34607. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  34608. return false;
  34609. return true;
  34610. };
  34611. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  34612. var t0;
  34613. var embeddedInPlane = false;
  34614. //defensive programming, actually not needed.
  34615. if (!trianglePlaneArray) {
  34616. trianglePlaneArray = [];
  34617. }
  34618. if (!trianglePlaneArray[faceIndex]) {
  34619. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  34620. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  34621. }
  34622. var trianglePlane = trianglePlaneArray[faceIndex];
  34623. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  34624. return;
  34625. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  34626. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  34627. if (normalDotVelocity == 0) {
  34628. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  34629. return;
  34630. embeddedInPlane = true;
  34631. t0 = 0;
  34632. }
  34633. else {
  34634. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  34635. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  34636. if (t0 > t1) {
  34637. var temp = t1;
  34638. t1 = t0;
  34639. t0 = temp;
  34640. }
  34641. if (t0 > 1.0 || t1 < 0.0)
  34642. return;
  34643. if (t0 < 0)
  34644. t0 = 0;
  34645. if (t0 > 1.0)
  34646. t0 = 1.0;
  34647. }
  34648. this._collisionPoint.copyFromFloats(0, 0, 0);
  34649. var found = false;
  34650. var t = 1.0;
  34651. if (!embeddedInPlane) {
  34652. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  34653. this.velocity.scaleToRef(t0, this._tempVector);
  34654. this._planeIntersectionPoint.addInPlace(this._tempVector);
  34655. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  34656. found = true;
  34657. t = t0;
  34658. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  34659. }
  34660. }
  34661. if (!found) {
  34662. var velocitySquaredLength = this.velocity.lengthSquared();
  34663. var a = velocitySquaredLength;
  34664. this.basePoint.subtractToRef(p1, this._tempVector);
  34665. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  34666. var c = this._tempVector.lengthSquared() - 1.0;
  34667. var lowestRoot = getLowestRoot(a, b, c, t);
  34668. if (lowestRoot.found) {
  34669. t = lowestRoot.root;
  34670. found = true;
  34671. this._collisionPoint.copyFrom(p1);
  34672. }
  34673. this.basePoint.subtractToRef(p2, this._tempVector);
  34674. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  34675. c = this._tempVector.lengthSquared() - 1.0;
  34676. lowestRoot = getLowestRoot(a, b, c, t);
  34677. if (lowestRoot.found) {
  34678. t = lowestRoot.root;
  34679. found = true;
  34680. this._collisionPoint.copyFrom(p2);
  34681. }
  34682. this.basePoint.subtractToRef(p3, this._tempVector);
  34683. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  34684. c = this._tempVector.lengthSquared() - 1.0;
  34685. lowestRoot = getLowestRoot(a, b, c, t);
  34686. if (lowestRoot.found) {
  34687. t = lowestRoot.root;
  34688. found = true;
  34689. this._collisionPoint.copyFrom(p3);
  34690. }
  34691. p2.subtractToRef(p1, this._edge);
  34692. p1.subtractToRef(this.basePoint, this._baseToVertex);
  34693. var edgeSquaredLength = this._edge.lengthSquared();
  34694. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  34695. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  34696. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  34697. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  34698. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  34699. lowestRoot = getLowestRoot(a, b, c, t);
  34700. if (lowestRoot.found) {
  34701. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  34702. if (f >= 0.0 && f <= 1.0) {
  34703. t = lowestRoot.root;
  34704. found = true;
  34705. this._edge.scaleInPlace(f);
  34706. p1.addToRef(this._edge, this._collisionPoint);
  34707. }
  34708. }
  34709. p3.subtractToRef(p2, this._edge);
  34710. p2.subtractToRef(this.basePoint, this._baseToVertex);
  34711. edgeSquaredLength = this._edge.lengthSquared();
  34712. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  34713. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  34714. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  34715. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  34716. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  34717. lowestRoot = getLowestRoot(a, b, c, t);
  34718. if (lowestRoot.found) {
  34719. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  34720. if (f >= 0.0 && f <= 1.0) {
  34721. t = lowestRoot.root;
  34722. found = true;
  34723. this._edge.scaleInPlace(f);
  34724. p2.addToRef(this._edge, this._collisionPoint);
  34725. }
  34726. }
  34727. p1.subtractToRef(p3, this._edge);
  34728. p3.subtractToRef(this.basePoint, this._baseToVertex);
  34729. edgeSquaredLength = this._edge.lengthSquared();
  34730. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  34731. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  34732. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  34733. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  34734. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  34735. lowestRoot = getLowestRoot(a, b, c, t);
  34736. if (lowestRoot.found) {
  34737. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  34738. if (f >= 0.0 && f <= 1.0) {
  34739. t = lowestRoot.root;
  34740. found = true;
  34741. this._edge.scaleInPlace(f);
  34742. p3.addToRef(this._edge, this._collisionPoint);
  34743. }
  34744. }
  34745. }
  34746. if (found) {
  34747. var distToCollision = t * this.velocity.length();
  34748. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  34749. if (!this.intersectionPoint) {
  34750. this.intersectionPoint = this._collisionPoint.clone();
  34751. }
  34752. else {
  34753. this.intersectionPoint.copyFrom(this._collisionPoint);
  34754. }
  34755. this.nearestDistance = distToCollision;
  34756. this.collisionFound = true;
  34757. }
  34758. }
  34759. };
  34760. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  34761. for (var i = indexStart; i < indexEnd; i += 3) {
  34762. var p1 = pts[indices[i] - decal];
  34763. var p2 = pts[indices[i + 1] - decal];
  34764. var p3 = pts[indices[i + 2] - decal];
  34765. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  34766. }
  34767. };
  34768. Collider.prototype._getResponse = function (pos, vel) {
  34769. pos.addToRef(vel, this._destinationPoint);
  34770. vel.scaleInPlace((this.nearestDistance / vel.length()));
  34771. this.basePoint.addToRef(vel, pos);
  34772. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  34773. this._slidePlaneNormal.normalize();
  34774. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  34775. pos.addInPlace(this._displacementVector);
  34776. this.intersectionPoint.addInPlace(this._displacementVector);
  34777. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  34778. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  34779. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  34780. };
  34781. return Collider;
  34782. }());
  34783. BABYLON.Collider = Collider;
  34784. })(BABYLON || (BABYLON = {}));
  34785. //# sourceMappingURL=babylon.collider.js.map
  34786. var BABYLON;
  34787. (function (BABYLON) {
  34788. //WebWorker code will be inserted to this variable.
  34789. BABYLON.CollisionWorker = "";
  34790. var WorkerTaskType;
  34791. (function (WorkerTaskType) {
  34792. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  34793. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  34794. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  34795. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  34796. var WorkerReplyType;
  34797. (function (WorkerReplyType) {
  34798. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  34799. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  34800. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  34801. var CollisionCoordinatorWorker = (function () {
  34802. function CollisionCoordinatorWorker() {
  34803. var _this = this;
  34804. this._scaledPosition = BABYLON.Vector3.Zero();
  34805. this._scaledVelocity = BABYLON.Vector3.Zero();
  34806. this.onMeshUpdated = function (mesh) {
  34807. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  34808. };
  34809. this.onGeometryUpdated = function (geometry) {
  34810. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  34811. };
  34812. this._afterRender = function () {
  34813. if (!_this._init)
  34814. return;
  34815. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  34816. return;
  34817. }
  34818. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  34819. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  34820. if (_this._runningUpdated > 4) {
  34821. return;
  34822. }
  34823. ++_this._runningUpdated;
  34824. var payload = {
  34825. updatedMeshes: _this._addUpdateMeshesList,
  34826. updatedGeometries: _this._addUpdateGeometriesList,
  34827. removedGeometries: _this._toRemoveGeometryArray,
  34828. removedMeshes: _this._toRemoveMeshesArray
  34829. };
  34830. var message = {
  34831. payload: payload,
  34832. taskType: WorkerTaskType.UPDATE
  34833. };
  34834. var serializable = [];
  34835. for (var id in payload.updatedGeometries) {
  34836. if (payload.updatedGeometries.hasOwnProperty(id)) {
  34837. //prepare transferables
  34838. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  34839. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  34840. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  34841. }
  34842. }
  34843. _this._worker.postMessage(message, serializable);
  34844. _this._addUpdateMeshesList = {};
  34845. _this._addUpdateGeometriesList = {};
  34846. _this._toRemoveGeometryArray = [];
  34847. _this._toRemoveMeshesArray = [];
  34848. };
  34849. this._onMessageFromWorker = function (e) {
  34850. var returnData = e.data;
  34851. if (returnData.error != WorkerReplyType.SUCCESS) {
  34852. //TODO what errors can be returned from the worker?
  34853. BABYLON.Tools.Warn("error returned from worker!");
  34854. return;
  34855. }
  34856. switch (returnData.taskType) {
  34857. case WorkerTaskType.INIT:
  34858. _this._init = true;
  34859. //Update the worked with ALL of the scene's current state
  34860. _this._scene.meshes.forEach(function (mesh) {
  34861. _this.onMeshAdded(mesh);
  34862. });
  34863. _this._scene.getGeometries().forEach(function (geometry) {
  34864. _this.onGeometryAdded(geometry);
  34865. });
  34866. break;
  34867. case WorkerTaskType.UPDATE:
  34868. _this._runningUpdated--;
  34869. break;
  34870. case WorkerTaskType.COLLIDE:
  34871. _this._runningCollisionTask = false;
  34872. var returnPayload = returnData.payload;
  34873. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  34874. return;
  34875. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  34876. //cleanup
  34877. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  34878. break;
  34879. }
  34880. };
  34881. this._collisionsCallbackArray = [];
  34882. this._init = false;
  34883. this._runningUpdated = 0;
  34884. this._runningCollisionTask = false;
  34885. this._addUpdateMeshesList = {};
  34886. this._addUpdateGeometriesList = {};
  34887. this._toRemoveGeometryArray = [];
  34888. this._toRemoveMeshesArray = [];
  34889. }
  34890. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  34891. if (!this._init)
  34892. return;
  34893. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  34894. return;
  34895. position.divideToRef(collider.radius, this._scaledPosition);
  34896. velocity.divideToRef(collider.radius, this._scaledVelocity);
  34897. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  34898. var payload = {
  34899. collider: {
  34900. position: this._scaledPosition.asArray(),
  34901. velocity: this._scaledVelocity.asArray(),
  34902. radius: collider.radius.asArray()
  34903. },
  34904. collisionId: collisionIndex,
  34905. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  34906. maximumRetry: maximumRetry
  34907. };
  34908. var message = {
  34909. payload: payload,
  34910. taskType: WorkerTaskType.COLLIDE
  34911. };
  34912. this._worker.postMessage(message);
  34913. };
  34914. CollisionCoordinatorWorker.prototype.init = function (scene) {
  34915. this._scene = scene;
  34916. this._scene.registerAfterRender(this._afterRender);
  34917. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  34918. this._worker = new Worker(workerUrl);
  34919. this._worker.onmessage = this._onMessageFromWorker;
  34920. var message = {
  34921. payload: {},
  34922. taskType: WorkerTaskType.INIT
  34923. };
  34924. this._worker.postMessage(message);
  34925. };
  34926. CollisionCoordinatorWorker.prototype.destroy = function () {
  34927. this._scene.unregisterAfterRender(this._afterRender);
  34928. this._worker.terminate();
  34929. };
  34930. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  34931. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  34932. this.onMeshUpdated(mesh);
  34933. };
  34934. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  34935. this._toRemoveMeshesArray.push(mesh.uniqueId);
  34936. };
  34937. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  34938. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  34939. geometry.onGeometryUpdated = this.onGeometryUpdated;
  34940. this.onGeometryUpdated(geometry);
  34941. };
  34942. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  34943. this._toRemoveGeometryArray.push(geometry.id);
  34944. };
  34945. return CollisionCoordinatorWorker;
  34946. }());
  34947. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  34948. var submeshes = [];
  34949. if (mesh.subMeshes) {
  34950. submeshes = mesh.subMeshes.map(function (sm, idx) {
  34951. return {
  34952. position: idx,
  34953. verticesStart: sm.verticesStart,
  34954. verticesCount: sm.verticesCount,
  34955. indexStart: sm.indexStart,
  34956. indexCount: sm.indexCount,
  34957. hasMaterial: !!sm.getMaterial(),
  34958. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  34959. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  34960. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  34961. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  34962. };
  34963. });
  34964. }
  34965. var geometryId = null;
  34966. if (mesh instanceof BABYLON.Mesh) {
  34967. geometryId = mesh.geometry ? mesh.geometry.id : null;
  34968. }
  34969. else if (mesh instanceof BABYLON.InstancedMesh) {
  34970. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  34971. }
  34972. return {
  34973. uniqueId: mesh.uniqueId,
  34974. id: mesh.id,
  34975. name: mesh.name,
  34976. geometryId: geometryId,
  34977. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  34978. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  34979. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  34980. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  34981. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  34982. subMeshes: submeshes,
  34983. checkCollisions: mesh.checkCollisions
  34984. };
  34985. };
  34986. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  34987. return {
  34988. id: geometry.id,
  34989. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  34990. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  34991. indices: new Uint32Array(geometry.getIndices() || []),
  34992. };
  34993. };
  34994. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  34995. var CollisionCoordinatorLegacy = (function () {
  34996. function CollisionCoordinatorLegacy() {
  34997. this._scaledPosition = BABYLON.Vector3.Zero();
  34998. this._scaledVelocity = BABYLON.Vector3.Zero();
  34999. this._finalPosition = BABYLON.Vector3.Zero();
  35000. }
  35001. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  35002. position.divideToRef(collider.radius, this._scaledPosition);
  35003. velocity.divideToRef(collider.radius, this._scaledVelocity);
  35004. collider.collidedMesh = null;
  35005. collider.retry = 0;
  35006. collider.initialVelocity = this._scaledVelocity;
  35007. collider.initialPosition = this._scaledPosition;
  35008. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  35009. this._finalPosition.multiplyInPlace(collider.radius);
  35010. //run the callback
  35011. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  35012. };
  35013. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  35014. this._scene = scene;
  35015. };
  35016. CollisionCoordinatorLegacy.prototype.destroy = function () {
  35017. //Legacy need no destruction method.
  35018. };
  35019. //No update in legacy mode
  35020. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  35021. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  35022. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  35023. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  35024. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  35025. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  35026. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  35027. if (excludedMesh === void 0) { excludedMesh = null; }
  35028. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  35029. if (collider.retry >= maximumRetry) {
  35030. finalPosition.copyFrom(position);
  35031. return;
  35032. }
  35033. // Check if this is a mesh else camera or -1
  35034. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  35035. collider._initialize(position, velocity, closeDistance);
  35036. // Check all meshes
  35037. for (var index = 0; index < this._scene.meshes.length; index++) {
  35038. var mesh = this._scene.meshes[index];
  35039. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  35040. mesh._checkCollision(collider);
  35041. }
  35042. }
  35043. if (!collider.collisionFound) {
  35044. position.addToRef(velocity, finalPosition);
  35045. return;
  35046. }
  35047. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  35048. collider._getResponse(position, velocity);
  35049. }
  35050. if (velocity.length() <= closeDistance) {
  35051. finalPosition.copyFrom(position);
  35052. return;
  35053. }
  35054. collider.retry++;
  35055. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  35056. };
  35057. return CollisionCoordinatorLegacy;
  35058. }());
  35059. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  35060. })(BABYLON || (BABYLON = {}));
  35061. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  35062. var BABYLON;
  35063. (function (BABYLON) {
  35064. var Particle = (function () {
  35065. function Particle() {
  35066. this.position = BABYLON.Vector3.Zero();
  35067. this.direction = BABYLON.Vector3.Zero();
  35068. this.color = new BABYLON.Color4(0, 0, 0, 0);
  35069. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  35070. this.lifeTime = 1.0;
  35071. this.age = 0;
  35072. this.size = 0;
  35073. this.angle = 0;
  35074. this.angularSpeed = 0;
  35075. }
  35076. Particle.prototype.copyTo = function (other) {
  35077. other.position.copyFrom(this.position);
  35078. other.direction.copyFrom(this.direction);
  35079. other.color.copyFrom(this.color);
  35080. other.colorStep.copyFrom(this.colorStep);
  35081. other.lifeTime = this.lifeTime;
  35082. other.age = this.age;
  35083. other.size = this.size;
  35084. other.angle = this.angle;
  35085. other.angularSpeed = this.angularSpeed;
  35086. };
  35087. return Particle;
  35088. }());
  35089. BABYLON.Particle = Particle;
  35090. })(BABYLON || (BABYLON = {}));
  35091. //# sourceMappingURL=babylon.particle.js.map
  35092. var BABYLON;
  35093. (function (BABYLON) {
  35094. var randomNumber = function (min, max) {
  35095. if (min === max) {
  35096. return (min);
  35097. }
  35098. var random = Math.random();
  35099. return ((random * (max - min)) + min);
  35100. };
  35101. var ParticleSystem = (function () {
  35102. function ParticleSystem(name, capacity, scene, customEffect) {
  35103. var _this = this;
  35104. this.name = name;
  35105. // Members
  35106. this.animations = [];
  35107. this.renderingGroupId = 0;
  35108. this.emitter = null;
  35109. this.emitRate = 10;
  35110. this.manualEmitCount = -1;
  35111. this.updateSpeed = 0.01;
  35112. this.targetStopDuration = 0;
  35113. this.disposeOnStop = false;
  35114. this.minEmitPower = 1;
  35115. this.maxEmitPower = 1;
  35116. this.minLifeTime = 1;
  35117. this.maxLifeTime = 1;
  35118. this.minSize = 1;
  35119. this.maxSize = 1;
  35120. this.minAngularSpeed = 0;
  35121. this.maxAngularSpeed = 0;
  35122. this.layerMask = 0x0FFFFFFF;
  35123. this.customShader = null;
  35124. this.preventAutoStart = false;
  35125. /**
  35126. * An event triggered when the system is disposed.
  35127. * @type {BABYLON.Observable}
  35128. */
  35129. this.onDisposeObservable = new BABYLON.Observable();
  35130. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  35131. this.forceDepthWrite = false;
  35132. this.gravity = BABYLON.Vector3.Zero();
  35133. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  35134. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  35135. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  35136. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  35137. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  35138. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  35139. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  35140. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  35141. this.particles = new Array();
  35142. this._stockParticles = new Array();
  35143. this._newPartsExcess = 0;
  35144. this._vertexBuffers = {};
  35145. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  35146. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  35147. this._scaledDirection = BABYLON.Vector3.Zero();
  35148. this._scaledGravity = BABYLON.Vector3.Zero();
  35149. this._currentRenderId = -1;
  35150. this._started = false;
  35151. this._stopped = false;
  35152. this._actualFrame = 0;
  35153. this.id = name;
  35154. this._capacity = capacity;
  35155. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35156. this._customEffect = customEffect;
  35157. scene.particleSystems.push(this);
  35158. var indices = [];
  35159. var index = 0;
  35160. for (var count = 0; count < capacity; count++) {
  35161. indices.push(index);
  35162. indices.push(index + 1);
  35163. indices.push(index + 2);
  35164. indices.push(index);
  35165. indices.push(index + 2);
  35166. indices.push(index + 3);
  35167. index += 4;
  35168. }
  35169. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  35170. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  35171. this._vertexData = new Float32Array(capacity * 11 * 4);
  35172. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  35173. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  35174. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  35175. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  35176. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  35177. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  35178. this._vertexBuffers["options"] = options;
  35179. // Default behaviors
  35180. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  35181. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  35182. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  35183. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  35184. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  35185. };
  35186. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  35187. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  35188. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  35189. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  35190. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  35191. };
  35192. this.updateFunction = function (particles) {
  35193. for (var index = 0; index < particles.length; index++) {
  35194. var particle = particles[index];
  35195. particle.age += _this._scaledUpdateSpeed;
  35196. if (particle.age >= particle.lifeTime) {
  35197. _this.recycleParticle(particle);
  35198. index--;
  35199. continue;
  35200. }
  35201. else {
  35202. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  35203. particle.color.addInPlace(_this._scaledColorStep);
  35204. if (particle.color.a < 0)
  35205. particle.color.a = 0;
  35206. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  35207. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  35208. particle.position.addInPlace(_this._scaledDirection);
  35209. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  35210. particle.direction.addInPlace(_this._scaledGravity);
  35211. }
  35212. }
  35213. };
  35214. }
  35215. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  35216. set: function (callback) {
  35217. if (this._onDisposeObserver) {
  35218. this.onDisposeObservable.remove(this._onDisposeObserver);
  35219. }
  35220. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35221. },
  35222. enumerable: true,
  35223. configurable: true
  35224. });
  35225. ParticleSystem.prototype.recycleParticle = function (particle) {
  35226. var lastParticle = this.particles.pop();
  35227. if (lastParticle !== particle) {
  35228. lastParticle.copyTo(particle);
  35229. this._stockParticles.push(lastParticle);
  35230. }
  35231. };
  35232. ParticleSystem.prototype.getCapacity = function () {
  35233. return this._capacity;
  35234. };
  35235. ParticleSystem.prototype.isAlive = function () {
  35236. return this._alive;
  35237. };
  35238. ParticleSystem.prototype.isStarted = function () {
  35239. return this._started;
  35240. };
  35241. ParticleSystem.prototype.start = function () {
  35242. this._started = true;
  35243. this._stopped = false;
  35244. this._actualFrame = 0;
  35245. };
  35246. ParticleSystem.prototype.stop = function () {
  35247. this._stopped = true;
  35248. };
  35249. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  35250. var offset = index * 11;
  35251. this._vertexData[offset] = particle.position.x;
  35252. this._vertexData[offset + 1] = particle.position.y;
  35253. this._vertexData[offset + 2] = particle.position.z;
  35254. this._vertexData[offset + 3] = particle.color.r;
  35255. this._vertexData[offset + 4] = particle.color.g;
  35256. this._vertexData[offset + 5] = particle.color.b;
  35257. this._vertexData[offset + 6] = particle.color.a;
  35258. this._vertexData[offset + 7] = particle.angle;
  35259. this._vertexData[offset + 8] = particle.size;
  35260. this._vertexData[offset + 9] = offsetX;
  35261. this._vertexData[offset + 10] = offsetY;
  35262. };
  35263. ParticleSystem.prototype._update = function (newParticles) {
  35264. // Update current
  35265. this._alive = this.particles.length > 0;
  35266. this.updateFunction(this.particles);
  35267. // Add new ones
  35268. var worldMatrix;
  35269. if (this.emitter.position) {
  35270. worldMatrix = this.emitter.getWorldMatrix();
  35271. }
  35272. else {
  35273. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  35274. }
  35275. var particle;
  35276. for (var index = 0; index < newParticles; index++) {
  35277. if (this.particles.length === this._capacity) {
  35278. break;
  35279. }
  35280. if (this._stockParticles.length !== 0) {
  35281. particle = this._stockParticles.pop();
  35282. particle.age = 0;
  35283. }
  35284. else {
  35285. particle = new BABYLON.Particle();
  35286. }
  35287. this.particles.push(particle);
  35288. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  35289. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  35290. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  35291. particle.size = randomNumber(this.minSize, this.maxSize);
  35292. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  35293. this.startPositionFunction(worldMatrix, particle.position, particle);
  35294. var step = randomNumber(0, 1.0);
  35295. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  35296. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  35297. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  35298. }
  35299. };
  35300. ParticleSystem.prototype._getEffect = function () {
  35301. if (this._customEffect) {
  35302. return this._customEffect;
  35303. }
  35304. ;
  35305. var defines = [];
  35306. if (this._scene.clipPlane) {
  35307. defines.push("#define CLIPPLANE");
  35308. }
  35309. // Effect
  35310. var join = defines.join("\n");
  35311. if (this._cachedDefines !== join) {
  35312. this._cachedDefines = join;
  35313. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  35314. }
  35315. return this._effect;
  35316. };
  35317. ParticleSystem.prototype.animate = function () {
  35318. if (!this._started)
  35319. return;
  35320. var effect = this._getEffect();
  35321. // Check
  35322. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  35323. return;
  35324. if (this._currentRenderId === this._scene.getRenderId()) {
  35325. return;
  35326. }
  35327. this._currentRenderId = this._scene.getRenderId();
  35328. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  35329. // determine the number of particles we need to create
  35330. var newParticles;
  35331. if (this.manualEmitCount > -1) {
  35332. newParticles = this.manualEmitCount;
  35333. this._newPartsExcess = 0;
  35334. this.manualEmitCount = 0;
  35335. }
  35336. else {
  35337. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  35338. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  35339. }
  35340. if (this._newPartsExcess > 1.0) {
  35341. newParticles += this._newPartsExcess >> 0;
  35342. this._newPartsExcess -= this._newPartsExcess >> 0;
  35343. }
  35344. this._alive = false;
  35345. if (!this._stopped) {
  35346. this._actualFrame += this._scaledUpdateSpeed;
  35347. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  35348. this.stop();
  35349. }
  35350. else {
  35351. newParticles = 0;
  35352. }
  35353. this._update(newParticles);
  35354. // Stopped?
  35355. if (this._stopped) {
  35356. if (!this._alive) {
  35357. this._started = false;
  35358. if (this.disposeOnStop) {
  35359. this._scene._toBeDisposed.push(this);
  35360. }
  35361. }
  35362. }
  35363. // Update VBO
  35364. var offset = 0;
  35365. for (var index = 0; index < this.particles.length; index++) {
  35366. var particle = this.particles[index];
  35367. this._appendParticleVertex(offset++, particle, 0, 0);
  35368. this._appendParticleVertex(offset++, particle, 1, 0);
  35369. this._appendParticleVertex(offset++, particle, 1, 1);
  35370. this._appendParticleVertex(offset++, particle, 0, 1);
  35371. }
  35372. this._vertexBuffer.update(this._vertexData);
  35373. };
  35374. ParticleSystem.prototype.render = function () {
  35375. var effect = this._getEffect();
  35376. // Check
  35377. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  35378. return 0;
  35379. var engine = this._scene.getEngine();
  35380. // Render
  35381. engine.enableEffect(effect);
  35382. engine.setState(false);
  35383. var viewMatrix = this._scene.getViewMatrix();
  35384. effect.setTexture("diffuseSampler", this.particleTexture);
  35385. effect.setMatrix("view", viewMatrix);
  35386. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  35387. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  35388. if (this._scene.clipPlane) {
  35389. var clipPlane = this._scene.clipPlane;
  35390. var invView = viewMatrix.clone();
  35391. invView.invert();
  35392. effect.setMatrix("invView", invView);
  35393. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  35394. }
  35395. // VBOs
  35396. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35397. // Draw order
  35398. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  35399. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  35400. }
  35401. else {
  35402. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  35403. }
  35404. if (this.forceDepthWrite) {
  35405. engine.setDepthWrite(true);
  35406. }
  35407. engine.draw(true, 0, this.particles.length * 6);
  35408. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35409. return this.particles.length;
  35410. };
  35411. ParticleSystem.prototype.dispose = function () {
  35412. if (this._vertexBuffer) {
  35413. this._vertexBuffer.dispose();
  35414. this._vertexBuffer = null;
  35415. }
  35416. if (this._indexBuffer) {
  35417. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35418. this._indexBuffer = null;
  35419. }
  35420. if (this.particleTexture) {
  35421. this.particleTexture.dispose();
  35422. this.particleTexture = null;
  35423. }
  35424. // Remove from scene
  35425. var index = this._scene.particleSystems.indexOf(this);
  35426. this._scene.particleSystems.splice(index, 1);
  35427. // Callback
  35428. this.onDisposeObservable.notifyObservers(this);
  35429. this.onDisposeObservable.clear();
  35430. };
  35431. // Clone
  35432. ParticleSystem.prototype.clone = function (name, newEmitter) {
  35433. var custom = null;
  35434. var program = null;
  35435. if (this.customShader != null) {
  35436. program = this.customShader;
  35437. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  35438. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  35439. }
  35440. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  35441. result.customShader = program;
  35442. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  35443. if (newEmitter === undefined) {
  35444. newEmitter = this.emitter;
  35445. }
  35446. result.emitter = newEmitter;
  35447. if (this.particleTexture) {
  35448. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  35449. }
  35450. if (!this.preventAutoStart) {
  35451. result.start();
  35452. }
  35453. return result;
  35454. };
  35455. ParticleSystem.prototype.serialize = function () {
  35456. var serializationObject = {};
  35457. serializationObject.name = this.name;
  35458. serializationObject.id = this.id;
  35459. // Emitter
  35460. if (this.emitter.position) {
  35461. serializationObject.emitterId = this.emitter.id;
  35462. }
  35463. else {
  35464. serializationObject.emitter = this.emitter.asArray();
  35465. }
  35466. serializationObject.capacity = this.getCapacity();
  35467. if (this.particleTexture) {
  35468. serializationObject.textureName = this.particleTexture.name;
  35469. }
  35470. // Animations
  35471. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  35472. // Particle system
  35473. serializationObject.minAngularSpeed = this.minAngularSpeed;
  35474. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  35475. serializationObject.minSize = this.minSize;
  35476. serializationObject.maxSize = this.maxSize;
  35477. serializationObject.minEmitPower = this.minEmitPower;
  35478. serializationObject.maxEmitPower = this.maxEmitPower;
  35479. serializationObject.minLifeTime = this.minLifeTime;
  35480. serializationObject.maxLifeTime = this.maxLifeTime;
  35481. serializationObject.emitRate = this.emitRate;
  35482. serializationObject.minEmitBox = this.minEmitBox.asArray();
  35483. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  35484. serializationObject.gravity = this.gravity.asArray();
  35485. serializationObject.direction1 = this.direction1.asArray();
  35486. serializationObject.direction2 = this.direction2.asArray();
  35487. serializationObject.color1 = this.color1.asArray();
  35488. serializationObject.color2 = this.color2.asArray();
  35489. serializationObject.colorDead = this.colorDead.asArray();
  35490. serializationObject.updateSpeed = this.updateSpeed;
  35491. serializationObject.targetStopDuration = this.targetStopDuration;
  35492. serializationObject.textureMask = this.textureMask.asArray();
  35493. serializationObject.blendMode = this.blendMode;
  35494. serializationObject.customShader = this.customShader;
  35495. serializationObject.preventAutoStart = this.preventAutoStart;
  35496. return serializationObject;
  35497. };
  35498. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  35499. var name = parsedParticleSystem.name;
  35500. var custom = null;
  35501. var program = null;
  35502. if (parsedParticleSystem.customShader) {
  35503. program = parsedParticleSystem.customShader;
  35504. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  35505. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  35506. }
  35507. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  35508. particleSystem.customShader = program;
  35509. if (parsedParticleSystem.id) {
  35510. particleSystem.id = parsedParticleSystem.id;
  35511. }
  35512. // Auto start
  35513. if (parsedParticleSystem.preventAutoStart) {
  35514. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  35515. }
  35516. // Texture
  35517. if (parsedParticleSystem.textureName) {
  35518. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  35519. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  35520. }
  35521. // Emitter
  35522. if (parsedParticleSystem.emitterId) {
  35523. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  35524. }
  35525. else {
  35526. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  35527. }
  35528. // Animations
  35529. if (parsedParticleSystem.animations) {
  35530. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  35531. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  35532. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  35533. }
  35534. }
  35535. if (parsedParticleSystem.autoAnimate) {
  35536. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  35537. }
  35538. // Particle system
  35539. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  35540. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  35541. particleSystem.minSize = parsedParticleSystem.minSize;
  35542. particleSystem.maxSize = parsedParticleSystem.maxSize;
  35543. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  35544. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  35545. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  35546. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  35547. particleSystem.emitRate = parsedParticleSystem.emitRate;
  35548. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  35549. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  35550. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  35551. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  35552. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  35553. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  35554. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  35555. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  35556. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  35557. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  35558. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  35559. particleSystem.blendMode = parsedParticleSystem.blendMode;
  35560. if (!particleSystem.preventAutoStart) {
  35561. particleSystem.start();
  35562. }
  35563. return particleSystem;
  35564. };
  35565. return ParticleSystem;
  35566. }());
  35567. // Statics
  35568. ParticleSystem.BLENDMODE_ONEONE = 0;
  35569. ParticleSystem.BLENDMODE_STANDARD = 1;
  35570. BABYLON.ParticleSystem = ParticleSystem;
  35571. })(BABYLON || (BABYLON = {}));
  35572. //# sourceMappingURL=babylon.particleSystem.js.map
  35573. var BABYLON;
  35574. (function (BABYLON) {
  35575. var SolidParticle = (function () {
  35576. /**
  35577. * Creates a Solid Particle object.
  35578. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  35579. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  35580. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  35581. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  35582. * `shapeId` (integer) is the model shape identifier in the SPS.
  35583. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  35584. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  35585. */
  35586. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  35587. this.idx = 0; // particle global index
  35588. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  35589. this.position = BABYLON.Vector3.Zero(); // position
  35590. this.rotation = BABYLON.Vector3.Zero(); // rotation
  35591. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  35592. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  35593. this.velocity = BABYLON.Vector3.Zero(); // velocity
  35594. this.alive = true; // alive
  35595. this.isVisible = true; // visibility
  35596. this._pos = 0; // index of this particle in the global "positions" array
  35597. this.shapeId = 0; // model shape id
  35598. this.idxInShape = 0; // index of the particle in its shape id
  35599. this.idx = particleIndex;
  35600. this._pos = positionIndex;
  35601. this._model = model;
  35602. this.shapeId = shapeId;
  35603. this.idxInShape = idxInShape;
  35604. this._sps = sps;
  35605. if (modelBoundingInfo) {
  35606. this._modelBoundingInfo = modelBoundingInfo;
  35607. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  35608. }
  35609. }
  35610. Object.defineProperty(SolidParticle.prototype, "scale", {
  35611. /**
  35612. * legacy support, changed scale to scaling
  35613. */
  35614. get: function () {
  35615. return this.scaling;
  35616. },
  35617. set: function (scale) {
  35618. this.scaling = scale;
  35619. },
  35620. enumerable: true,
  35621. configurable: true
  35622. });
  35623. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  35624. /**
  35625. * legacy support, changed quaternion to rotationQuaternion
  35626. */
  35627. get: function () {
  35628. return this.rotationQuaternion;
  35629. },
  35630. set: function (q) {
  35631. this.rotationQuaternion = q;
  35632. },
  35633. enumerable: true,
  35634. configurable: true
  35635. });
  35636. /**
  35637. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  35638. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  35639. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  35640. */
  35641. SolidParticle.prototype.intersectsMesh = function (target) {
  35642. if (!this._boundingInfo || !target._boundingInfo) {
  35643. return false;
  35644. }
  35645. if (this._sps._bSphereOnly) {
  35646. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  35647. }
  35648. return this._boundingInfo.intersects(target._boundingInfo, false);
  35649. };
  35650. return SolidParticle;
  35651. }());
  35652. BABYLON.SolidParticle = SolidParticle;
  35653. var ModelShape = (function () {
  35654. /**
  35655. * 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.
  35656. * SPS internal tool, don't use it manually.
  35657. */
  35658. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  35659. this.shapeID = id;
  35660. this._shape = shape;
  35661. this._shapeUV = shapeUV;
  35662. this._positionFunction = posFunction;
  35663. this._vertexFunction = vtxFunction;
  35664. }
  35665. return ModelShape;
  35666. }());
  35667. BABYLON.ModelShape = ModelShape;
  35668. })(BABYLON || (BABYLON = {}));
  35669. //# sourceMappingURL=babylon.solidParticle.js.map
  35670. var BABYLON;
  35671. (function (BABYLON) {
  35672. /**
  35673. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  35674. */
  35675. var SolidParticleSystem = (function () {
  35676. /**
  35677. * Creates a SPS (Solid Particle System) object.
  35678. * `name` (String) is the SPS name, this will be the underlying mesh name.
  35679. * `scene` (Scene) is the scene in which the SPS is added.
  35680. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  35681. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  35682. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  35683. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  35684. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  35685. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  35686. */
  35687. function SolidParticleSystem(name, scene, options) {
  35688. // public members
  35689. /**
  35690. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  35691. * Example : var p = SPS.particles[i];
  35692. */
  35693. this.particles = new Array();
  35694. /**
  35695. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  35696. */
  35697. this.nbParticles = 0;
  35698. /**
  35699. * If the particles must ever face the camera (default false). Useful for planar particles.
  35700. */
  35701. this.billboard = false;
  35702. /**
  35703. * Recompute normals when adding a shape
  35704. */
  35705. this.recomputeNormals = true;
  35706. /**
  35707. * This a counter ofr your own usage. It's not set by any SPS functions.
  35708. */
  35709. this.counter = 0;
  35710. /**
  35711. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  35712. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  35713. */
  35714. this.vars = {};
  35715. this._positions = new Array();
  35716. this._indices = new Array();
  35717. this._normals = new Array();
  35718. this._colors = new Array();
  35719. this._uvs = new Array();
  35720. this._index = 0; // indices index
  35721. this._updatable = true;
  35722. this._pickable = false;
  35723. this._isVisibilityBoxLocked = false;
  35724. this._alwaysVisible = false;
  35725. this._shapeCounter = 0;
  35726. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  35727. this._color = new BABYLON.Color4(0, 0, 0, 0);
  35728. this._computeParticleColor = true;
  35729. this._computeParticleTexture = true;
  35730. this._computeParticleRotation = true;
  35731. this._computeParticleVertex = false;
  35732. this._computeBoundingBox = false;
  35733. this._cam_axisZ = BABYLON.Vector3.Zero();
  35734. this._cam_axisY = BABYLON.Vector3.Zero();
  35735. this._cam_axisX = BABYLON.Vector3.Zero();
  35736. this._axisX = BABYLON.Axis.X;
  35737. this._axisY = BABYLON.Axis.Y;
  35738. this._axisZ = BABYLON.Axis.Z;
  35739. this._camDir = BABYLON.Vector3.Zero();
  35740. this._rotMatrix = new BABYLON.Matrix();
  35741. this._invertMatrix = new BABYLON.Matrix();
  35742. this._rotated = BABYLON.Vector3.Zero();
  35743. this._quaternion = new BABYLON.Quaternion();
  35744. this._vertex = BABYLON.Vector3.Zero();
  35745. this._normal = BABYLON.Vector3.Zero();
  35746. this._yaw = 0.0;
  35747. this._pitch = 0.0;
  35748. this._roll = 0.0;
  35749. this._halfroll = 0.0;
  35750. this._halfpitch = 0.0;
  35751. this._halfyaw = 0.0;
  35752. this._sinRoll = 0.0;
  35753. this._cosRoll = 0.0;
  35754. this._sinPitch = 0.0;
  35755. this._cosPitch = 0.0;
  35756. this._sinYaw = 0.0;
  35757. this._cosYaw = 0.0;
  35758. this._w = 0.0;
  35759. this._mustUnrotateFixedNormals = false;
  35760. this._minimum = BABYLON.Tmp.Vector3[0];
  35761. this._maximum = BABYLON.Tmp.Vector3[1];
  35762. this._scale = BABYLON.Tmp.Vector3[2];
  35763. this._translation = BABYLON.Tmp.Vector3[3];
  35764. this._minBbox = BABYLON.Tmp.Vector3[4];
  35765. this._maxBbox = BABYLON.Tmp.Vector3[5];
  35766. this._particlesIntersect = false;
  35767. this._bSphereOnly = false;
  35768. this._bSphereRadiusFactor = 1.0;
  35769. this.name = name;
  35770. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35771. this._camera = scene.activeCamera;
  35772. this._pickable = options ? options.isPickable : false;
  35773. this._particlesIntersect = options ? options.particleIntersection : false;
  35774. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  35775. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  35776. if (options && options.updatable) {
  35777. this._updatable = options.updatable;
  35778. }
  35779. else {
  35780. this._updatable = true;
  35781. }
  35782. if (this._pickable) {
  35783. this.pickedParticles = [];
  35784. }
  35785. }
  35786. /**
  35787. * Builds the SPS underlying mesh. Returns a standard Mesh.
  35788. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  35789. */
  35790. SolidParticleSystem.prototype.buildMesh = function () {
  35791. if (this.nbParticles === 0) {
  35792. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  35793. this.addShape(triangle, 1);
  35794. triangle.dispose();
  35795. }
  35796. this._positions32 = new Float32Array(this._positions);
  35797. this._uvs32 = new Float32Array(this._uvs);
  35798. this._colors32 = new Float32Array(this._colors);
  35799. if (this.recomputeNormals) {
  35800. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  35801. }
  35802. this._normals32 = new Float32Array(this._normals);
  35803. this._fixedNormal32 = new Float32Array(this._normals);
  35804. if (this._mustUnrotateFixedNormals) {
  35805. this._unrotateFixedNormals();
  35806. }
  35807. var vertexData = new BABYLON.VertexData();
  35808. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  35809. vertexData.indices = this._indices;
  35810. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  35811. if (this._uvs32) {
  35812. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  35813. ;
  35814. }
  35815. if (this._colors32) {
  35816. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  35817. }
  35818. var mesh = new BABYLON.Mesh(this.name, this._scene);
  35819. vertexData.applyToMesh(mesh, this._updatable);
  35820. this.mesh = mesh;
  35821. this.mesh.isPickable = this._pickable;
  35822. // free memory
  35823. this._positions = null;
  35824. this._normals = null;
  35825. this._uvs = null;
  35826. this._colors = null;
  35827. if (!this._updatable) {
  35828. this.particles.length = 0;
  35829. }
  35830. return mesh;
  35831. };
  35832. /**
  35833. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  35834. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  35835. * Thus the particles generated from `digest()` have their property `position` set yet.
  35836. * `mesh` ( Mesh ) is the mesh to be digested
  35837. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  35838. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  35839. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  35840. */
  35841. SolidParticleSystem.prototype.digest = function (mesh, options) {
  35842. var size = (options && options.facetNb) || 1;
  35843. var number = (options && options.number);
  35844. var delta = (options && options.delta) || 0;
  35845. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35846. var meshInd = mesh.getIndices();
  35847. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35848. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35849. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35850. var f = 0; // facet counter
  35851. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  35852. // compute size from number
  35853. if (number) {
  35854. number = (number > totalFacets) ? totalFacets : number;
  35855. size = Math.round(totalFacets / number);
  35856. delta = 0;
  35857. }
  35858. else {
  35859. size = (size > totalFacets) ? totalFacets : size;
  35860. }
  35861. var facetPos = []; // submesh positions
  35862. var facetInd = []; // submesh indices
  35863. var facetUV = []; // submesh UV
  35864. var facetCol = []; // submesh colors
  35865. var barycenter = BABYLON.Tmp.Vector3[0];
  35866. var rand;
  35867. var sizeO = size;
  35868. while (f < totalFacets) {
  35869. size = sizeO + Math.floor((1 + delta) * Math.random());
  35870. if (f > totalFacets - size) {
  35871. size = totalFacets - f;
  35872. }
  35873. // reset temp arrays
  35874. facetPos.length = 0;
  35875. facetInd.length = 0;
  35876. facetUV.length = 0;
  35877. facetCol.length = 0;
  35878. // iterate over "size" facets
  35879. var fi = 0;
  35880. for (var j = f * 3; j < (f + size) * 3; j++) {
  35881. facetInd.push(fi);
  35882. var i = meshInd[j];
  35883. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  35884. if (meshUV) {
  35885. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  35886. }
  35887. if (meshCol) {
  35888. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  35889. }
  35890. fi++;
  35891. }
  35892. // create a model shape for each single particle
  35893. var idx = this.nbParticles;
  35894. var shape = this._posToShape(facetPos);
  35895. var shapeUV = this._uvsToShapeUV(facetUV);
  35896. // compute the barycenter of the shape
  35897. var v;
  35898. for (v = 0; v < shape.length; v++) {
  35899. barycenter.addInPlace(shape[v]);
  35900. }
  35901. barycenter.scaleInPlace(1 / shape.length);
  35902. // shift the shape from its barycenter to the origin
  35903. for (v = 0; v < shape.length; v++) {
  35904. shape[v].subtractInPlace(barycenter);
  35905. }
  35906. var bInfo;
  35907. if (this._particlesIntersect) {
  35908. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  35909. }
  35910. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  35911. // add the particle in the SPS
  35912. var currentPos = this._positions.length;
  35913. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  35914. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  35915. // initialize the particle position
  35916. this.particles[this.nbParticles].position.addInPlace(barycenter);
  35917. this._index += shape.length;
  35918. idx++;
  35919. this.nbParticles++;
  35920. this._shapeCounter++;
  35921. f += size;
  35922. }
  35923. return this;
  35924. };
  35925. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  35926. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  35927. var index = 0;
  35928. var idx = 0;
  35929. for (var p = 0; p < this.particles.length; p++) {
  35930. this._particle = this.particles[p];
  35931. this._shape = this._particle._model._shape;
  35932. if (this._particle.rotationQuaternion) {
  35933. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  35934. }
  35935. else {
  35936. this._yaw = this._particle.rotation.y;
  35937. this._pitch = this._particle.rotation.x;
  35938. this._roll = this._particle.rotation.z;
  35939. this._quaternionRotationYPR();
  35940. }
  35941. this._quaternionToRotationMatrix();
  35942. this._rotMatrix.invertToRef(this._invertMatrix);
  35943. for (var pt = 0; pt < this._shape.length; pt++) {
  35944. idx = index + pt * 3;
  35945. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  35946. this._fixedNormal32[idx] = this._normal.x;
  35947. this._fixedNormal32[idx + 1] = this._normal.y;
  35948. this._fixedNormal32[idx + 2] = this._normal.z;
  35949. }
  35950. index = idx + 3;
  35951. }
  35952. };
  35953. //reset copy
  35954. SolidParticleSystem.prototype._resetCopy = function () {
  35955. this._copy.position.x = 0;
  35956. this._copy.position.y = 0;
  35957. this._copy.position.z = 0;
  35958. this._copy.rotation.x = 0;
  35959. this._copy.rotation.y = 0;
  35960. this._copy.rotation.z = 0;
  35961. this._copy.rotationQuaternion = null;
  35962. this._copy.scaling.x = 1;
  35963. this._copy.scaling.y = 1;
  35964. this._copy.scaling.z = 1;
  35965. this._copy.uvs.x = 0;
  35966. this._copy.uvs.y = 0;
  35967. this._copy.uvs.z = 1;
  35968. this._copy.uvs.w = 1;
  35969. this._copy.color = null;
  35970. };
  35971. // _meshBuilder : inserts the shape model in the global SPS mesh
  35972. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  35973. var i;
  35974. var u = 0;
  35975. var c = 0;
  35976. var n = 0;
  35977. this._resetCopy();
  35978. if (options && options.positionFunction) {
  35979. options.positionFunction(this._copy, idx, idxInShape);
  35980. this._mustUnrotateFixedNormals = true;
  35981. }
  35982. if (this._copy.rotationQuaternion) {
  35983. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  35984. }
  35985. else {
  35986. this._yaw = this._copy.rotation.y;
  35987. this._pitch = this._copy.rotation.x;
  35988. this._roll = this._copy.rotation.z;
  35989. this._quaternionRotationYPR();
  35990. }
  35991. this._quaternionToRotationMatrix();
  35992. for (i = 0; i < shape.length; i++) {
  35993. this._vertex.x = shape[i].x;
  35994. this._vertex.y = shape[i].y;
  35995. this._vertex.z = shape[i].z;
  35996. if (options && options.vertexFunction) {
  35997. options.vertexFunction(this._copy, this._vertex, i);
  35998. }
  35999. this._vertex.x *= this._copy.scaling.x;
  36000. this._vertex.y *= this._copy.scaling.y;
  36001. this._vertex.z *= this._copy.scaling.z;
  36002. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36003. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36004. if (meshUV) {
  36005. 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);
  36006. u += 2;
  36007. }
  36008. if (this._copy.color) {
  36009. this._color = this._copy.color;
  36010. }
  36011. else if (meshCol && meshCol[c] !== undefined) {
  36012. this._color.r = meshCol[c];
  36013. this._color.g = meshCol[c + 1];
  36014. this._color.b = meshCol[c + 2];
  36015. this._color.a = meshCol[c + 3];
  36016. }
  36017. else {
  36018. this._color.r = 1;
  36019. this._color.g = 1;
  36020. this._color.b = 1;
  36021. this._color.a = 1;
  36022. }
  36023. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36024. c += 4;
  36025. if (!this.recomputeNormals && meshNor) {
  36026. this._normal.x = meshNor[n];
  36027. this._normal.y = meshNor[n + 1];
  36028. this._normal.z = meshNor[n + 2];
  36029. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  36030. normals.push(this._normal.x, this._normal.y, this._normal.z);
  36031. n += 3;
  36032. }
  36033. }
  36034. for (i = 0; i < meshInd.length; i++) {
  36035. indices.push(p + meshInd[i]);
  36036. }
  36037. if (this._pickable) {
  36038. var nbfaces = meshInd.length / 3;
  36039. for (i = 0; i < nbfaces; i++) {
  36040. this.pickedParticles.push({ idx: idx, faceId: i });
  36041. }
  36042. }
  36043. return this._copy;
  36044. };
  36045. // returns a shape array from positions array
  36046. SolidParticleSystem.prototype._posToShape = function (positions) {
  36047. var shape = [];
  36048. for (var i = 0; i < positions.length; i += 3) {
  36049. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36050. }
  36051. return shape;
  36052. };
  36053. // returns a shapeUV array from a Vector4 uvs
  36054. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36055. var shapeUV = [];
  36056. if (uvs) {
  36057. for (var i = 0; i < uvs.length; i++)
  36058. shapeUV.push(uvs[i]);
  36059. }
  36060. return shapeUV;
  36061. };
  36062. // adds a new particle object in the particles array
  36063. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  36064. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  36065. this.particles.push(sp);
  36066. return sp;
  36067. };
  36068. /**
  36069. * Adds some particles to the SPS from the model shape. Returns the shape id.
  36070. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  36071. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  36072. * `nb` (positive integer) the number of particles to be created from this model
  36073. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  36074. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  36075. */
  36076. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36077. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36078. var meshInd = mesh.getIndices();
  36079. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36080. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36081. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36082. var bbInfo;
  36083. if (this._particlesIntersect) {
  36084. bbInfo = mesh.getBoundingInfo();
  36085. }
  36086. var shape = this._posToShape(meshPos);
  36087. var shapeUV = this._uvsToShapeUV(meshUV);
  36088. var posfunc = options ? options.positionFunction : null;
  36089. var vtxfunc = options ? options.vertexFunction : null;
  36090. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36091. // particles
  36092. var sp;
  36093. var currentCopy;
  36094. var idx = this.nbParticles;
  36095. for (var i = 0; i < nb; i++) {
  36096. var currentPos = this._positions.length;
  36097. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  36098. if (this._updatable) {
  36099. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  36100. sp.position.copyFrom(currentCopy.position);
  36101. sp.rotation.copyFrom(currentCopy.rotation);
  36102. if (currentCopy.rotationQuaternion) {
  36103. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  36104. }
  36105. if (currentCopy.color) {
  36106. sp.color.copyFrom(currentCopy.color);
  36107. }
  36108. sp.scaling.copyFrom(currentCopy.scaling);
  36109. sp.uvs.copyFrom(currentCopy.uvs);
  36110. }
  36111. this._index += shape.length;
  36112. idx++;
  36113. }
  36114. this.nbParticles += nb;
  36115. this._shapeCounter++;
  36116. return this._shapeCounter - 1;
  36117. };
  36118. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36119. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36120. this._resetCopy();
  36121. if (particle._model._positionFunction) {
  36122. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36123. }
  36124. if (this._copy.rotationQuaternion) {
  36125. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  36126. }
  36127. else {
  36128. this._yaw = this._copy.rotation.y;
  36129. this._pitch = this._copy.rotation.x;
  36130. this._roll = this._copy.rotation.z;
  36131. this._quaternionRotationYPR();
  36132. }
  36133. this._quaternionToRotationMatrix();
  36134. this._shape = particle._model._shape;
  36135. for (var pt = 0; pt < this._shape.length; pt++) {
  36136. this._vertex.x = this._shape[pt].x;
  36137. this._vertex.y = this._shape[pt].y;
  36138. this._vertex.z = this._shape[pt].z;
  36139. if (particle._model._vertexFunction) {
  36140. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36141. }
  36142. this._vertex.x *= this._copy.scaling.x;
  36143. this._vertex.y *= this._copy.scaling.y;
  36144. this._vertex.z *= this._copy.scaling.z;
  36145. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36146. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36147. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36148. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36149. }
  36150. particle.position.x = 0.0;
  36151. particle.position.y = 0.0;
  36152. particle.position.z = 0.0;
  36153. particle.rotation.x = 0.0;
  36154. particle.rotation.y = 0.0;
  36155. particle.rotation.z = 0.0;
  36156. particle.rotationQuaternion = null;
  36157. particle.scaling.x = 1.0;
  36158. particle.scaling.y = 1.0;
  36159. particle.scaling.z = 1.0;
  36160. };
  36161. /**
  36162. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  36163. * Returns the SPS.
  36164. */
  36165. SolidParticleSystem.prototype.rebuildMesh = function () {
  36166. for (var p = 0; p < this.particles.length; p++) {
  36167. this._rebuildParticle(this.particles[p]);
  36168. }
  36169. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36170. return this;
  36171. };
  36172. /**
  36173. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  36174. * This method calls `updateParticle()` for each particle of the SPS.
  36175. * For an animated SPS, it is usually called within the render loop.
  36176. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  36177. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  36178. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  36179. * Returns the SPS.
  36180. */
  36181. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36182. if (start === void 0) { start = 0; }
  36183. if (end === void 0) { end = this.nbParticles - 1; }
  36184. if (update === void 0) { update = true; }
  36185. if (!this._updatable) {
  36186. return;
  36187. }
  36188. // custom beforeUpdate
  36189. this.beforeUpdateParticles(start, end, update);
  36190. this._cam_axisX.x = 1.0;
  36191. this._cam_axisX.y = 0.0;
  36192. this._cam_axisX.z = 0.0;
  36193. this._cam_axisY.x = 0.0;
  36194. this._cam_axisY.y = 1.0;
  36195. this._cam_axisY.z = 0.0;
  36196. this._cam_axisZ.x = 0.0;
  36197. this._cam_axisZ.y = 0.0;
  36198. this._cam_axisZ.z = 1.0;
  36199. // if the particles will always face the camera
  36200. if (this.billboard) {
  36201. this.mesh.computeWorldMatrix(true);
  36202. // compute the camera position and un-rotate it by the current mesh rotation
  36203. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  36204. this._quaternionToRotationMatrix();
  36205. this._rotMatrix.invertToRef(this._invertMatrix);
  36206. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  36207. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  36208. this._cam_axisZ.normalize();
  36209. // same for camera up vector extracted from the cam view matrix
  36210. var view = this._camera.getViewMatrix(true);
  36211. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  36212. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  36213. this._cam_axisY.normalize();
  36214. this._cam_axisX.normalize();
  36215. }
  36216. }
  36217. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36218. var idx = 0; // current position index in the global array positions32
  36219. var index = 0; // position start index in the global array positions32 of the current particle
  36220. var colidx = 0; // current color index in the global array colors32
  36221. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  36222. var uvidx = 0; // current uv index in the global array uvs32
  36223. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  36224. var pt = 0; // current index in the particle model shape
  36225. if (this.mesh.isFacetDataEnabled) {
  36226. this._computeBoundingBox = true;
  36227. }
  36228. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  36229. if (this._computeBoundingBox) {
  36230. if (start == 0 && end == this.nbParticles - 1) {
  36231. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  36232. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  36233. }
  36234. else {
  36235. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  36236. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  36237. }
  36238. }
  36239. // particle loop
  36240. index = this.particles[start]._pos;
  36241. var vpos = (index / 3) | 0;
  36242. colorIndex = vpos * 4;
  36243. uvIndex = vpos * 2;
  36244. for (var p = start; p <= end; p++) {
  36245. this._particle = this.particles[p];
  36246. this._shape = this._particle._model._shape;
  36247. this._shapeUV = this._particle._model._shapeUV;
  36248. // call to custom user function to update the particle properties
  36249. this.updateParticle(this._particle);
  36250. if (this._particle.isVisible) {
  36251. // particle rotation matrix
  36252. if (this.billboard) {
  36253. this._particle.rotation.x = 0.0;
  36254. this._particle.rotation.y = 0.0;
  36255. }
  36256. if (this._computeParticleRotation || this.billboard) {
  36257. if (this._particle.rotationQuaternion) {
  36258. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  36259. }
  36260. else {
  36261. this._yaw = this._particle.rotation.y;
  36262. this._pitch = this._particle.rotation.x;
  36263. this._roll = this._particle.rotation.z;
  36264. this._quaternionRotationYPR();
  36265. }
  36266. this._quaternionToRotationMatrix();
  36267. }
  36268. // particle vertex loop
  36269. for (pt = 0; pt < this._shape.length; pt++) {
  36270. idx = index + pt * 3;
  36271. colidx = colorIndex + pt * 4;
  36272. uvidx = uvIndex + pt * 2;
  36273. this._vertex.x = this._shape[pt].x;
  36274. this._vertex.y = this._shape[pt].y;
  36275. this._vertex.z = this._shape[pt].z;
  36276. if (this._computeParticleVertex) {
  36277. this.updateParticleVertex(this._particle, this._vertex, pt);
  36278. }
  36279. // positions
  36280. this._vertex.x *= this._particle.scaling.x;
  36281. this._vertex.y *= this._particle.scaling.y;
  36282. this._vertex.z *= this._particle.scaling.z;
  36283. 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];
  36284. 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;
  36285. 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;
  36286. 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;
  36287. 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;
  36288. 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;
  36289. 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;
  36290. if (this._computeBoundingBox) {
  36291. if (this._positions32[idx] < this._minimum.x) {
  36292. this._minimum.x = this._positions32[idx];
  36293. }
  36294. if (this._positions32[idx] > this._maximum.x) {
  36295. this._maximum.x = this._positions32[idx];
  36296. }
  36297. if (this._positions32[idx + 1] < this._minimum.y) {
  36298. this._minimum.y = this._positions32[idx + 1];
  36299. }
  36300. if (this._positions32[idx + 1] > this._maximum.y) {
  36301. this._maximum.y = this._positions32[idx + 1];
  36302. }
  36303. if (this._positions32[idx + 2] < this._minimum.z) {
  36304. this._minimum.z = this._positions32[idx + 2];
  36305. }
  36306. if (this._positions32[idx + 2] > this._maximum.z) {
  36307. this._maximum.z = this._positions32[idx + 2];
  36308. }
  36309. }
  36310. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  36311. if (!this._computeParticleVertex) {
  36312. this._normal.x = this._fixedNormal32[idx];
  36313. this._normal.y = this._fixedNormal32[idx + 1];
  36314. this._normal.z = this._fixedNormal32[idx + 2];
  36315. 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]);
  36316. 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]);
  36317. 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]);
  36318. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  36319. 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;
  36320. 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;
  36321. }
  36322. if (this._computeParticleColor) {
  36323. this._colors32[colidx] = this._particle.color.r;
  36324. this._colors32[colidx + 1] = this._particle.color.g;
  36325. this._colors32[colidx + 2] = this._particle.color.b;
  36326. this._colors32[colidx + 3] = this._particle.color.a;
  36327. }
  36328. if (this._computeParticleTexture) {
  36329. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36330. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36331. }
  36332. }
  36333. }
  36334. else {
  36335. for (pt = 0; pt < this._shape.length; pt++) {
  36336. idx = index + pt * 3;
  36337. colidx = colorIndex + pt * 4;
  36338. uvidx = uvIndex + pt * 2;
  36339. this._positions32[idx] = this._camera.position.x;
  36340. this._positions32[idx + 1] = this._camera.position.y;
  36341. this._positions32[idx + 2] = this._camera.position.z;
  36342. this._normals32[idx] = 0.0;
  36343. this._normals32[idx + 1] = 0.0;
  36344. this._normals32[idx + 2] = 0.0;
  36345. if (this._computeParticleColor) {
  36346. this._colors32[colidx] = this._particle.color.r;
  36347. this._colors32[colidx + 1] = this._particle.color.g;
  36348. this._colors32[colidx + 2] = this._particle.color.b;
  36349. this._colors32[colidx + 3] = this._particle.color.a;
  36350. }
  36351. if (this._computeParticleTexture) {
  36352. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36353. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36354. }
  36355. }
  36356. }
  36357. // if the particle intersections must be computed : update the bbInfo
  36358. if (this._particlesIntersect) {
  36359. var bInfo = this._particle._boundingInfo;
  36360. var bBox = bInfo.boundingBox;
  36361. var bSphere = bInfo.boundingSphere;
  36362. if (!this._bSphereOnly) {
  36363. // place, scale and rotate the particle bbox within the SPS local system, then update it
  36364. for (var b = 0; b < bBox.vectors.length; b++) {
  36365. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  36366. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  36367. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  36368. 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];
  36369. 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;
  36370. 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;
  36371. 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;
  36372. 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;
  36373. 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;
  36374. 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;
  36375. }
  36376. bBox._update(this.mesh._worldMatrix);
  36377. }
  36378. // place and scale the particle bouding sphere in the SPS local system, then update it
  36379. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  36380. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  36381. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  36382. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  36383. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  36384. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  36385. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  36386. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  36387. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  36388. 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));
  36389. bSphere._update(this.mesh._worldMatrix);
  36390. }
  36391. // increment indexes for the next particle
  36392. index = idx + 3;
  36393. colorIndex = colidx + 4;
  36394. uvIndex = uvidx + 2;
  36395. }
  36396. // if the VBO must be updated
  36397. if (update) {
  36398. if (this._computeParticleColor) {
  36399. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  36400. }
  36401. if (this._computeParticleTexture) {
  36402. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  36403. }
  36404. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36405. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  36406. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  36407. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  36408. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  36409. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  36410. for (var i = 0; i < this._normals32.length; i++) {
  36411. this._fixedNormal32[i] = this._normals32[i];
  36412. }
  36413. }
  36414. if (!this.mesh.areNormalsFrozen) {
  36415. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  36416. }
  36417. }
  36418. }
  36419. if (this._computeBoundingBox) {
  36420. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  36421. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  36422. }
  36423. this.afterUpdateParticles(start, end, update);
  36424. return this;
  36425. };
  36426. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  36427. this._halfroll = this._roll * 0.5;
  36428. this._halfpitch = this._pitch * 0.5;
  36429. this._halfyaw = this._yaw * 0.5;
  36430. this._sinRoll = Math.sin(this._halfroll);
  36431. this._cosRoll = Math.cos(this._halfroll);
  36432. this._sinPitch = Math.sin(this._halfpitch);
  36433. this._cosPitch = Math.cos(this._halfpitch);
  36434. this._sinYaw = Math.sin(this._halfyaw);
  36435. this._cosYaw = Math.cos(this._halfyaw);
  36436. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  36437. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  36438. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  36439. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  36440. };
  36441. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  36442. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  36443. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  36444. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  36445. this._rotMatrix.m[3] = 0;
  36446. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  36447. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  36448. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  36449. this._rotMatrix.m[7] = 0;
  36450. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  36451. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  36452. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  36453. this._rotMatrix.m[11] = 0;
  36454. this._rotMatrix.m[12] = 0;
  36455. this._rotMatrix.m[13] = 0;
  36456. this._rotMatrix.m[14] = 0;
  36457. this._rotMatrix.m[15] = 1.0;
  36458. };
  36459. /**
  36460. * Disposes the SPS.
  36461. * Returns nothing.
  36462. */
  36463. SolidParticleSystem.prototype.dispose = function () {
  36464. this.mesh.dispose();
  36465. this.vars = null;
  36466. // drop references to internal big arrays for the GC
  36467. this._positions = null;
  36468. this._indices = null;
  36469. this._normals = null;
  36470. this._uvs = null;
  36471. this._colors = null;
  36472. this._positions32 = null;
  36473. this._normals32 = null;
  36474. this._fixedNormal32 = null;
  36475. this._uvs32 = null;
  36476. this._colors32 = null;
  36477. this.pickedParticles = null;
  36478. };
  36479. /**
  36480. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  36481. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  36482. * Returns the SPS.
  36483. */
  36484. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  36485. if (!this._isVisibilityBoxLocked) {
  36486. this.mesh.refreshBoundingInfo();
  36487. }
  36488. return this;
  36489. };
  36490. /**
  36491. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  36492. * @param size the size (float) of the visibility box
  36493. * note : this doesn't lock the SPS mesh bounding box.
  36494. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  36495. */
  36496. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  36497. var vis = size / 2;
  36498. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  36499. };
  36500. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  36501. // getter and setter
  36502. get: function () {
  36503. return this._alwaysVisible;
  36504. },
  36505. /**
  36506. * Sets the SPS as always visible or not
  36507. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  36508. */
  36509. set: function (val) {
  36510. this._alwaysVisible = val;
  36511. this.mesh.alwaysSelectAsActiveMesh = val;
  36512. },
  36513. enumerable: true,
  36514. configurable: true
  36515. });
  36516. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  36517. get: function () {
  36518. return this._isVisibilityBoxLocked;
  36519. },
  36520. /**
  36521. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  36522. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  36523. */
  36524. set: function (val) {
  36525. this._isVisibilityBoxLocked = val;
  36526. this.mesh.getBoundingInfo().isLocked = val;
  36527. },
  36528. enumerable: true,
  36529. configurable: true
  36530. });
  36531. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  36532. // getters
  36533. get: function () {
  36534. return this._computeParticleRotation;
  36535. },
  36536. // Optimizer setters
  36537. /**
  36538. * Tells to `setParticles()` to compute the particle rotations or not.
  36539. * Default value : true. The SPS is faster when it's set to false.
  36540. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  36541. */
  36542. set: function (val) {
  36543. this._computeParticleRotation = val;
  36544. },
  36545. enumerable: true,
  36546. configurable: true
  36547. });
  36548. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  36549. get: function () {
  36550. return this._computeParticleColor;
  36551. },
  36552. /**
  36553. * Tells to `setParticles()` to compute the particle colors or not.
  36554. * Default value : true. The SPS is faster when it's set to false.
  36555. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  36556. */
  36557. set: function (val) {
  36558. this._computeParticleColor = val;
  36559. },
  36560. enumerable: true,
  36561. configurable: true
  36562. });
  36563. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  36564. get: function () {
  36565. return this._computeParticleTexture;
  36566. },
  36567. /**
  36568. * Tells to `setParticles()` to compute the particle textures or not.
  36569. * Default value : true. The SPS is faster when it's set to false.
  36570. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  36571. */
  36572. set: function (val) {
  36573. this._computeParticleTexture = val;
  36574. },
  36575. enumerable: true,
  36576. configurable: true
  36577. });
  36578. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  36579. get: function () {
  36580. return this._computeParticleVertex;
  36581. },
  36582. /**
  36583. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  36584. * Default value : false. The SPS is faster when it's set to false.
  36585. * Note : the particle custom vertex positions aren't stored values.
  36586. */
  36587. set: function (val) {
  36588. this._computeParticleVertex = val;
  36589. },
  36590. enumerable: true,
  36591. configurable: true
  36592. });
  36593. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  36594. get: function () {
  36595. return this._computeBoundingBox;
  36596. },
  36597. /**
  36598. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  36599. */
  36600. set: function (val) {
  36601. this._computeBoundingBox = val;
  36602. },
  36603. enumerable: true,
  36604. configurable: true
  36605. });
  36606. // =======================================================================
  36607. // Particle behavior logic
  36608. // these following methods may be overwritten by the user to fit his needs
  36609. /**
  36610. * This function does nothing. It may be overwritten to set all the particle first values.
  36611. * The SPS doesn't call this function, you may have to call it by your own.
  36612. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  36613. */
  36614. SolidParticleSystem.prototype.initParticles = function () {
  36615. };
  36616. /**
  36617. * This function does nothing. It may be overwritten to recycle a particle.
  36618. * The SPS doesn't call this function, you may have to call it by your own.
  36619. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  36620. */
  36621. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  36622. return particle;
  36623. };
  36624. /**
  36625. * Updates a particle : this function should be overwritten by the user.
  36626. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  36627. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  36628. * ex : just set a particle position or velocity and recycle conditions
  36629. */
  36630. SolidParticleSystem.prototype.updateParticle = function (particle) {
  36631. return particle;
  36632. };
  36633. /**
  36634. * Updates a vertex of a particle : it can be overwritten by the user.
  36635. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  36636. * @param particle the current particle
  36637. * @param vertex the current index of the current particle
  36638. * @param pt the index of the current vertex in the particle shape
  36639. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  36640. * ex : just set a vertex particle position
  36641. */
  36642. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  36643. return vertex;
  36644. };
  36645. /**
  36646. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  36647. * This does nothing and may be overwritten by the user.
  36648. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  36649. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  36650. * @param update the boolean update value actually passed to setParticles()
  36651. */
  36652. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  36653. };
  36654. /**
  36655. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  36656. * This will be passed three parameters.
  36657. * This does nothing and may be overwritten by the user.
  36658. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  36659. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  36660. * @param update the boolean update value actually passed to setParticles()
  36661. */
  36662. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  36663. };
  36664. return SolidParticleSystem;
  36665. }());
  36666. BABYLON.SolidParticleSystem = SolidParticleSystem;
  36667. })(BABYLON || (BABYLON = {}));
  36668. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  36669. /// <reference path="babylon.mesh.ts" />
  36670. var BABYLON;
  36671. (function (BABYLON) {
  36672. var GroundMesh = (function (_super) {
  36673. __extends(GroundMesh, _super);
  36674. function GroundMesh(name, scene) {
  36675. var _this = _super.call(this, name, scene) || this;
  36676. _this.generateOctree = false;
  36677. _this._worldInverse = new BABYLON.Matrix();
  36678. return _this;
  36679. }
  36680. GroundMesh.prototype.getClassName = function () {
  36681. return "GroundMesh";
  36682. };
  36683. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  36684. get: function () {
  36685. return Math.min(this._subdivisionsX, this._subdivisionsY);
  36686. },
  36687. enumerable: true,
  36688. configurable: true
  36689. });
  36690. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  36691. get: function () {
  36692. return this._subdivisionsX;
  36693. },
  36694. enumerable: true,
  36695. configurable: true
  36696. });
  36697. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  36698. get: function () {
  36699. return this._subdivisionsY;
  36700. },
  36701. enumerable: true,
  36702. configurable: true
  36703. });
  36704. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  36705. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  36706. this._subdivisionsX = chunksCount;
  36707. this._subdivisionsY = chunksCount;
  36708. this.subdivide(chunksCount);
  36709. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  36710. };
  36711. /**
  36712. * Returns a height (y) value in the Worl system :
  36713. * the ground altitude at the coordinates (x, z) expressed in the World system.
  36714. * Returns the ground y position if (x, z) are outside the ground surface.
  36715. */
  36716. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  36717. var world = this.getWorldMatrix();
  36718. var invMat = BABYLON.Tmp.Matrix[5];
  36719. world.invertToRef(invMat);
  36720. var tmpVect = BABYLON.Tmp.Vector3[8];
  36721. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  36722. x = tmpVect.x;
  36723. z = tmpVect.z;
  36724. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  36725. return this.position.y;
  36726. }
  36727. if (!this._heightQuads || this._heightQuads.length == 0) {
  36728. this._initHeightQuads();
  36729. this._computeHeightQuads();
  36730. }
  36731. var facet = this._getFacetAt(x, z);
  36732. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  36733. // return y in the World system
  36734. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  36735. return tmpVect.y;
  36736. };
  36737. /**
  36738. * Returns a normalized vector (Vector3) orthogonal to the ground
  36739. * at the ground coordinates (x, z) expressed in the World system.
  36740. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  36741. */
  36742. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  36743. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  36744. this.getNormalAtCoordinatesToRef(x, z, normal);
  36745. return normal;
  36746. };
  36747. /**
  36748. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  36749. * at the ground coordinates (x, z) expressed in the World system.
  36750. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  36751. * Returns the GroundMesh.
  36752. */
  36753. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  36754. var world = this.getWorldMatrix();
  36755. var tmpMat = BABYLON.Tmp.Matrix[5];
  36756. world.invertToRef(tmpMat);
  36757. var tmpVect = BABYLON.Tmp.Vector3[8];
  36758. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  36759. x = tmpVect.x;
  36760. z = tmpVect.z;
  36761. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  36762. return this;
  36763. }
  36764. if (!this._heightQuads || this._heightQuads.length == 0) {
  36765. this._initHeightQuads();
  36766. this._computeHeightQuads();
  36767. }
  36768. var facet = this._getFacetAt(x, z);
  36769. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  36770. return this;
  36771. };
  36772. /**
  36773. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  36774. * if the ground has been updated.
  36775. * This can be used in the render loop.
  36776. * Returns the GroundMesh.
  36777. */
  36778. GroundMesh.prototype.updateCoordinateHeights = function () {
  36779. if (!this._heightQuads || this._heightQuads.length == 0) {
  36780. this._initHeightQuads();
  36781. }
  36782. this._computeHeightQuads();
  36783. return this;
  36784. };
  36785. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  36786. GroundMesh.prototype._getFacetAt = function (x, z) {
  36787. // retrieve col and row from x, z coordinates in the ground local system
  36788. var subdivisionsX = this._subdivisionsX;
  36789. var subdivisionsY = this._subdivisionsY;
  36790. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  36791. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  36792. var quad = this._heightQuads[row * this._subdivisionsX + col];
  36793. var facet;
  36794. if (z < quad.slope.x * x + quad.slope.y) {
  36795. facet = quad.facet1;
  36796. }
  36797. else {
  36798. facet = quad.facet2;
  36799. }
  36800. return facet;
  36801. };
  36802. // Creates and populates the heightMap array with "facet" elements :
  36803. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  36804. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  36805. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  36806. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  36807. // Returns the GroundMesh.
  36808. GroundMesh.prototype._initHeightQuads = function () {
  36809. var subdivisionsX = this._subdivisionsX;
  36810. var subdivisionsY = this._subdivisionsY;
  36811. this._heightQuads = new Array();
  36812. for (var row = 0; row < subdivisionsY; row++) {
  36813. for (var col = 0; col < subdivisionsX; col++) {
  36814. 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) };
  36815. this._heightQuads[row * subdivisionsX + col] = quad;
  36816. }
  36817. }
  36818. return this;
  36819. };
  36820. // Compute each quad element values and update the the heightMap array :
  36821. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  36822. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  36823. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  36824. // Returns the GroundMesh.
  36825. GroundMesh.prototype._computeHeightQuads = function () {
  36826. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36827. var v1 = BABYLON.Tmp.Vector3[3];
  36828. var v2 = BABYLON.Tmp.Vector3[2];
  36829. var v3 = BABYLON.Tmp.Vector3[1];
  36830. var v4 = BABYLON.Tmp.Vector3[0];
  36831. var v1v2 = BABYLON.Tmp.Vector3[4];
  36832. var v1v3 = BABYLON.Tmp.Vector3[5];
  36833. var v1v4 = BABYLON.Tmp.Vector3[6];
  36834. var norm1 = BABYLON.Tmp.Vector3[7];
  36835. var norm2 = BABYLON.Tmp.Vector3[8];
  36836. var i = 0;
  36837. var j = 0;
  36838. var k = 0;
  36839. var cd = 0; // 2D slope coefficient : z = cd * x + h
  36840. var h = 0;
  36841. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  36842. var d2 = 0;
  36843. var subdivisionsX = this._subdivisionsX;
  36844. var subdivisionsY = this._subdivisionsY;
  36845. for (var row = 0; row < subdivisionsY; row++) {
  36846. for (var col = 0; col < subdivisionsX; col++) {
  36847. i = col * 3;
  36848. j = row * (subdivisionsX + 1) * 3;
  36849. k = (row + 1) * (subdivisionsX + 1) * 3;
  36850. v1.x = positions[j + i];
  36851. v1.y = positions[j + i + 1];
  36852. v1.z = positions[j + i + 2];
  36853. v2.x = positions[j + i + 3];
  36854. v2.y = positions[j + i + 4];
  36855. v2.z = positions[j + i + 5];
  36856. v3.x = positions[k + i];
  36857. v3.y = positions[k + i + 1];
  36858. v3.z = positions[k + i + 2];
  36859. v4.x = positions[k + i + 3];
  36860. v4.y = positions[k + i + 4];
  36861. v4.z = positions[k + i + 5];
  36862. // 2D slope V1V4
  36863. cd = (v4.z - v1.z) / (v4.x - v1.x);
  36864. h = v1.z - cd * v1.x; // v1 belongs to the slope
  36865. // facet equations :
  36866. // we compute each facet normal vector
  36867. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  36868. // we compute the value d by applying the equation to v1 which belongs to the plane
  36869. // then we store the facet equation in a Vector4
  36870. v2.subtractToRef(v1, v1v2);
  36871. v3.subtractToRef(v1, v1v3);
  36872. v4.subtractToRef(v1, v1v4);
  36873. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  36874. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  36875. norm1.normalize();
  36876. norm2.normalize();
  36877. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  36878. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  36879. var quad = this._heightQuads[row * subdivisionsX + col];
  36880. quad.slope.copyFromFloats(cd, h);
  36881. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  36882. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  36883. }
  36884. }
  36885. return this;
  36886. };
  36887. GroundMesh.prototype.serialize = function (serializationObject) {
  36888. _super.prototype.serialize.call(this, serializationObject);
  36889. serializationObject.subdivisionsX = this._subdivisionsX;
  36890. serializationObject.subdivisionsY = this._subdivisionsY;
  36891. serializationObject.minX = this._minX;
  36892. serializationObject.maxX = this._maxX;
  36893. serializationObject.minZ = this._minZ;
  36894. serializationObject.maxZ = this._maxZ;
  36895. serializationObject.width = this._width;
  36896. serializationObject.height = this._height;
  36897. };
  36898. GroundMesh.Parse = function (parsedMesh, scene) {
  36899. var result = new GroundMesh(parsedMesh.name, scene);
  36900. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  36901. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  36902. result._minX = parsedMesh.minX;
  36903. result._maxX = parsedMesh.maxX;
  36904. result._minZ = parsedMesh.minZ;
  36905. result._maxZ = parsedMesh.maxZ;
  36906. result._width = parsedMesh.width;
  36907. result._height = parsedMesh.height;
  36908. return result;
  36909. };
  36910. return GroundMesh;
  36911. }(BABYLON.Mesh));
  36912. BABYLON.GroundMesh = GroundMesh;
  36913. })(BABYLON || (BABYLON = {}));
  36914. //# sourceMappingURL=babylon.groundMesh.js.map
  36915. var BABYLON;
  36916. (function (BABYLON) {
  36917. /**
  36918. * Creates an instance based on a source mesh.
  36919. */
  36920. var InstancedMesh = (function (_super) {
  36921. __extends(InstancedMesh, _super);
  36922. function InstancedMesh(name, source) {
  36923. var _this = _super.call(this, name, source.getScene()) || this;
  36924. source.instances.push(_this);
  36925. _this._sourceMesh = source;
  36926. _this.position.copyFrom(source.position);
  36927. _this.rotation.copyFrom(source.rotation);
  36928. _this.scaling.copyFrom(source.scaling);
  36929. if (source.rotationQuaternion) {
  36930. _this.rotationQuaternion = source.rotationQuaternion.clone();
  36931. }
  36932. _this.infiniteDistance = source.infiniteDistance;
  36933. _this.setPivotMatrix(source.getPivotMatrix());
  36934. _this.refreshBoundingInfo();
  36935. _this._syncSubMeshes();
  36936. return _this;
  36937. }
  36938. /**
  36939. * Returns the string "InstancedMesh".
  36940. */
  36941. InstancedMesh.prototype.getClassName = function () {
  36942. return "InstancedMesh";
  36943. };
  36944. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  36945. // Methods
  36946. get: function () {
  36947. return this._sourceMesh.receiveShadows;
  36948. },
  36949. enumerable: true,
  36950. configurable: true
  36951. });
  36952. Object.defineProperty(InstancedMesh.prototype, "material", {
  36953. get: function () {
  36954. return this._sourceMesh.material;
  36955. },
  36956. enumerable: true,
  36957. configurable: true
  36958. });
  36959. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  36960. get: function () {
  36961. return this._sourceMesh.visibility;
  36962. },
  36963. enumerable: true,
  36964. configurable: true
  36965. });
  36966. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  36967. get: function () {
  36968. return this._sourceMesh.skeleton;
  36969. },
  36970. enumerable: true,
  36971. configurable: true
  36972. });
  36973. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  36974. get: function () {
  36975. return this._sourceMesh.renderingGroupId;
  36976. },
  36977. enumerable: true,
  36978. configurable: true
  36979. });
  36980. /**
  36981. * Returns the total number of vertices (integer).
  36982. */
  36983. InstancedMesh.prototype.getTotalVertices = function () {
  36984. return this._sourceMesh.getTotalVertices();
  36985. };
  36986. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  36987. get: function () {
  36988. return this._sourceMesh;
  36989. },
  36990. enumerable: true,
  36991. configurable: true
  36992. });
  36993. /**
  36994. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  36995. */
  36996. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  36997. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  36998. };
  36999. /**
  37000. * Sets the vertex data of the mesh geometry for the requested `kind`.
  37001. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  37002. * The `data` are either a numeric array either a Float32Array.
  37003. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  37004. * 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).
  37005. * Note that a new underlying VertexBuffer object is created each call.
  37006. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  37007. *
  37008. * Possible `kind` values :
  37009. * - BABYLON.VertexBuffer.PositionKind
  37010. * - BABYLON.VertexBuffer.UVKind
  37011. * - BABYLON.VertexBuffer.UV2Kind
  37012. * - BABYLON.VertexBuffer.UV3Kind
  37013. * - BABYLON.VertexBuffer.UV4Kind
  37014. * - BABYLON.VertexBuffer.UV5Kind
  37015. * - BABYLON.VertexBuffer.UV6Kind
  37016. * - BABYLON.VertexBuffer.ColorKind
  37017. * - BABYLON.VertexBuffer.MatricesIndicesKind
  37018. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  37019. * - BABYLON.VertexBuffer.MatricesWeightsKind
  37020. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  37021. *
  37022. * Returns the Mesh.
  37023. */
  37024. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  37025. if (this.sourceMesh) {
  37026. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  37027. }
  37028. return this.sourceMesh;
  37029. };
  37030. /**
  37031. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  37032. * If the mesh has no geometry, it is simply returned as it is.
  37033. * The `data` are either a numeric array either a Float32Array.
  37034. * No new underlying VertexBuffer object is created.
  37035. * 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.
  37036. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  37037. *
  37038. * Possible `kind` values :
  37039. * - BABYLON.VertexBuffer.PositionKind
  37040. * - BABYLON.VertexBuffer.UVKind
  37041. * - BABYLON.VertexBuffer.UV2Kind
  37042. * - BABYLON.VertexBuffer.UV3Kind
  37043. * - BABYLON.VertexBuffer.UV4Kind
  37044. * - BABYLON.VertexBuffer.UV5Kind
  37045. * - BABYLON.VertexBuffer.UV6Kind
  37046. * - BABYLON.VertexBuffer.ColorKind
  37047. * - BABYLON.VertexBuffer.MatricesIndicesKind
  37048. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  37049. * - BABYLON.VertexBuffer.MatricesWeightsKind
  37050. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  37051. *
  37052. * Returns the Mesh.
  37053. */
  37054. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  37055. if (this.sourceMesh) {
  37056. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  37057. }
  37058. return this.sourceMesh;
  37059. };
  37060. /**
  37061. * Sets the mesh indices.
  37062. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  37063. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  37064. * This method creates a new index buffer each call.
  37065. * Returns the Mesh.
  37066. */
  37067. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  37068. if (this.sourceMesh) {
  37069. this.sourceMesh.setIndices(indices, totalVertices);
  37070. }
  37071. return this.sourceMesh;
  37072. };
  37073. /**
  37074. * Boolean : True if the mesh owns the requested kind of data.
  37075. */
  37076. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  37077. return this._sourceMesh.isVerticesDataPresent(kind);
  37078. };
  37079. /**
  37080. * Returns an array of indices (IndicesArray).
  37081. */
  37082. InstancedMesh.prototype.getIndices = function () {
  37083. return this._sourceMesh.getIndices();
  37084. };
  37085. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  37086. get: function () {
  37087. return this._sourceMesh._positions;
  37088. },
  37089. enumerable: true,
  37090. configurable: true
  37091. });
  37092. /**
  37093. * Sets a new updated BoundingInfo to the mesh.
  37094. * Returns the mesh.
  37095. */
  37096. InstancedMesh.prototype.refreshBoundingInfo = function () {
  37097. var meshBB = this._sourceMesh.getBoundingInfo();
  37098. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  37099. this._updateBoundingInfo();
  37100. return this;
  37101. };
  37102. InstancedMesh.prototype._preActivate = function () {
  37103. if (this._currentLOD) {
  37104. this._currentLOD._preActivate();
  37105. }
  37106. return this;
  37107. };
  37108. InstancedMesh.prototype._activate = function (renderId) {
  37109. if (this._currentLOD) {
  37110. this._currentLOD._registerInstanceForRenderId(this, renderId);
  37111. }
  37112. return this;
  37113. };
  37114. /**
  37115. * Returns the current associated LOD AbstractMesh.
  37116. */
  37117. InstancedMesh.prototype.getLOD = function (camera) {
  37118. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  37119. if (this._currentLOD === this.sourceMesh) {
  37120. return this;
  37121. }
  37122. return this._currentLOD;
  37123. };
  37124. InstancedMesh.prototype._syncSubMeshes = function () {
  37125. this.releaseSubMeshes();
  37126. if (this._sourceMesh.subMeshes) {
  37127. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  37128. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  37129. }
  37130. }
  37131. return this;
  37132. };
  37133. InstancedMesh.prototype._generatePointsArray = function () {
  37134. return this._sourceMesh._generatePointsArray();
  37135. };
  37136. /**
  37137. * Creates a new InstancedMesh from the current mesh.
  37138. * - name (string) : the cloned mesh name
  37139. * - newParent (optional Node) : the optional Node to parent the clone to.
  37140. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  37141. *
  37142. * Returns the clone.
  37143. */
  37144. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  37145. var result = this._sourceMesh.createInstance(name);
  37146. // Deep copy
  37147. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  37148. // Bounding info
  37149. this.refreshBoundingInfo();
  37150. // Parent
  37151. if (newParent) {
  37152. result.parent = newParent;
  37153. }
  37154. if (!doNotCloneChildren) {
  37155. // Children
  37156. for (var index = 0; index < this.getScene().meshes.length; index++) {
  37157. var mesh = this.getScene().meshes[index];
  37158. if (mesh.parent === this) {
  37159. mesh.clone(mesh.name, result);
  37160. }
  37161. }
  37162. }
  37163. result.computeWorldMatrix(true);
  37164. return result;
  37165. };
  37166. /**
  37167. * Disposes the InstancedMesh.
  37168. * Returns nothing.
  37169. */
  37170. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  37171. // Remove from mesh
  37172. var index = this._sourceMesh.instances.indexOf(this);
  37173. this._sourceMesh.instances.splice(index, 1);
  37174. _super.prototype.dispose.call(this, doNotRecurse);
  37175. };
  37176. return InstancedMesh;
  37177. }(BABYLON.AbstractMesh));
  37178. BABYLON.InstancedMesh = InstancedMesh;
  37179. })(BABYLON || (BABYLON = {}));
  37180. //# sourceMappingURL=babylon.instancedMesh.js.map
  37181. /// <reference path="babylon.mesh.ts" />
  37182. var BABYLON;
  37183. (function (BABYLON) {
  37184. var LinesMesh = (function (_super) {
  37185. __extends(LinesMesh, _super);
  37186. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  37187. if (parent === void 0) { parent = null; }
  37188. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  37189. _this.color = new BABYLON.Color3(1, 1, 1);
  37190. _this.alpha = 1;
  37191. _this._positionBuffer = {};
  37192. if (source) {
  37193. _this.color = source.color.clone();
  37194. _this.alpha = source.alpha;
  37195. }
  37196. _this._intersectionThreshold = 0.1;
  37197. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  37198. attributes: [BABYLON.VertexBuffer.PositionKind],
  37199. uniforms: ["worldViewProjection", "color"],
  37200. needAlphaBlending: true
  37201. });
  37202. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  37203. return _this;
  37204. }
  37205. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  37206. /**
  37207. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37208. * This margin is expressed in world space coordinates, so its value may vary.
  37209. * Default value is 0.1
  37210. * @returns the intersection Threshold value.
  37211. */
  37212. get: function () {
  37213. return this._intersectionThreshold;
  37214. },
  37215. /**
  37216. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37217. * This margin is expressed in world space coordinates, so its value may vary.
  37218. * @param value the new threshold to apply
  37219. */
  37220. set: function (value) {
  37221. if (this._intersectionThreshold === value) {
  37222. return;
  37223. }
  37224. this._intersectionThreshold = value;
  37225. if (this.geometry) {
  37226. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  37227. }
  37228. },
  37229. enumerable: true,
  37230. configurable: true
  37231. });
  37232. /**
  37233. * Returns the string "LineMesh"
  37234. */
  37235. LinesMesh.prototype.getClassName = function () {
  37236. return "LinesMesh";
  37237. };
  37238. Object.defineProperty(LinesMesh.prototype, "material", {
  37239. get: function () {
  37240. return this._colorShader;
  37241. },
  37242. enumerable: true,
  37243. configurable: true
  37244. });
  37245. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  37246. get: function () {
  37247. return false;
  37248. },
  37249. enumerable: true,
  37250. configurable: true
  37251. });
  37252. LinesMesh.prototype.createInstance = function (name) {
  37253. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  37254. return null;
  37255. };
  37256. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  37257. var engine = this.getScene().getEngine();
  37258. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  37259. // VBOs
  37260. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  37261. // Color
  37262. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  37263. return this;
  37264. };
  37265. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  37266. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  37267. return this;
  37268. }
  37269. var engine = this.getScene().getEngine();
  37270. // Draw order
  37271. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  37272. return this;
  37273. };
  37274. LinesMesh.prototype.dispose = function (doNotRecurse) {
  37275. this._colorShader.dispose();
  37276. _super.prototype.dispose.call(this, doNotRecurse);
  37277. };
  37278. /**
  37279. * Returns a new LineMesh object cloned from the current one.
  37280. */
  37281. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  37282. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  37283. };
  37284. return LinesMesh;
  37285. }(BABYLON.Mesh));
  37286. BABYLON.LinesMesh = LinesMesh;
  37287. })(BABYLON || (BABYLON = {}));
  37288. //# sourceMappingURL=babylon.linesMesh.js.map
  37289. var BABYLON;
  37290. (function (BABYLON) {
  37291. var ShaderMaterial = (function (_super) {
  37292. __extends(ShaderMaterial, _super);
  37293. function ShaderMaterial(name, scene, shaderPath, options) {
  37294. var _this = _super.call(this, name, scene) || this;
  37295. _this._textures = {};
  37296. _this._textureArrays = {};
  37297. _this._floats = {};
  37298. _this._floatsArrays = {};
  37299. _this._colors3 = {};
  37300. _this._colors4 = {};
  37301. _this._vectors2 = {};
  37302. _this._vectors3 = {};
  37303. _this._vectors4 = {};
  37304. _this._matrices = {};
  37305. _this._matrices3x3 = {};
  37306. _this._matrices2x2 = {};
  37307. _this._vectors3Arrays = {};
  37308. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  37309. _this._shaderPath = shaderPath;
  37310. options.needAlphaBlending = options.needAlphaBlending || false;
  37311. options.needAlphaTesting = options.needAlphaTesting || false;
  37312. options.attributes = options.attributes || ["position", "normal", "uv"];
  37313. options.uniforms = options.uniforms || ["worldViewProjection"];
  37314. options.samplers = options.samplers || [];
  37315. options.defines = options.defines || [];
  37316. _this._options = options;
  37317. return _this;
  37318. }
  37319. ShaderMaterial.prototype.getClassName = function () {
  37320. return "ShaderMaterial";
  37321. };
  37322. ShaderMaterial.prototype.needAlphaBlending = function () {
  37323. return this._options.needAlphaBlending;
  37324. };
  37325. ShaderMaterial.prototype.needAlphaTesting = function () {
  37326. return this._options.needAlphaTesting;
  37327. };
  37328. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  37329. if (this._options.uniforms.indexOf(uniformName) === -1) {
  37330. this._options.uniforms.push(uniformName);
  37331. }
  37332. };
  37333. ShaderMaterial.prototype.setTexture = function (name, texture) {
  37334. if (this._options.samplers.indexOf(name) === -1) {
  37335. this._options.samplers.push(name);
  37336. }
  37337. this._textures[name] = texture;
  37338. return this;
  37339. };
  37340. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  37341. if (this._options.samplers.indexOf(name) === -1) {
  37342. this._options.samplers.push(name);
  37343. }
  37344. this._checkUniform(name);
  37345. this._textureArrays[name] = textures;
  37346. return this;
  37347. };
  37348. ShaderMaterial.prototype.setFloat = function (name, value) {
  37349. this._checkUniform(name);
  37350. this._floats[name] = value;
  37351. return this;
  37352. };
  37353. ShaderMaterial.prototype.setFloats = function (name, value) {
  37354. this._checkUniform(name);
  37355. this._floatsArrays[name] = value;
  37356. return this;
  37357. };
  37358. ShaderMaterial.prototype.setColor3 = function (name, value) {
  37359. this._checkUniform(name);
  37360. this._colors3[name] = value;
  37361. return this;
  37362. };
  37363. ShaderMaterial.prototype.setColor4 = function (name, value) {
  37364. this._checkUniform(name);
  37365. this._colors4[name] = value;
  37366. return this;
  37367. };
  37368. ShaderMaterial.prototype.setVector2 = function (name, value) {
  37369. this._checkUniform(name);
  37370. this._vectors2[name] = value;
  37371. return this;
  37372. };
  37373. ShaderMaterial.prototype.setVector3 = function (name, value) {
  37374. this._checkUniform(name);
  37375. this._vectors3[name] = value;
  37376. return this;
  37377. };
  37378. ShaderMaterial.prototype.setVector4 = function (name, value) {
  37379. this._checkUniform(name);
  37380. this._vectors4[name] = value;
  37381. return this;
  37382. };
  37383. ShaderMaterial.prototype.setMatrix = function (name, value) {
  37384. this._checkUniform(name);
  37385. this._matrices[name] = value;
  37386. return this;
  37387. };
  37388. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  37389. this._checkUniform(name);
  37390. this._matrices3x3[name] = value;
  37391. return this;
  37392. };
  37393. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  37394. this._checkUniform(name);
  37395. this._matrices2x2[name] = value;
  37396. return this;
  37397. };
  37398. ShaderMaterial.prototype.setArray3 = function (name, value) {
  37399. this._checkUniform(name);
  37400. this._vectors3Arrays[name] = value;
  37401. return this;
  37402. };
  37403. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  37404. if (!mesh) {
  37405. return true;
  37406. }
  37407. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  37408. return false;
  37409. }
  37410. return false;
  37411. };
  37412. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  37413. var scene = this.getScene();
  37414. var engine = scene.getEngine();
  37415. if (!this.checkReadyOnEveryCall) {
  37416. if (this._renderId === scene.getRenderId()) {
  37417. if (this._checkCache(scene, mesh, useInstances)) {
  37418. return true;
  37419. }
  37420. }
  37421. }
  37422. // Instances
  37423. var defines = [];
  37424. var fallbacks = new BABYLON.EffectFallbacks();
  37425. if (useInstances) {
  37426. defines.push("#define INSTANCES");
  37427. }
  37428. for (var index = 0; index < this._options.defines.length; index++) {
  37429. defines.push(this._options.defines[index]);
  37430. }
  37431. // Bones
  37432. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  37433. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37434. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37435. fallbacks.addCPUSkinningFallback(0, mesh);
  37436. }
  37437. // Textures
  37438. for (var name in this._textures) {
  37439. if (!this._textures[name].isReady()) {
  37440. return false;
  37441. }
  37442. }
  37443. // Alpha test
  37444. if (engine.getAlphaTesting()) {
  37445. defines.push("#define ALPHATEST");
  37446. }
  37447. var previousEffect = this._effect;
  37448. var join = defines.join("\n");
  37449. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  37450. if (!this._effect.isReady()) {
  37451. return false;
  37452. }
  37453. if (previousEffect !== this._effect) {
  37454. scene.resetCachedMaterial();
  37455. }
  37456. this._renderId = scene.getRenderId();
  37457. return true;
  37458. };
  37459. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37460. var scene = this.getScene();
  37461. if (this._options.uniforms.indexOf("world") !== -1) {
  37462. this._effect.setMatrix("world", world);
  37463. }
  37464. if (this._options.uniforms.indexOf("worldView") !== -1) {
  37465. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  37466. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  37467. }
  37468. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  37469. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  37470. }
  37471. };
  37472. ShaderMaterial.prototype.bind = function (world, mesh) {
  37473. // Std values
  37474. this.bindOnlyWorldMatrix(world);
  37475. if (this.getScene().getCachedMaterial() !== this) {
  37476. if (this._options.uniforms.indexOf("view") !== -1) {
  37477. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  37478. }
  37479. if (this._options.uniforms.indexOf("projection") !== -1) {
  37480. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  37481. }
  37482. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  37483. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  37484. }
  37485. // Bones
  37486. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  37487. var name;
  37488. // Texture
  37489. for (name in this._textures) {
  37490. this._effect.setTexture(name, this._textures[name]);
  37491. }
  37492. // Texture arrays
  37493. for (name in this._textureArrays) {
  37494. this._effect.setTextureArray(name, this._textureArrays[name]);
  37495. }
  37496. // Float
  37497. for (name in this._floats) {
  37498. this._effect.setFloat(name, this._floats[name]);
  37499. }
  37500. // Float s
  37501. for (name in this._floatsArrays) {
  37502. this._effect.setArray(name, this._floatsArrays[name]);
  37503. }
  37504. // Color3
  37505. for (name in this._colors3) {
  37506. this._effect.setColor3(name, this._colors3[name]);
  37507. }
  37508. // Color4
  37509. for (name in this._colors4) {
  37510. var color = this._colors4[name];
  37511. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  37512. }
  37513. // Vector2
  37514. for (name in this._vectors2) {
  37515. this._effect.setVector2(name, this._vectors2[name]);
  37516. }
  37517. // Vector3
  37518. for (name in this._vectors3) {
  37519. this._effect.setVector3(name, this._vectors3[name]);
  37520. }
  37521. // Vector4
  37522. for (name in this._vectors4) {
  37523. this._effect.setVector4(name, this._vectors4[name]);
  37524. }
  37525. // Matrix
  37526. for (name in this._matrices) {
  37527. this._effect.setMatrix(name, this._matrices[name]);
  37528. }
  37529. // Matrix 3x3
  37530. for (name in this._matrices3x3) {
  37531. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  37532. }
  37533. // Matrix 2x2
  37534. for (name in this._matrices2x2) {
  37535. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  37536. }
  37537. // Vector3Array
  37538. for (name in this._vectors3Arrays) {
  37539. this._effect.setArray3(name, this._vectors3Arrays[name]);
  37540. }
  37541. }
  37542. this._afterBind(mesh);
  37543. };
  37544. ShaderMaterial.prototype.clone = function (name) {
  37545. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  37546. return newShaderMaterial;
  37547. };
  37548. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37549. if (forceDisposeTextures) {
  37550. var name;
  37551. for (name in this._textures) {
  37552. this._textures[name].dispose();
  37553. }
  37554. for (name in this._textureArrays) {
  37555. var array = this._textureArrays[name];
  37556. for (var index = 0; index < array.length; index++) {
  37557. array[index].dispose();
  37558. }
  37559. }
  37560. }
  37561. this._textures = {};
  37562. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37563. };
  37564. ShaderMaterial.prototype.serialize = function () {
  37565. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37566. serializationObject.customType = "BABYLON.ShaderMaterial";
  37567. serializationObject.options = this._options;
  37568. serializationObject.shaderPath = this._shaderPath;
  37569. var name;
  37570. // Texture
  37571. serializationObject.textures = {};
  37572. for (name in this._textures) {
  37573. serializationObject.textures[name] = this._textures[name].serialize();
  37574. }
  37575. // Texture arrays
  37576. serializationObject.textureArrays = {};
  37577. for (name in this._textureArrays) {
  37578. serializationObject.textureArrays[name] = [];
  37579. var array = this._textureArrays[name];
  37580. for (var index = 0; index < array.length; index++) {
  37581. serializationObject.textureArrays[name].push(array[index].serialize());
  37582. }
  37583. }
  37584. // Float
  37585. serializationObject.floats = {};
  37586. for (name in this._floats) {
  37587. serializationObject.floats[name] = this._floats[name];
  37588. }
  37589. // Float s
  37590. serializationObject.floatArrays = {};
  37591. for (name in this._floatsArrays) {
  37592. serializationObject.floatArrays[name] = this._floatsArrays[name];
  37593. }
  37594. // Color3
  37595. serializationObject.colors3 = {};
  37596. for (name in this._colors3) {
  37597. serializationObject.colors3[name] = this._colors3[name].asArray();
  37598. }
  37599. // Color4
  37600. serializationObject.colors4 = {};
  37601. for (name in this._colors4) {
  37602. serializationObject.colors4[name] = this._colors4[name].asArray();
  37603. }
  37604. // Vector2
  37605. serializationObject.vectors2 = {};
  37606. for (name in this._vectors2) {
  37607. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  37608. }
  37609. // Vector3
  37610. serializationObject.vectors3 = {};
  37611. for (name in this._vectors3) {
  37612. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  37613. }
  37614. // Vector4
  37615. serializationObject.vectors4 = {};
  37616. for (name in this._vectors4) {
  37617. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  37618. }
  37619. // Matrix
  37620. serializationObject.matrices = {};
  37621. for (name in this._matrices) {
  37622. serializationObject.matrices[name] = this._matrices[name].asArray();
  37623. }
  37624. // Matrix 3x3
  37625. serializationObject.matrices3x3 = {};
  37626. for (name in this._matrices3x3) {
  37627. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  37628. }
  37629. // Matrix 2x2
  37630. serializationObject.matrices2x2 = {};
  37631. for (name in this._matrices2x2) {
  37632. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  37633. }
  37634. // Vector3Array
  37635. serializationObject.vectors3Arrays = {};
  37636. for (name in this._vectors3Arrays) {
  37637. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  37638. }
  37639. return serializationObject;
  37640. };
  37641. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  37642. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  37643. var name;
  37644. // Texture
  37645. for (name in source.textures) {
  37646. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  37647. }
  37648. // Texture arrays
  37649. for (name in source.textureArrays) {
  37650. var array = source.textureArrays[name];
  37651. var textureArray = new Array();
  37652. for (var index = 0; index < array.length; index++) {
  37653. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  37654. }
  37655. material.setTextureArray(name, textureArray);
  37656. }
  37657. // Float
  37658. for (name in source.floats) {
  37659. material.setFloat(name, source.floats[name]);
  37660. }
  37661. // Float s
  37662. for (name in source.floatsArrays) {
  37663. material.setFloats(name, source.floatsArrays[name]);
  37664. }
  37665. // Color3
  37666. for (name in source.colors3) {
  37667. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  37668. }
  37669. // Color4
  37670. for (name in source.colors4) {
  37671. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  37672. }
  37673. // Vector2
  37674. for (name in source.vectors2) {
  37675. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  37676. }
  37677. // Vector3
  37678. for (name in source.vectors3) {
  37679. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  37680. }
  37681. // Vector4
  37682. for (name in source.vectors4) {
  37683. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  37684. }
  37685. // Matrix
  37686. for (name in source.matrices) {
  37687. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  37688. }
  37689. // Matrix 3x3
  37690. for (name in source.matrices3x3) {
  37691. material.setMatrix3x3(name, source.matrices3x3[name]);
  37692. }
  37693. // Matrix 2x2
  37694. for (name in source.matrices2x2) {
  37695. material.setMatrix2x2(name, source.matrices2x2[name]);
  37696. }
  37697. // Vector3Array
  37698. for (name in source.vectors3Arrays) {
  37699. material.setArray3(name, source.vectors3Arrays[name]);
  37700. }
  37701. return material;
  37702. };
  37703. return ShaderMaterial;
  37704. }(BABYLON.Material));
  37705. BABYLON.ShaderMaterial = ShaderMaterial;
  37706. })(BABYLON || (BABYLON = {}));
  37707. //# sourceMappingURL=babylon.shaderMaterial.js.map
  37708. var BABYLON;
  37709. (function (BABYLON) {
  37710. var MeshBuilder = (function () {
  37711. function MeshBuilder() {
  37712. }
  37713. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  37714. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  37715. return BABYLON.Mesh.DOUBLESIDE;
  37716. }
  37717. if (orientation === undefined || orientation === null) {
  37718. return BABYLON.Mesh.FRONTSIDE;
  37719. }
  37720. return orientation;
  37721. };
  37722. /**
  37723. * Creates a box mesh.
  37724. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  37725. * The parameter `size` sets the size (float) of each box side (default 1).
  37726. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  37727. * 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).
  37728. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  37729. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37730. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37731. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37732. */
  37733. MeshBuilder.CreateBox = function (name, options, scene) {
  37734. var box = new BABYLON.Mesh(name, scene);
  37735. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37736. box.sideOrientation = options.sideOrientation;
  37737. var vertexData = BABYLON.VertexData.CreateBox(options);
  37738. vertexData.applyToMesh(box, options.updatable);
  37739. return box;
  37740. };
  37741. /**
  37742. * Creates a sphere mesh.
  37743. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  37744. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  37745. * 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`).
  37746. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  37747. * 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
  37748. * 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).
  37749. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37750. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37751. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37752. */
  37753. MeshBuilder.CreateSphere = function (name, options, scene) {
  37754. var sphere = new BABYLON.Mesh(name, scene);
  37755. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37756. sphere.sideOrientation = options.sideOrientation;
  37757. var vertexData = BABYLON.VertexData.CreateSphere(options);
  37758. vertexData.applyToMesh(sphere, options.updatable);
  37759. return sphere;
  37760. };
  37761. /**
  37762. * Creates a plane polygonal mesh. By default, this is a disc.
  37763. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  37764. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  37765. * 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.
  37766. * 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
  37767. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37768. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37770. */
  37771. MeshBuilder.CreateDisc = function (name, options, scene) {
  37772. var disc = new BABYLON.Mesh(name, scene);
  37773. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37774. disc.sideOrientation = options.sideOrientation;
  37775. var vertexData = BABYLON.VertexData.CreateDisc(options);
  37776. vertexData.applyToMesh(disc, options.updatable);
  37777. return disc;
  37778. };
  37779. /**
  37780. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  37781. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  37782. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  37783. * 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`).
  37784. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  37785. * 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.
  37786. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37787. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37788. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37789. */
  37790. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  37791. var sphere = new BABYLON.Mesh(name, scene);
  37792. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37793. sphere.sideOrientation = options.sideOrientation;
  37794. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  37795. vertexData.applyToMesh(sphere, options.updatable);
  37796. return sphere;
  37797. };
  37798. ;
  37799. /**
  37800. * Creates a ribbon mesh.
  37801. * 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.
  37802. *
  37803. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  37804. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  37805. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  37806. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  37807. * 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.
  37808. * 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.
  37809. * 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
  37810. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37811. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37812. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37813. * 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.
  37814. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  37815. * 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
  37816. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  37817. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  37818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37819. */
  37820. MeshBuilder.CreateRibbon = function (name, options, scene) {
  37821. var pathArray = options.pathArray;
  37822. var closeArray = options.closeArray;
  37823. var closePath = options.closePath;
  37824. var offset = options.offset;
  37825. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37826. var instance = options.instance;
  37827. var updatable = options.updatable;
  37828. if (instance) {
  37829. // positionFunction : ribbon case
  37830. // only pathArray and sideOrientation parameters are taken into account for positions update
  37831. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  37832. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  37833. var positionFunction = function (positions) {
  37834. var minlg = pathArray[0].length;
  37835. var i = 0;
  37836. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  37837. for (var si = 1; si <= ns; si++) {
  37838. for (var p = 0; p < pathArray.length; p++) {
  37839. var path = pathArray[p];
  37840. var l = path.length;
  37841. minlg = (minlg < l) ? minlg : l;
  37842. var j = 0;
  37843. while (j < minlg) {
  37844. positions[i] = path[j].x;
  37845. positions[i + 1] = path[j].y;
  37846. positions[i + 2] = path[j].z;
  37847. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  37848. BABYLON.Tmp.Vector3[0].x = path[j].x;
  37849. }
  37850. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  37851. BABYLON.Tmp.Vector3[1].x = path[j].x;
  37852. }
  37853. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  37854. BABYLON.Tmp.Vector3[0].y = path[j].y;
  37855. }
  37856. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  37857. BABYLON.Tmp.Vector3[1].y = path[j].y;
  37858. }
  37859. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  37860. BABYLON.Tmp.Vector3[0].z = path[j].z;
  37861. }
  37862. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  37863. BABYLON.Tmp.Vector3[1].z = path[j].z;
  37864. }
  37865. j++;
  37866. i += 3;
  37867. }
  37868. if (instance._closePath) {
  37869. positions[i] = path[0].x;
  37870. positions[i + 1] = path[0].y;
  37871. positions[i + 2] = path[0].z;
  37872. i += 3;
  37873. }
  37874. }
  37875. }
  37876. };
  37877. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37878. positionFunction(positions);
  37879. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  37880. instance._boundingInfo.update(instance._worldMatrix);
  37881. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  37882. if (options.colors) {
  37883. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37884. for (var c = 0; c < options.colors.length; c++) {
  37885. colors[c * 4] = options.colors[c].r;
  37886. colors[c * 4 + 1] = options.colors[c].g;
  37887. colors[c * 4 + 2] = options.colors[c].b;
  37888. colors[c * 4 + 3] = options.colors[c].a;
  37889. }
  37890. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  37891. }
  37892. if (options.uvs) {
  37893. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37894. for (var i = 0; i < options.uvs.length; i++) {
  37895. uvs[i * 2] = options.uvs[i].x;
  37896. uvs[i * 2 + 1] = options.uvs[i].y;
  37897. }
  37898. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  37899. }
  37900. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  37901. var indices = instance.getIndices();
  37902. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37903. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  37904. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  37905. if (instance._closePath) {
  37906. var indexFirst = 0;
  37907. var indexLast = 0;
  37908. for (var p = 0; p < pathArray.length; p++) {
  37909. indexFirst = instance._idx[p] * 3;
  37910. if (p + 1 < pathArray.length) {
  37911. indexLast = (instance._idx[p + 1] - 1) * 3;
  37912. }
  37913. else {
  37914. indexLast = normals.length - 3;
  37915. }
  37916. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37917. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37918. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37919. normals[indexLast] = normals[indexFirst];
  37920. normals[indexLast + 1] = normals[indexFirst + 1];
  37921. normals[indexLast + 2] = normals[indexFirst + 2];
  37922. }
  37923. }
  37924. if (!(instance.areNormalsFrozen)) {
  37925. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  37926. }
  37927. }
  37928. return instance;
  37929. }
  37930. else {
  37931. var ribbon = new BABYLON.Mesh(name, scene);
  37932. ribbon.sideOrientation = sideOrientation;
  37933. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  37934. if (closePath) {
  37935. ribbon._idx = vertexData._idx;
  37936. }
  37937. ribbon._closePath = closePath;
  37938. ribbon._closeArray = closeArray;
  37939. vertexData.applyToMesh(ribbon, updatable);
  37940. return ribbon;
  37941. }
  37942. };
  37943. /**
  37944. * Creates a cylinder or a cone mesh.
  37945. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  37946. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  37947. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  37948. * 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.
  37949. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  37950. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  37951. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  37952. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  37953. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  37954. * 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).
  37955. * 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
  37956. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  37957. * 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
  37958. * 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.
  37959. * If `enclose` is false, a ring surface is one element.
  37960. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  37961. * 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
  37962. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37963. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37964. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37965. */
  37966. MeshBuilder.CreateCylinder = function (name, options, scene) {
  37967. var cylinder = new BABYLON.Mesh(name, scene);
  37968. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37969. cylinder.sideOrientation = options.sideOrientation;
  37970. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  37971. vertexData.applyToMesh(cylinder, options.updatable);
  37972. return cylinder;
  37973. };
  37974. /**
  37975. * Creates a torus mesh.
  37976. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  37977. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  37978. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  37979. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  37980. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37981. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37982. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37983. */
  37984. MeshBuilder.CreateTorus = function (name, options, scene) {
  37985. var torus = new BABYLON.Mesh(name, scene);
  37986. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37987. torus.sideOrientation = options.sideOrientation;
  37988. var vertexData = BABYLON.VertexData.CreateTorus(options);
  37989. vertexData.applyToMesh(torus, options.updatable);
  37990. return torus;
  37991. };
  37992. /**
  37993. * Creates a torus knot mesh.
  37994. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  37995. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  37996. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  37997. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  37998. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  37999. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38000. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38001. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38002. */
  38003. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  38004. var torusKnot = new BABYLON.Mesh(name, scene);
  38005. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38006. torusKnot.sideOrientation = options.sideOrientation;
  38007. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  38008. vertexData.applyToMesh(torusKnot, options.updatable);
  38009. return torusKnot;
  38010. };
  38011. /**
  38012. * Creates a line system mesh.
  38013. * A line system is a pool of many lines gathered in a single mesh.
  38014. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  38015. * 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.
  38016. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  38017. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  38018. * 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
  38019. * 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
  38020. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  38021. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38022. */
  38023. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  38024. var instance = options.instance;
  38025. var lines = options.lines;
  38026. if (instance) {
  38027. var positionFunction = function (positions) {
  38028. var i = 0;
  38029. for (var l = 0; l < lines.length; l++) {
  38030. var points = lines[l];
  38031. for (var p = 0; p < points.length; p++) {
  38032. positions[i] = points[p].x;
  38033. positions[i + 1] = points[p].y;
  38034. positions[i + 2] = points[p].z;
  38035. i += 3;
  38036. }
  38037. }
  38038. };
  38039. instance.updateMeshPositions(positionFunction, false);
  38040. return instance;
  38041. }
  38042. // line system creation
  38043. var lineSystem = new BABYLON.LinesMesh(name, scene);
  38044. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  38045. vertexData.applyToMesh(lineSystem, options.updatable);
  38046. return lineSystem;
  38047. };
  38048. /**
  38049. * Creates a line mesh.
  38050. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  38051. * 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.
  38052. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  38053. * The parameter `points` is an array successive Vector3.
  38054. * 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
  38055. * When updating an instance, remember that only point positions can change, not the number of points.
  38056. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38057. */
  38058. MeshBuilder.CreateLines = function (name, options, scene) {
  38059. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  38060. return lines;
  38061. };
  38062. /**
  38063. * Creates a dashed line mesh.
  38064. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  38065. * 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.
  38066. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  38067. * The parameter `points` is an array successive Vector3.
  38068. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  38069. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  38070. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  38071. * 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
  38072. * When updating an instance, remember that only point positions can change, not the number of points.
  38073. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38074. */
  38075. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  38076. var points = options.points;
  38077. var instance = options.instance;
  38078. var gapSize = options.gapSize;
  38079. var dashNb = options.dashNb;
  38080. var dashSize = options.dashSize;
  38081. if (instance) {
  38082. var positionFunction = function (positions) {
  38083. var curvect = BABYLON.Vector3.Zero();
  38084. var nbSeg = positions.length / 6;
  38085. var lg = 0;
  38086. var nb = 0;
  38087. var shft = 0;
  38088. var dashshft = 0;
  38089. var curshft = 0;
  38090. var p = 0;
  38091. var i = 0;
  38092. var j = 0;
  38093. for (i = 0; i < points.length - 1; i++) {
  38094. points[i + 1].subtractToRef(points[i], curvect);
  38095. lg += curvect.length();
  38096. }
  38097. shft = lg / nbSeg;
  38098. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  38099. for (i = 0; i < points.length - 1; i++) {
  38100. points[i + 1].subtractToRef(points[i], curvect);
  38101. nb = Math.floor(curvect.length() / shft);
  38102. curvect.normalize();
  38103. j = 0;
  38104. while (j < nb && p < positions.length) {
  38105. curshft = shft * j;
  38106. positions[p] = points[i].x + curshft * curvect.x;
  38107. positions[p + 1] = points[i].y + curshft * curvect.y;
  38108. positions[p + 2] = points[i].z + curshft * curvect.z;
  38109. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  38110. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  38111. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  38112. p += 6;
  38113. j++;
  38114. }
  38115. }
  38116. while (p < positions.length) {
  38117. positions[p] = points[i].x;
  38118. positions[p + 1] = points[i].y;
  38119. positions[p + 2] = points[i].z;
  38120. p += 3;
  38121. }
  38122. };
  38123. instance.updateMeshPositions(positionFunction, false);
  38124. return instance;
  38125. }
  38126. // dashed lines creation
  38127. var dashedLines = new BABYLON.LinesMesh(name, scene);
  38128. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  38129. vertexData.applyToMesh(dashedLines, options.updatable);
  38130. dashedLines.dashSize = dashSize;
  38131. dashedLines.gapSize = gapSize;
  38132. return dashedLines;
  38133. };
  38134. /**
  38135. * Creates an extruded shape mesh.
  38136. * 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.
  38137. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  38138. *
  38139. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  38140. * 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
  38141. * extruded along the Z axis.
  38142. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  38143. * 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.
  38144. * The parameter `scale` (float, default 1) is the value to scale the shape.
  38145. * 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
  38146. * 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
  38147. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  38148. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38149. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38150. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38152. */
  38153. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  38154. var path = options.path;
  38155. var shape = options.shape;
  38156. var scale = options.scale || 1;
  38157. var rotation = options.rotation || 0;
  38158. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  38159. var updatable = options.updatable;
  38160. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38161. var instance = options.instance;
  38162. var invertUV = options.invertUV || false;
  38163. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  38164. };
  38165. /**
  38166. * Creates an custom extruded shape mesh.
  38167. * 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.
  38168. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  38169. *
  38170. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  38171. * 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
  38172. * extruded along the Z axis.
  38173. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  38174. * 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
  38175. * and the distance of this point from the begining of the path :
  38176. * ```javascript
  38177. * var rotationFunction = function(i, distance) {
  38178. * // do things
  38179. * return rotationValue; }
  38180. * ```
  38181. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  38182. * 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
  38183. * and the distance of this point from the begining of the path :
  38184. * ```javascript
  38185. * var scaleFunction = function(i, distance) {
  38186. * // do things
  38187. * return scaleValue;}
  38188. * ```
  38189. * It must returns a float value that will be the scale value applied to the shape on each path point.
  38190. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  38191. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  38192. * 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
  38193. * 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
  38194. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  38195. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38196. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38197. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38198. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38199. */
  38200. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  38201. var path = options.path;
  38202. var shape = options.shape;
  38203. var scaleFunction = options.scaleFunction || (function () { return 1; });
  38204. var rotationFunction = options.rotationFunction || (function () { return 0; });
  38205. var ribbonCloseArray = options.ribbonCloseArray || false;
  38206. var ribbonClosePath = options.ribbonClosePath || false;
  38207. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  38208. var updatable = options.updatable;
  38209. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38210. var instance = options.instance;
  38211. var invertUV = options.invertUV || false;
  38212. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  38213. };
  38214. /**
  38215. * Creates lathe mesh.
  38216. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  38217. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  38218. *
  38219. * 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
  38220. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  38221. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  38222. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  38223. * 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.
  38224. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  38225. * 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
  38226. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38227. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38228. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38229. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38230. */
  38231. MeshBuilder.CreateLathe = function (name, options, scene) {
  38232. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  38233. var closed = (options.closed === undefined) ? true : options.closed;
  38234. var shape = options.shape;
  38235. var radius = options.radius || 1;
  38236. var tessellation = options.tessellation || 64;
  38237. var updatable = options.updatable;
  38238. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38239. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  38240. var pi2 = Math.PI * 2;
  38241. var paths = new Array();
  38242. var invertUV = options.invertUV || false;
  38243. var i = 0;
  38244. var p = 0;
  38245. var step = pi2 / tessellation * arc;
  38246. var rotated;
  38247. var path = new Array();
  38248. ;
  38249. for (i = 0; i <= tessellation; i++) {
  38250. var path = [];
  38251. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  38252. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  38253. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  38254. }
  38255. for (p = 0; p < shape.length; p++) {
  38256. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  38257. path.push(rotated);
  38258. }
  38259. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  38260. 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));
  38261. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  38262. }
  38263. paths.push(path);
  38264. }
  38265. // lathe ribbon
  38266. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  38267. return lathe;
  38268. };
  38269. /**
  38270. * Creates a plane mesh.
  38271. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  38272. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  38273. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  38274. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  38275. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38276. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38277. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38278. */
  38279. MeshBuilder.CreatePlane = function (name, options, scene) {
  38280. var plane = new BABYLON.Mesh(name, scene);
  38281. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38282. plane.sideOrientation = options.sideOrientation;
  38283. var vertexData = BABYLON.VertexData.CreatePlane(options);
  38284. vertexData.applyToMesh(plane, options.updatable);
  38285. if (options.sourcePlane) {
  38286. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  38287. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  38288. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  38289. plane.rotate(vectorProduct, product);
  38290. }
  38291. return plane;
  38292. };
  38293. /**
  38294. * Creates a ground mesh.
  38295. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  38296. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  38297. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  38298. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38299. */
  38300. MeshBuilder.CreateGround = function (name, options, scene) {
  38301. var ground = new BABYLON.GroundMesh(name, scene);
  38302. ground._setReady(false);
  38303. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38304. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38305. ground._width = options.width || 1;
  38306. ground._height = options.height || 1;
  38307. ground._maxX = ground._width / 2;
  38308. ground._maxZ = ground._height / 2;
  38309. ground._minX = -ground._maxX;
  38310. ground._minZ = -ground._maxZ;
  38311. var vertexData = BABYLON.VertexData.CreateGround(options);
  38312. vertexData.applyToMesh(ground, options.updatable);
  38313. ground._setReady(true);
  38314. return ground;
  38315. };
  38316. /**
  38317. * Creates a tiled ground mesh.
  38318. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  38319. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  38320. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  38321. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  38322. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  38323. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  38324. * numbers of subdivisions on the ground width and height of each tile.
  38325. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38326. */
  38327. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  38328. var tiledGround = new BABYLON.Mesh(name, scene);
  38329. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  38330. vertexData.applyToMesh(tiledGround, options.updatable);
  38331. return tiledGround;
  38332. };
  38333. /**
  38334. * Creates a ground mesh from a height map.
  38335. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  38336. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  38337. * The parameter `url` sets the URL of the height map image resource.
  38338. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  38339. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  38340. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  38341. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  38342. * 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.
  38343. * 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).
  38344. * This function is passed the newly built mesh :
  38345. * ```javascript
  38346. * function(mesh) { // do things
  38347. * return; }
  38348. * ```
  38349. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38350. */
  38351. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  38352. var width = options.width || 10.0;
  38353. var height = options.height || 10.0;
  38354. var subdivisions = options.subdivisions || 1 | 0;
  38355. var minHeight = options.minHeight || 0.0;
  38356. var maxHeight = options.maxHeight || 10.0;
  38357. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38358. var updatable = options.updatable;
  38359. var onReady = options.onReady;
  38360. var ground = new BABYLON.GroundMesh(name, scene);
  38361. ground._subdivisionsX = subdivisions;
  38362. ground._subdivisionsY = subdivisions;
  38363. ground._width = width;
  38364. ground._height = height;
  38365. ground._maxX = ground._width / 2.0;
  38366. ground._maxZ = ground._height / 2.0;
  38367. ground._minX = -ground._maxX;
  38368. ground._minZ = -ground._maxZ;
  38369. ground._setReady(false);
  38370. var onload = function (img) {
  38371. // Getting height map data
  38372. var canvas = document.createElement("canvas");
  38373. var context = canvas.getContext("2d");
  38374. var bufferWidth = img.width;
  38375. var bufferHeight = img.height;
  38376. canvas.width = bufferWidth;
  38377. canvas.height = bufferHeight;
  38378. context.drawImage(img, 0, 0);
  38379. // Create VertexData from map data
  38380. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  38381. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  38382. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  38383. width: width, height: height,
  38384. subdivisions: subdivisions,
  38385. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  38386. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  38387. });
  38388. vertexData.applyToMesh(ground, updatable);
  38389. ground._setReady(true);
  38390. //execute ready callback, if set
  38391. if (onReady) {
  38392. onReady(ground);
  38393. }
  38394. };
  38395. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  38396. return ground;
  38397. };
  38398. /**
  38399. * Creates a tube mesh.
  38400. * 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.
  38401. *
  38402. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  38403. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  38404. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  38405. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  38406. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  38407. * 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.
  38408. * It must return a radius value (positive float) :
  38409. * ```javascript
  38410. * var radiusFunction = function(i, distance) {
  38411. * // do things
  38412. * return radius; }
  38413. * ```
  38414. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  38415. * 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
  38416. * 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
  38417. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38418. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38419. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38420. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38421. */
  38422. MeshBuilder.CreateTube = function (name, options, scene) {
  38423. var path = options.path;
  38424. var radius = options.radius || 1.0;
  38425. var tessellation = options.tessellation || 64 | 0;
  38426. var radiusFunction = options.radiusFunction;
  38427. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  38428. var invertUV = options.invertUV || false;
  38429. var updatable = options.updatable;
  38430. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38431. var instance = options.instance;
  38432. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  38433. // tube geometry
  38434. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  38435. var tangents = path3D.getTangents();
  38436. var normals = path3D.getNormals();
  38437. var distances = path3D.getDistances();
  38438. var pi2 = Math.PI * 2;
  38439. var step = pi2 / tessellation * arc;
  38440. var returnRadius = function () { return radius; };
  38441. var radiusFunctionFinal = radiusFunction || returnRadius;
  38442. var circlePath;
  38443. var rad;
  38444. var normal;
  38445. var rotated;
  38446. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  38447. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  38448. for (var i = 0; i < path.length; i++) {
  38449. rad = radiusFunctionFinal(i, distances[i]); // current radius
  38450. circlePath = Array(); // current circle array
  38451. normal = normals[i]; // current normal
  38452. for (var t = 0; t < tessellation; t++) {
  38453. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  38454. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  38455. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  38456. rotated.scaleInPlace(rad).addInPlace(path[i]);
  38457. circlePath[t] = rotated;
  38458. }
  38459. circlePaths[index] = circlePath;
  38460. index++;
  38461. }
  38462. // cap
  38463. var capPath = function (nbPoints, pathIndex) {
  38464. var pointCap = Array();
  38465. for (var i = 0; i < nbPoints; i++) {
  38466. pointCap.push(path[pathIndex]);
  38467. }
  38468. return pointCap;
  38469. };
  38470. switch (cap) {
  38471. case BABYLON.Mesh.NO_CAP:
  38472. break;
  38473. case BABYLON.Mesh.CAP_START:
  38474. circlePaths[0] = capPath(tessellation, 0);
  38475. circlePaths[1] = circlePaths[2].slice(0);
  38476. break;
  38477. case BABYLON.Mesh.CAP_END:
  38478. circlePaths[index] = circlePaths[index - 1].slice(0);
  38479. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  38480. break;
  38481. case BABYLON.Mesh.CAP_ALL:
  38482. circlePaths[0] = capPath(tessellation, 0);
  38483. circlePaths[1] = circlePaths[2].slice(0);
  38484. circlePaths[index] = circlePaths[index - 1].slice(0);
  38485. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  38486. break;
  38487. default:
  38488. break;
  38489. }
  38490. return circlePaths;
  38491. };
  38492. var path3D;
  38493. var pathArray;
  38494. if (instance) {
  38495. var arc = options.arc || instance.arc;
  38496. path3D = (instance.path3D).update(path);
  38497. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  38498. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  38499. instance.path3D = path3D;
  38500. instance.pathArray = pathArray;
  38501. instance.arc = arc;
  38502. return instance;
  38503. }
  38504. // tube creation
  38505. path3D = new BABYLON.Path3D(path);
  38506. var newPathArray = new Array();
  38507. cap = (cap < 0 || cap > 3) ? 0 : cap;
  38508. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  38509. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  38510. tube.pathArray = pathArray;
  38511. tube.path3D = path3D;
  38512. tube.tessellation = tessellation;
  38513. tube.cap = cap;
  38514. tube.arc = options.arc;
  38515. return tube;
  38516. };
  38517. /**
  38518. * Creates a polyhedron mesh.
  38519. *
  38520. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  38521. * 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
  38522. * to choose the wanted type.
  38523. * The parameter `size` (positive float, default 1) sets the polygon size.
  38524. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  38525. * 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`.
  38526. * 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
  38527. * 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)`).
  38528. * 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
  38529. * 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.
  38530. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38531. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38532. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38533. */
  38534. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  38535. var polyhedron = new BABYLON.Mesh(name, scene);
  38536. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38537. polyhedron.sideOrientation = options.sideOrientation;
  38538. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  38539. vertexData.applyToMesh(polyhedron, options.updatable);
  38540. return polyhedron;
  38541. };
  38542. /**
  38543. * Creates a decal mesh.
  38544. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  38545. * 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.
  38546. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  38547. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  38548. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  38549. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  38550. */
  38551. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  38552. var indices = sourceMesh.getIndices();
  38553. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38554. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38555. var position = options.position || BABYLON.Vector3.Zero();
  38556. var normal = options.normal || BABYLON.Vector3.Up();
  38557. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  38558. var angle = options.angle || 0;
  38559. // Getting correct rotation
  38560. if (!normal) {
  38561. var target = new BABYLON.Vector3(0, 0, 1);
  38562. var camera = sourceMesh.getScene().activeCamera;
  38563. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  38564. normal = camera.globalPosition.subtract(cameraWorldTarget);
  38565. }
  38566. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  38567. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  38568. var pitch = Math.atan2(normal.y, len);
  38569. // Matrix
  38570. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  38571. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  38572. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  38573. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  38574. var vertexData = new BABYLON.VertexData();
  38575. vertexData.indices = [];
  38576. vertexData.positions = [];
  38577. vertexData.normals = [];
  38578. vertexData.uvs = [];
  38579. var currentVertexDataIndex = 0;
  38580. var extractDecalVector3 = function (indexId) {
  38581. var vertexId = indices[indexId];
  38582. var result = new BABYLON.PositionNormalVertex();
  38583. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  38584. // Send vector to decal local world
  38585. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  38586. // Get normal
  38587. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  38588. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  38589. return result;
  38590. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  38591. var clip = function (vertices, axis) {
  38592. if (vertices.length === 0) {
  38593. return vertices;
  38594. }
  38595. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  38596. var clipVertices = function (v0, v1) {
  38597. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  38598. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  38599. };
  38600. var result = new Array();
  38601. for (var index = 0; index < vertices.length; index += 3) {
  38602. var v1Out;
  38603. var v2Out;
  38604. var v3Out;
  38605. var total = 0;
  38606. var nV1, nV2, nV3, nV4;
  38607. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  38608. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  38609. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  38610. v1Out = d1 > 0;
  38611. v2Out = d2 > 0;
  38612. v3Out = d3 > 0;
  38613. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  38614. switch (total) {
  38615. case 0:
  38616. result.push(vertices[index]);
  38617. result.push(vertices[index + 1]);
  38618. result.push(vertices[index + 2]);
  38619. break;
  38620. case 1:
  38621. if (v1Out) {
  38622. nV1 = vertices[index + 1];
  38623. nV2 = vertices[index + 2];
  38624. nV3 = clipVertices(vertices[index], nV1);
  38625. nV4 = clipVertices(vertices[index], nV2);
  38626. }
  38627. if (v2Out) {
  38628. nV1 = vertices[index];
  38629. nV2 = vertices[index + 2];
  38630. nV3 = clipVertices(vertices[index + 1], nV1);
  38631. nV4 = clipVertices(vertices[index + 1], nV2);
  38632. result.push(nV3);
  38633. result.push(nV2.clone());
  38634. result.push(nV1.clone());
  38635. result.push(nV2.clone());
  38636. result.push(nV3.clone());
  38637. result.push(nV4);
  38638. break;
  38639. }
  38640. if (v3Out) {
  38641. nV1 = vertices[index];
  38642. nV2 = vertices[index + 1];
  38643. nV3 = clipVertices(vertices[index + 2], nV1);
  38644. nV4 = clipVertices(vertices[index + 2], nV2);
  38645. }
  38646. result.push(nV1.clone());
  38647. result.push(nV2.clone());
  38648. result.push(nV3);
  38649. result.push(nV4);
  38650. result.push(nV3.clone());
  38651. result.push(nV2.clone());
  38652. break;
  38653. case 2:
  38654. if (!v1Out) {
  38655. nV1 = vertices[index].clone();
  38656. nV2 = clipVertices(nV1, vertices[index + 1]);
  38657. nV3 = clipVertices(nV1, vertices[index + 2]);
  38658. result.push(nV1);
  38659. result.push(nV2);
  38660. result.push(nV3);
  38661. }
  38662. if (!v2Out) {
  38663. nV1 = vertices[index + 1].clone();
  38664. nV2 = clipVertices(nV1, vertices[index + 2]);
  38665. nV3 = clipVertices(nV1, vertices[index]);
  38666. result.push(nV1);
  38667. result.push(nV2);
  38668. result.push(nV3);
  38669. }
  38670. if (!v3Out) {
  38671. nV1 = vertices[index + 2].clone();
  38672. nV2 = clipVertices(nV1, vertices[index]);
  38673. nV3 = clipVertices(nV1, vertices[index + 1]);
  38674. result.push(nV1);
  38675. result.push(nV2);
  38676. result.push(nV3);
  38677. }
  38678. break;
  38679. case 3:
  38680. break;
  38681. }
  38682. }
  38683. return result;
  38684. };
  38685. for (var index = 0; index < indices.length; index += 3) {
  38686. var faceVertices = new Array();
  38687. faceVertices.push(extractDecalVector3(index));
  38688. faceVertices.push(extractDecalVector3(index + 1));
  38689. faceVertices.push(extractDecalVector3(index + 2));
  38690. // Clip
  38691. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  38692. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  38693. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  38694. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  38695. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  38696. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  38697. if (faceVertices.length === 0) {
  38698. continue;
  38699. }
  38700. // Add UVs and get back to world
  38701. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  38702. var vertex = faceVertices[vIndex];
  38703. //TODO check for Int32Array | Uint32Array | Uint16Array
  38704. vertexData.indices.push(currentVertexDataIndex);
  38705. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  38706. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  38707. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  38708. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  38709. currentVertexDataIndex++;
  38710. }
  38711. }
  38712. // Return mesh
  38713. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  38714. vertexData.applyToMesh(decal);
  38715. decal.position = position.clone();
  38716. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  38717. return decal;
  38718. };
  38719. // Privates
  38720. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  38721. // extrusion geometry
  38722. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  38723. var tangents = path3D.getTangents();
  38724. var normals = path3D.getNormals();
  38725. var binormals = path3D.getBinormals();
  38726. var distances = path3D.getDistances();
  38727. var angle = 0;
  38728. var returnScale = function () { return scale; };
  38729. var returnRotation = function () { return rotation; };
  38730. var rotate = custom ? rotateFunction : returnRotation;
  38731. var scl = custom ? scaleFunction : returnScale;
  38732. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  38733. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  38734. for (var i = 0; i < curve.length; i++) {
  38735. var shapePath = new Array();
  38736. var angleStep = rotate(i, distances[i]);
  38737. var scaleRatio = scl(i, distances[i]);
  38738. for (var p = 0; p < shape.length; p++) {
  38739. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  38740. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  38741. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  38742. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  38743. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  38744. shapePath[p] = rotated;
  38745. }
  38746. shapePaths[index] = shapePath;
  38747. angle += angleStep;
  38748. index++;
  38749. }
  38750. // cap
  38751. var capPath = function (shapePath) {
  38752. var pointCap = Array();
  38753. var barycenter = BABYLON.Vector3.Zero();
  38754. var i;
  38755. for (i = 0; i < shapePath.length; i++) {
  38756. barycenter.addInPlace(shapePath[i]);
  38757. }
  38758. barycenter.scaleInPlace(1.0 / shapePath.length);
  38759. for (i = 0; i < shapePath.length; i++) {
  38760. pointCap.push(barycenter);
  38761. }
  38762. return pointCap;
  38763. };
  38764. switch (cap) {
  38765. case BABYLON.Mesh.NO_CAP:
  38766. break;
  38767. case BABYLON.Mesh.CAP_START:
  38768. shapePaths[0] = capPath(shapePaths[2]);
  38769. shapePaths[1] = shapePaths[2];
  38770. break;
  38771. case BABYLON.Mesh.CAP_END:
  38772. shapePaths[index] = shapePaths[index - 1];
  38773. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  38774. break;
  38775. case BABYLON.Mesh.CAP_ALL:
  38776. shapePaths[0] = capPath(shapePaths[2]);
  38777. shapePaths[1] = shapePaths[2];
  38778. shapePaths[index] = shapePaths[index - 1];
  38779. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  38780. break;
  38781. default:
  38782. break;
  38783. }
  38784. return shapePaths;
  38785. };
  38786. var path3D;
  38787. var pathArray;
  38788. if (instance) {
  38789. path3D = (instance.path3D).update(curve);
  38790. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  38791. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  38792. return instance;
  38793. }
  38794. // extruded shape creation
  38795. path3D = new BABYLON.Path3D(curve);
  38796. var newShapePaths = new Array();
  38797. cap = (cap < 0 || cap > 3) ? 0 : cap;
  38798. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  38799. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  38800. extrudedGeneric.pathArray = pathArray;
  38801. extrudedGeneric.path3D = path3D;
  38802. extrudedGeneric.cap = cap;
  38803. return extrudedGeneric;
  38804. };
  38805. return MeshBuilder;
  38806. }());
  38807. BABYLON.MeshBuilder = MeshBuilder;
  38808. })(BABYLON || (BABYLON = {}));
  38809. //# sourceMappingURL=babylon.meshBuilder.js.map
  38810. var BABYLON;
  38811. (function (BABYLON) {
  38812. var AudioEngine = (function () {
  38813. function AudioEngine() {
  38814. this._audioContext = null;
  38815. this._audioContextInitialized = false;
  38816. this.canUseWebAudio = false;
  38817. this.WarnedWebAudioUnsupported = false;
  38818. this.unlocked = false;
  38819. this.isMP3supported = false;
  38820. this.isOGGsupported = false;
  38821. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  38822. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  38823. this.canUseWebAudio = true;
  38824. }
  38825. var audioElem = document.createElement('audio');
  38826. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  38827. this.isMP3supported = true;
  38828. }
  38829. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  38830. this.isOGGsupported = true;
  38831. }
  38832. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  38833. this._unlockiOSaudio();
  38834. }
  38835. else {
  38836. this.unlocked = true;
  38837. }
  38838. }
  38839. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  38840. get: function () {
  38841. if (!this._audioContextInitialized) {
  38842. this._initializeAudioContext();
  38843. }
  38844. return this._audioContext;
  38845. },
  38846. enumerable: true,
  38847. configurable: true
  38848. });
  38849. AudioEngine.prototype._unlockiOSaudio = function () {
  38850. var _this = this;
  38851. var unlockaudio = function () {
  38852. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  38853. var source = _this.audioContext.createBufferSource();
  38854. source.buffer = buffer;
  38855. source.connect(_this.audioContext.destination);
  38856. source.start(0);
  38857. setTimeout(function () {
  38858. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  38859. _this.unlocked = true;
  38860. window.removeEventListener('touchend', unlockaudio, false);
  38861. if (_this.onAudioUnlocked) {
  38862. _this.onAudioUnlocked();
  38863. }
  38864. }
  38865. }, 0);
  38866. };
  38867. window.addEventListener('touchend', unlockaudio, false);
  38868. };
  38869. AudioEngine.prototype._initializeAudioContext = function () {
  38870. try {
  38871. if (this.canUseWebAudio) {
  38872. this._audioContext = new AudioContext();
  38873. // create a global volume gain node
  38874. this.masterGain = this._audioContext.createGain();
  38875. this.masterGain.gain.value = 1;
  38876. this.masterGain.connect(this._audioContext.destination);
  38877. this._audioContextInitialized = true;
  38878. }
  38879. }
  38880. catch (e) {
  38881. this.canUseWebAudio = false;
  38882. BABYLON.Tools.Error("Web Audio: " + e.message);
  38883. }
  38884. };
  38885. AudioEngine.prototype.dispose = function () {
  38886. if (this.canUseWebAudio && this._audioContextInitialized) {
  38887. if (this._connectedAnalyser) {
  38888. this._connectedAnalyser.stopDebugCanvas();
  38889. this._connectedAnalyser.dispose();
  38890. this.masterGain.disconnect();
  38891. this.masterGain.connect(this._audioContext.destination);
  38892. this._connectedAnalyser = null;
  38893. }
  38894. this.masterGain.gain.value = 1;
  38895. }
  38896. this.WarnedWebAudioUnsupported = false;
  38897. };
  38898. AudioEngine.prototype.getGlobalVolume = function () {
  38899. if (this.canUseWebAudio && this._audioContextInitialized) {
  38900. return this.masterGain.gain.value;
  38901. }
  38902. else {
  38903. return -1;
  38904. }
  38905. };
  38906. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  38907. if (this.canUseWebAudio && this._audioContextInitialized) {
  38908. this.masterGain.gain.value = newVolume;
  38909. }
  38910. };
  38911. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  38912. if (this._connectedAnalyser) {
  38913. this._connectedAnalyser.stopDebugCanvas();
  38914. }
  38915. if (this.canUseWebAudio && this._audioContextInitialized) {
  38916. this._connectedAnalyser = analyser;
  38917. this.masterGain.disconnect();
  38918. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  38919. }
  38920. };
  38921. return AudioEngine;
  38922. }());
  38923. BABYLON.AudioEngine = AudioEngine;
  38924. })(BABYLON || (BABYLON = {}));
  38925. //# sourceMappingURL=babylon.audioEngine.js.map
  38926. var BABYLON;
  38927. (function (BABYLON) {
  38928. var Sound = (function () {
  38929. /**
  38930. * Create a sound and attach it to a scene
  38931. * @param name Name of your sound
  38932. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  38933. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  38934. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  38935. */
  38936. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  38937. var _this = this;
  38938. this.autoplay = false;
  38939. this.loop = false;
  38940. this.useCustomAttenuation = false;
  38941. this.spatialSound = false;
  38942. this.refDistance = 1;
  38943. this.rolloffFactor = 1;
  38944. this.maxDistance = 100;
  38945. this.distanceModel = "linear";
  38946. this._panningModel = "equalpower";
  38947. this._playbackRate = 1;
  38948. this._streaming = false;
  38949. this._startTime = 0;
  38950. this._startOffset = 0;
  38951. this._position = BABYLON.Vector3.Zero();
  38952. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  38953. this._volume = 1;
  38954. this._isLoaded = false;
  38955. this._isReadyToPlay = false;
  38956. this.isPlaying = false;
  38957. this.isPaused = false;
  38958. this._isDirectional = false;
  38959. // Used if you'd like to create a directional sound.
  38960. // If not set, the sound will be omnidirectional
  38961. this._coneInnerAngle = 360;
  38962. this._coneOuterAngle = 360;
  38963. this._coneOuterGain = 0;
  38964. this._isOutputConnected = false;
  38965. this._urlType = "Unknown";
  38966. this.name = name;
  38967. this._scene = scene;
  38968. this._readyToPlayCallback = readyToPlayCallback;
  38969. // Default custom attenuation function is a linear attenuation
  38970. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  38971. if (currentDistance < maxDistance) {
  38972. return currentVolume * (1 - currentDistance / maxDistance);
  38973. }
  38974. else {
  38975. return 0;
  38976. }
  38977. };
  38978. if (options) {
  38979. this.autoplay = options.autoplay || false;
  38980. this.loop = options.loop || false;
  38981. // if volume === 0, we need another way to check this option
  38982. if (options.volume !== undefined) {
  38983. this._volume = options.volume;
  38984. }
  38985. this.spatialSound = options.spatialSound || false;
  38986. this.maxDistance = options.maxDistance || 100;
  38987. this.useCustomAttenuation = options.useCustomAttenuation || false;
  38988. this.rolloffFactor = options.rolloffFactor || 1;
  38989. this.refDistance = options.refDistance || 1;
  38990. this.distanceModel = options.distanceModel || "linear";
  38991. this._playbackRate = options.playbackRate || 1;
  38992. this._streaming = options.streaming || false;
  38993. }
  38994. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38995. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  38996. this._soundGain.gain.value = this._volume;
  38997. this._inputAudioNode = this._soundGain;
  38998. this._ouputAudioNode = this._soundGain;
  38999. if (this.spatialSound) {
  39000. this._createSpatialParameters();
  39001. }
  39002. this._scene.mainSoundTrack.AddSound(this);
  39003. var validParameter = true;
  39004. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  39005. if (urlOrArrayBuffer) {
  39006. if (typeof (urlOrArrayBuffer) === "string")
  39007. this._urlType = "String";
  39008. if (Array.isArray(urlOrArrayBuffer))
  39009. this._urlType = "Array";
  39010. if (urlOrArrayBuffer instanceof ArrayBuffer)
  39011. this._urlType = "ArrayBuffer";
  39012. var urls = [];
  39013. var codecSupportedFound = false;
  39014. switch (this._urlType) {
  39015. case "ArrayBuffer":
  39016. if (urlOrArrayBuffer.byteLength > 0) {
  39017. codecSupportedFound = true;
  39018. this._soundLoaded(urlOrArrayBuffer);
  39019. }
  39020. break;
  39021. case "String":
  39022. urls.push(urlOrArrayBuffer);
  39023. case "Array":
  39024. if (urls.length === 0)
  39025. urls = urlOrArrayBuffer;
  39026. // If we found a supported format, we load it immediately and stop the loop
  39027. for (var i = 0; i < urls.length; i++) {
  39028. var url = urls[i];
  39029. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  39030. codecSupportedFound = true;
  39031. }
  39032. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  39033. codecSupportedFound = true;
  39034. }
  39035. if (url.indexOf(".wav", url.length - 4) !== -1) {
  39036. codecSupportedFound = true;
  39037. }
  39038. if (codecSupportedFound) {
  39039. // Loading sound using XHR2
  39040. if (!this._streaming) {
  39041. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  39042. }
  39043. else {
  39044. this._htmlAudioElement = new Audio(url);
  39045. this._htmlAudioElement.controls = false;
  39046. this._htmlAudioElement.loop = this.loop;
  39047. this._htmlAudioElement.crossOrigin = "anonymous";
  39048. this._htmlAudioElement.preload = "auto";
  39049. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  39050. _this._isReadyToPlay = true;
  39051. if (_this.autoplay) {
  39052. _this.play();
  39053. }
  39054. if (_this._readyToPlayCallback) {
  39055. _this._readyToPlayCallback();
  39056. }
  39057. });
  39058. document.body.appendChild(this._htmlAudioElement);
  39059. }
  39060. break;
  39061. }
  39062. }
  39063. break;
  39064. default:
  39065. validParameter = false;
  39066. break;
  39067. }
  39068. if (!validParameter) {
  39069. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  39070. }
  39071. else {
  39072. if (!codecSupportedFound) {
  39073. this._isReadyToPlay = true;
  39074. // Simulating a ready to play event to avoid breaking code path
  39075. if (this._readyToPlayCallback) {
  39076. window.setTimeout(function () {
  39077. _this._readyToPlayCallback();
  39078. }, 1000);
  39079. }
  39080. }
  39081. }
  39082. }
  39083. }
  39084. else {
  39085. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  39086. this._scene.mainSoundTrack.AddSound(this);
  39087. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  39088. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  39089. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  39090. }
  39091. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  39092. if (this._readyToPlayCallback) {
  39093. window.setTimeout(function () {
  39094. _this._readyToPlayCallback();
  39095. }, 1000);
  39096. }
  39097. }
  39098. }
  39099. Sound.prototype.dispose = function () {
  39100. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  39101. if (this.isPlaying) {
  39102. this.stop();
  39103. }
  39104. this._isReadyToPlay = false;
  39105. if (this.soundTrackId === -1) {
  39106. this._scene.mainSoundTrack.RemoveSound(this);
  39107. }
  39108. else {
  39109. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  39110. }
  39111. if (this._soundGain) {
  39112. this._soundGain.disconnect();
  39113. this._soundGain = null;
  39114. }
  39115. if (this._soundPanner) {
  39116. this._soundPanner.disconnect();
  39117. this._soundPanner = null;
  39118. }
  39119. if (this._soundSource) {
  39120. this._soundSource.disconnect();
  39121. this._soundSource = null;
  39122. }
  39123. this._audioBuffer = null;
  39124. if (this._htmlAudioElement) {
  39125. this._htmlAudioElement.pause();
  39126. this._htmlAudioElement.src = "";
  39127. document.body.removeChild(this._htmlAudioElement);
  39128. }
  39129. if (this._connectedMesh) {
  39130. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39131. this._connectedMesh = null;
  39132. }
  39133. }
  39134. };
  39135. Sound.prototype.isReady = function () {
  39136. return this._isReadyToPlay;
  39137. };
  39138. Sound.prototype._soundLoaded = function (audioData) {
  39139. var _this = this;
  39140. this._isLoaded = true;
  39141. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  39142. _this._audioBuffer = buffer;
  39143. _this._isReadyToPlay = true;
  39144. if (_this.autoplay) {
  39145. _this.play();
  39146. }
  39147. if (_this._readyToPlayCallback) {
  39148. _this._readyToPlayCallback();
  39149. }
  39150. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  39151. };
  39152. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  39153. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39154. this._audioBuffer = audioBuffer;
  39155. this._isReadyToPlay = true;
  39156. }
  39157. };
  39158. Sound.prototype.updateOptions = function (options) {
  39159. if (options) {
  39160. this.loop = options.loop || this.loop;
  39161. this.maxDistance = options.maxDistance || this.maxDistance;
  39162. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  39163. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  39164. this.refDistance = options.refDistance || this.refDistance;
  39165. this.distanceModel = options.distanceModel || this.distanceModel;
  39166. this._playbackRate = options.playbackRate || this._playbackRate;
  39167. this._updateSpatialParameters();
  39168. if (this.isPlaying) {
  39169. if (this._streaming) {
  39170. this._htmlAudioElement.playbackRate = this._playbackRate;
  39171. }
  39172. else {
  39173. this._soundSource.playbackRate.value = this._playbackRate;
  39174. }
  39175. }
  39176. }
  39177. };
  39178. Sound.prototype._createSpatialParameters = function () {
  39179. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39180. if (this._scene.headphone) {
  39181. this._panningModel = "HRTF";
  39182. }
  39183. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  39184. this._updateSpatialParameters();
  39185. this._soundPanner.connect(this._ouputAudioNode);
  39186. this._inputAudioNode = this._soundPanner;
  39187. }
  39188. };
  39189. Sound.prototype._updateSpatialParameters = function () {
  39190. if (this.spatialSound) {
  39191. if (this.useCustomAttenuation) {
  39192. // Tricks to disable in a way embedded Web Audio attenuation
  39193. this._soundPanner.distanceModel = "linear";
  39194. this._soundPanner.maxDistance = Number.MAX_VALUE;
  39195. this._soundPanner.refDistance = 1;
  39196. this._soundPanner.rolloffFactor = 1;
  39197. this._soundPanner.panningModel = this._panningModel;
  39198. }
  39199. else {
  39200. this._soundPanner.distanceModel = this.distanceModel;
  39201. this._soundPanner.maxDistance = this.maxDistance;
  39202. this._soundPanner.refDistance = this.refDistance;
  39203. this._soundPanner.rolloffFactor = this.rolloffFactor;
  39204. this._soundPanner.panningModel = this._panningModel;
  39205. }
  39206. }
  39207. };
  39208. Sound.prototype.switchPanningModelToHRTF = function () {
  39209. this._panningModel = "HRTF";
  39210. this._switchPanningModel();
  39211. };
  39212. Sound.prototype.switchPanningModelToEqualPower = function () {
  39213. this._panningModel = "equalpower";
  39214. this._switchPanningModel();
  39215. };
  39216. Sound.prototype._switchPanningModel = function () {
  39217. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  39218. this._soundPanner.panningModel = this._panningModel;
  39219. }
  39220. };
  39221. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  39222. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39223. if (this._isOutputConnected) {
  39224. this._ouputAudioNode.disconnect();
  39225. }
  39226. this._ouputAudioNode.connect(soundTrackAudioNode);
  39227. this._isOutputConnected = true;
  39228. }
  39229. };
  39230. /**
  39231. * Transform this sound into a directional source
  39232. * @param coneInnerAngle Size of the inner cone in degree
  39233. * @param coneOuterAngle Size of the outer cone in degree
  39234. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  39235. */
  39236. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  39237. if (coneOuterAngle < coneInnerAngle) {
  39238. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  39239. return;
  39240. }
  39241. this._coneInnerAngle = coneInnerAngle;
  39242. this._coneOuterAngle = coneOuterAngle;
  39243. this._coneOuterGain = coneOuterGain;
  39244. this._isDirectional = true;
  39245. if (this.isPlaying && this.loop) {
  39246. this.stop();
  39247. this.play();
  39248. }
  39249. };
  39250. Sound.prototype.setPosition = function (newPosition) {
  39251. this._position = newPosition;
  39252. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  39253. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  39254. }
  39255. };
  39256. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  39257. this._localDirection = newLocalDirection;
  39258. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  39259. this._updateDirection();
  39260. }
  39261. };
  39262. Sound.prototype._updateDirection = function () {
  39263. var mat = this._connectedMesh.getWorldMatrix();
  39264. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  39265. direction.normalize();
  39266. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  39267. };
  39268. Sound.prototype.updateDistanceFromListener = function () {
  39269. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  39270. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  39271. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  39272. }
  39273. };
  39274. Sound.prototype.setAttenuationFunction = function (callback) {
  39275. this._customAttenuationFunction = callback;
  39276. };
  39277. /**
  39278. * Play the sound
  39279. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  39280. * @param offset (optional) Start the sound setting it at a specific time
  39281. */
  39282. Sound.prototype.play = function (time, offset) {
  39283. var _this = this;
  39284. if (this._isReadyToPlay && this._scene.audioEnabled) {
  39285. try {
  39286. if (this._startOffset < 0) {
  39287. time = -this._startOffset;
  39288. this._startOffset = 0;
  39289. }
  39290. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  39291. if (!this._soundSource || !this._streamingSource) {
  39292. if (this.spatialSound) {
  39293. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  39294. if (this._isDirectional) {
  39295. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  39296. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  39297. this._soundPanner.coneOuterGain = this._coneOuterGain;
  39298. if (this._connectedMesh) {
  39299. this._updateDirection();
  39300. }
  39301. else {
  39302. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  39303. }
  39304. }
  39305. }
  39306. }
  39307. if (this._streaming) {
  39308. if (!this._streamingSource) {
  39309. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  39310. this._htmlAudioElement.onended = function () { _this._onended(); };
  39311. this._htmlAudioElement.playbackRate = this._playbackRate;
  39312. }
  39313. this._streamingSource.disconnect();
  39314. this._streamingSource.connect(this._inputAudioNode);
  39315. this._htmlAudioElement.play();
  39316. }
  39317. else {
  39318. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  39319. this._soundSource.buffer = this._audioBuffer;
  39320. this._soundSource.connect(this._inputAudioNode);
  39321. this._soundSource.loop = this.loop;
  39322. this._soundSource.playbackRate.value = this._playbackRate;
  39323. this._soundSource.onended = function () { _this._onended(); };
  39324. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  39325. }
  39326. this._startTime = startTime;
  39327. this.isPlaying = true;
  39328. this.isPaused = false;
  39329. }
  39330. catch (ex) {
  39331. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  39332. }
  39333. }
  39334. };
  39335. Sound.prototype._onended = function () {
  39336. this.isPlaying = false;
  39337. if (this.onended) {
  39338. this.onended();
  39339. }
  39340. };
  39341. /**
  39342. * Stop the sound
  39343. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  39344. */
  39345. Sound.prototype.stop = function (time) {
  39346. if (this.isPlaying) {
  39347. if (this._streaming) {
  39348. this._htmlAudioElement.pause();
  39349. // Test needed for Firefox or it will generate an Invalid State Error
  39350. if (this._htmlAudioElement.currentTime > 0) {
  39351. this._htmlAudioElement.currentTime = 0;
  39352. }
  39353. }
  39354. else {
  39355. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  39356. this._soundSource.stop(stopTime);
  39357. this._soundSource.onended = null;
  39358. if (!this.isPaused) {
  39359. this._startOffset = 0;
  39360. }
  39361. }
  39362. this.isPlaying = false;
  39363. }
  39364. };
  39365. Sound.prototype.pause = function () {
  39366. if (this.isPlaying) {
  39367. this.isPaused = true;
  39368. if (this._streaming) {
  39369. this._htmlAudioElement.pause();
  39370. }
  39371. else {
  39372. this.stop(0);
  39373. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  39374. }
  39375. }
  39376. };
  39377. Sound.prototype.setVolume = function (newVolume, time) {
  39378. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39379. if (time) {
  39380. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  39381. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  39382. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  39383. }
  39384. else {
  39385. this._soundGain.gain.value = newVolume;
  39386. }
  39387. }
  39388. this._volume = newVolume;
  39389. };
  39390. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  39391. this._playbackRate = newPlaybackRate;
  39392. if (this.isPlaying) {
  39393. if (this._streaming) {
  39394. this._htmlAudioElement.playbackRate = this._playbackRate;
  39395. }
  39396. else {
  39397. this._soundSource.playbackRate.value = this._playbackRate;
  39398. }
  39399. }
  39400. };
  39401. Sound.prototype.getVolume = function () {
  39402. return this._volume;
  39403. };
  39404. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  39405. var _this = this;
  39406. if (this._connectedMesh) {
  39407. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39408. this._registerFunc = null;
  39409. }
  39410. this._connectedMesh = meshToConnectTo;
  39411. if (!this.spatialSound) {
  39412. this.spatialSound = true;
  39413. this._createSpatialParameters();
  39414. if (this.isPlaying && this.loop) {
  39415. this.stop();
  39416. this.play();
  39417. }
  39418. }
  39419. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  39420. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  39421. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  39422. };
  39423. Sound.prototype.detachFromMesh = function () {
  39424. if (this._connectedMesh) {
  39425. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39426. this._registerFunc = null;
  39427. this._connectedMesh = null;
  39428. }
  39429. };
  39430. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  39431. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  39432. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  39433. this._updateDirection();
  39434. }
  39435. };
  39436. Sound.prototype.clone = function () {
  39437. var _this = this;
  39438. if (!this._streaming) {
  39439. var setBufferAndRun = function () {
  39440. if (_this._isReadyToPlay) {
  39441. clonedSound._audioBuffer = _this.getAudioBuffer();
  39442. clonedSound._isReadyToPlay = true;
  39443. if (clonedSound.autoplay) {
  39444. clonedSound.play();
  39445. }
  39446. }
  39447. else {
  39448. window.setTimeout(setBufferAndRun, 300);
  39449. }
  39450. };
  39451. var currentOptions = {
  39452. autoplay: this.autoplay, loop: this.loop,
  39453. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  39454. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  39455. refDistance: this.refDistance, distanceModel: this.distanceModel
  39456. };
  39457. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  39458. if (this.useCustomAttenuation) {
  39459. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  39460. }
  39461. clonedSound.setPosition(this._position);
  39462. clonedSound.setPlaybackRate(this._playbackRate);
  39463. setBufferAndRun();
  39464. return clonedSound;
  39465. }
  39466. else {
  39467. return null;
  39468. }
  39469. };
  39470. Sound.prototype.getAudioBuffer = function () {
  39471. return this._audioBuffer;
  39472. };
  39473. Sound.prototype.serialize = function () {
  39474. var serializationObject = {
  39475. name: this.name,
  39476. url: this.name,
  39477. autoplay: this.autoplay,
  39478. loop: this.loop,
  39479. volume: this._volume,
  39480. spatialSound: this.spatialSound,
  39481. maxDistance: this.maxDistance,
  39482. rolloffFactor: this.rolloffFactor,
  39483. refDistance: this.refDistance,
  39484. distanceModel: this.distanceModel,
  39485. playbackRate: this._playbackRate,
  39486. panningModel: this._panningModel,
  39487. soundTrackId: this.soundTrackId
  39488. };
  39489. if (this.spatialSound) {
  39490. if (this._connectedMesh)
  39491. serializationObject.connectedMeshId = this._connectedMesh.id;
  39492. serializationObject.position = this._position.asArray();
  39493. serializationObject.refDistance = this.refDistance;
  39494. serializationObject.distanceModel = this.distanceModel;
  39495. serializationObject.isDirectional = this._isDirectional;
  39496. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  39497. serializationObject.coneInnerAngle = this._coneInnerAngle;
  39498. serializationObject.coneOuterAngle = this._coneOuterAngle;
  39499. serializationObject.coneOuterGain = this._coneOuterGain;
  39500. }
  39501. return serializationObject;
  39502. };
  39503. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  39504. var soundName = parsedSound.name;
  39505. var soundUrl;
  39506. if (parsedSound.url) {
  39507. soundUrl = rootUrl + parsedSound.url;
  39508. }
  39509. else {
  39510. soundUrl = rootUrl + soundName;
  39511. }
  39512. var options = {
  39513. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  39514. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  39515. rolloffFactor: parsedSound.rolloffFactor,
  39516. refDistance: parsedSound.refDistance,
  39517. distanceModel: parsedSound.distanceModel,
  39518. playbackRate: parsedSound.playbackRate
  39519. };
  39520. var newSound;
  39521. if (!sourceSound) {
  39522. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  39523. scene._addPendingData(newSound);
  39524. }
  39525. else {
  39526. var setBufferAndRun = function () {
  39527. if (sourceSound._isReadyToPlay) {
  39528. newSound._audioBuffer = sourceSound.getAudioBuffer();
  39529. newSound._isReadyToPlay = true;
  39530. if (newSound.autoplay) {
  39531. newSound.play();
  39532. }
  39533. }
  39534. else {
  39535. window.setTimeout(setBufferAndRun, 300);
  39536. }
  39537. };
  39538. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  39539. setBufferAndRun();
  39540. }
  39541. if (parsedSound.position) {
  39542. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  39543. newSound.setPosition(soundPosition);
  39544. }
  39545. if (parsedSound.isDirectional) {
  39546. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  39547. if (parsedSound.localDirectionToMesh) {
  39548. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  39549. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  39550. }
  39551. }
  39552. if (parsedSound.connectedMeshId) {
  39553. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  39554. if (connectedMesh) {
  39555. newSound.attachToMesh(connectedMesh);
  39556. }
  39557. }
  39558. return newSound;
  39559. };
  39560. return Sound;
  39561. }());
  39562. BABYLON.Sound = Sound;
  39563. })(BABYLON || (BABYLON = {}));
  39564. //# sourceMappingURL=babylon.sound.js.map
  39565. var BABYLON;
  39566. (function (BABYLON) {
  39567. var SoundTrack = (function () {
  39568. function SoundTrack(scene, options) {
  39569. this.id = -1;
  39570. this._isMainTrack = false;
  39571. this._isInitialized = false;
  39572. this._scene = scene;
  39573. this.soundCollection = new Array();
  39574. this._options = options;
  39575. if (!this._isMainTrack) {
  39576. this._scene.soundTracks.push(this);
  39577. this.id = this._scene.soundTracks.length - 1;
  39578. }
  39579. }
  39580. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  39581. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39582. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  39583. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  39584. if (this._options) {
  39585. if (this._options.volume) {
  39586. this._outputAudioNode.gain.value = this._options.volume;
  39587. }
  39588. if (this._options.mainTrack) {
  39589. this._isMainTrack = this._options.mainTrack;
  39590. }
  39591. }
  39592. this._isInitialized = true;
  39593. }
  39594. };
  39595. SoundTrack.prototype.dispose = function () {
  39596. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39597. if (this._connectedAnalyser) {
  39598. this._connectedAnalyser.stopDebugCanvas();
  39599. }
  39600. while (this.soundCollection.length) {
  39601. this.soundCollection[0].dispose();
  39602. }
  39603. if (this._outputAudioNode) {
  39604. this._outputAudioNode.disconnect();
  39605. }
  39606. this._outputAudioNode = null;
  39607. }
  39608. };
  39609. SoundTrack.prototype.AddSound = function (sound) {
  39610. if (!this._isInitialized) {
  39611. this._initializeSoundTrackAudioGraph();
  39612. }
  39613. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39614. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  39615. }
  39616. if (sound.soundTrackId) {
  39617. if (sound.soundTrackId === -1) {
  39618. this._scene.mainSoundTrack.RemoveSound(sound);
  39619. }
  39620. else {
  39621. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  39622. }
  39623. }
  39624. this.soundCollection.push(sound);
  39625. sound.soundTrackId = this.id;
  39626. };
  39627. SoundTrack.prototype.RemoveSound = function (sound) {
  39628. var index = this.soundCollection.indexOf(sound);
  39629. if (index !== -1) {
  39630. this.soundCollection.splice(index, 1);
  39631. }
  39632. };
  39633. SoundTrack.prototype.setVolume = function (newVolume) {
  39634. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39635. this._outputAudioNode.gain.value = newVolume;
  39636. }
  39637. };
  39638. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  39639. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39640. for (var i = 0; i < this.soundCollection.length; i++) {
  39641. this.soundCollection[i].switchPanningModelToHRTF();
  39642. }
  39643. }
  39644. };
  39645. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  39646. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39647. for (var i = 0; i < this.soundCollection.length; i++) {
  39648. this.soundCollection[i].switchPanningModelToEqualPower();
  39649. }
  39650. }
  39651. };
  39652. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  39653. if (this._connectedAnalyser) {
  39654. this._connectedAnalyser.stopDebugCanvas();
  39655. }
  39656. this._connectedAnalyser = analyser;
  39657. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39658. this._outputAudioNode.disconnect();
  39659. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  39660. }
  39661. };
  39662. return SoundTrack;
  39663. }());
  39664. BABYLON.SoundTrack = SoundTrack;
  39665. })(BABYLON || (BABYLON = {}));
  39666. //# sourceMappingURL=babylon.soundtrack.js.map
  39667. var BABYLON;
  39668. (function (BABYLON) {
  39669. var Analyser = (function () {
  39670. function Analyser(scene) {
  39671. this.SMOOTHING = 0.75;
  39672. this.FFT_SIZE = 512;
  39673. this.BARGRAPHAMPLITUDE = 256;
  39674. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  39675. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  39676. this._scene = scene;
  39677. this._audioEngine = BABYLON.Engine.audioEngine;
  39678. if (this._audioEngine.canUseWebAudio) {
  39679. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  39680. this._webAudioAnalyser.minDecibels = -140;
  39681. this._webAudioAnalyser.maxDecibels = 0;
  39682. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39683. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39684. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  39685. }
  39686. }
  39687. Analyser.prototype.getFrequencyBinCount = function () {
  39688. if (this._audioEngine.canUseWebAudio) {
  39689. return this._webAudioAnalyser.frequencyBinCount;
  39690. }
  39691. else {
  39692. return 0;
  39693. }
  39694. };
  39695. Analyser.prototype.getByteFrequencyData = function () {
  39696. if (this._audioEngine.canUseWebAudio) {
  39697. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39698. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39699. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  39700. }
  39701. return this._byteFreqs;
  39702. };
  39703. Analyser.prototype.getByteTimeDomainData = function () {
  39704. if (this._audioEngine.canUseWebAudio) {
  39705. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39706. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39707. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  39708. }
  39709. return this._byteTime;
  39710. };
  39711. Analyser.prototype.getFloatFrequencyData = function () {
  39712. if (this._audioEngine.canUseWebAudio) {
  39713. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39714. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39715. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  39716. }
  39717. return this._floatFreqs;
  39718. };
  39719. Analyser.prototype.drawDebugCanvas = function () {
  39720. var _this = this;
  39721. if (this._audioEngine.canUseWebAudio) {
  39722. if (!this._debugCanvas) {
  39723. this._debugCanvas = document.createElement("canvas");
  39724. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  39725. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  39726. this._debugCanvas.style.position = "absolute";
  39727. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  39728. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  39729. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  39730. document.body.appendChild(this._debugCanvas);
  39731. this._registerFunc = function () {
  39732. _this.drawDebugCanvas();
  39733. };
  39734. this._scene.registerBeforeRender(this._registerFunc);
  39735. }
  39736. if (this._registerFunc) {
  39737. var workingArray = this.getByteFrequencyData();
  39738. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  39739. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  39740. // Draw the frequency domain chart.
  39741. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  39742. var value = workingArray[i];
  39743. var percent = value / this.BARGRAPHAMPLITUDE;
  39744. var height = this.DEBUGCANVASSIZE.height * percent;
  39745. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  39746. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  39747. var hue = i / this.getFrequencyBinCount() * 360;
  39748. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  39749. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  39750. }
  39751. }
  39752. }
  39753. };
  39754. Analyser.prototype.stopDebugCanvas = function () {
  39755. if (this._debugCanvas) {
  39756. this._scene.unregisterBeforeRender(this._registerFunc);
  39757. this._registerFunc = null;
  39758. document.body.removeChild(this._debugCanvas);
  39759. this._debugCanvas = null;
  39760. this._debugCanvasContext = null;
  39761. }
  39762. };
  39763. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  39764. if (this._audioEngine.canUseWebAudio) {
  39765. inputAudioNode.connect(this._webAudioAnalyser);
  39766. this._webAudioAnalyser.connect(outputAudioNode);
  39767. }
  39768. };
  39769. Analyser.prototype.dispose = function () {
  39770. if (this._audioEngine.canUseWebAudio) {
  39771. this._webAudioAnalyser.disconnect();
  39772. }
  39773. };
  39774. return Analyser;
  39775. }());
  39776. BABYLON.Analyser = Analyser;
  39777. })(BABYLON || (BABYLON = {}));
  39778. //# sourceMappingURL=babylon.analyser.js.map
  39779. var BABYLON;
  39780. (function (BABYLON) {
  39781. var CubeTexture = (function (_super) {
  39782. __extends(CubeTexture, _super);
  39783. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  39784. if (onLoad === void 0) { onLoad = null; }
  39785. if (onError === void 0) { onError = null; }
  39786. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  39787. var _this = _super.call(this, scene) || this;
  39788. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  39789. _this.name = rootUrl;
  39790. _this.url = rootUrl;
  39791. _this._noMipmap = noMipmap;
  39792. _this.hasAlpha = false;
  39793. _this._format = format;
  39794. if (!rootUrl && !files) {
  39795. return _this;
  39796. }
  39797. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  39798. if (!files) {
  39799. if (!extensions) {
  39800. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  39801. }
  39802. files = [];
  39803. for (var index = 0; index < extensions.length; index++) {
  39804. files.push(rootUrl + extensions[index]);
  39805. }
  39806. _this._extensions = extensions;
  39807. }
  39808. _this._files = files;
  39809. if (!_this._texture) {
  39810. if (!scene.useDelayedTextureLoading) {
  39811. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  39812. }
  39813. else {
  39814. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39815. }
  39816. }
  39817. else if (onLoad) {
  39818. if (_this._texture.isReady) {
  39819. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  39820. }
  39821. else {
  39822. _this._texture.onLoadedCallbacks.push(onLoad);
  39823. }
  39824. }
  39825. _this.isCube = true;
  39826. _this._textureMatrix = BABYLON.Matrix.Identity();
  39827. return _this;
  39828. }
  39829. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  39830. return new CubeTexture("", scene, null, noMipmap, files);
  39831. };
  39832. // Methods
  39833. CubeTexture.prototype.delayLoad = function () {
  39834. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  39835. return;
  39836. }
  39837. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39838. this._texture = this._getFromCache(this.url, this._noMipmap);
  39839. if (!this._texture) {
  39840. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  39841. }
  39842. };
  39843. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  39844. return this._textureMatrix;
  39845. };
  39846. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  39847. var texture = BABYLON.SerializationHelper.Parse(function () {
  39848. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  39849. }, parsedTexture, scene);
  39850. // Animations
  39851. if (parsedTexture.animations) {
  39852. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  39853. var parsedAnimation = parsedTexture.animations[animationIndex];
  39854. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  39855. }
  39856. }
  39857. return texture;
  39858. };
  39859. CubeTexture.prototype.clone = function () {
  39860. var _this = this;
  39861. return BABYLON.SerializationHelper.Clone(function () {
  39862. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  39863. }, this);
  39864. };
  39865. return CubeTexture;
  39866. }(BABYLON.BaseTexture));
  39867. BABYLON.CubeTexture = CubeTexture;
  39868. })(BABYLON || (BABYLON = {}));
  39869. //# sourceMappingURL=babylon.cubeTexture.js.map
  39870. var BABYLON;
  39871. (function (BABYLON) {
  39872. var RenderTargetTexture = (function (_super) {
  39873. __extends(RenderTargetTexture, _super);
  39874. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  39875. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  39876. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  39877. if (isCube === void 0) { isCube = false; }
  39878. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39879. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  39880. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  39881. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  39882. _this.isCube = isCube;
  39883. /**
  39884. * Use this list to define the list of mesh you want to render.
  39885. */
  39886. _this.renderList = new Array();
  39887. _this.renderParticles = true;
  39888. _this.renderSprites = false;
  39889. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  39890. // Events
  39891. /**
  39892. * An event triggered when the texture is unbind.
  39893. * @type {BABYLON.Observable}
  39894. */
  39895. _this.onAfterUnbindObservable = new BABYLON.Observable();
  39896. /**
  39897. * An event triggered before rendering the texture
  39898. * @type {BABYLON.Observable}
  39899. */
  39900. _this.onBeforeRenderObservable = new BABYLON.Observable();
  39901. /**
  39902. * An event triggered after rendering the texture
  39903. * @type {BABYLON.Observable}
  39904. */
  39905. _this.onAfterRenderObservable = new BABYLON.Observable();
  39906. /**
  39907. * An event triggered after the texture clear
  39908. * @type {BABYLON.Observable}
  39909. */
  39910. _this.onClearObservable = new BABYLON.Observable();
  39911. _this._currentRefreshId = -1;
  39912. _this._refreshRate = 1;
  39913. _this._samples = 1;
  39914. _this.name = name;
  39915. _this.isRenderTarget = true;
  39916. _this._size = size;
  39917. _this._generateMipMaps = generateMipMaps;
  39918. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  39919. _this._renderTargetOptions = {
  39920. generateMipMaps: generateMipMaps,
  39921. type: type,
  39922. samplingMode: samplingMode,
  39923. generateDepthBuffer: generateDepthBuffer,
  39924. generateStencilBuffer: generateStencilBuffer
  39925. };
  39926. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  39927. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39928. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39929. }
  39930. if (isCube) {
  39931. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  39932. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  39933. _this._textureMatrix = BABYLON.Matrix.Identity();
  39934. }
  39935. else {
  39936. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  39937. }
  39938. // Rendering groups
  39939. _this._renderingManager = new BABYLON.RenderingManager(scene);
  39940. return _this;
  39941. }
  39942. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  39943. get: function () {
  39944. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  39945. },
  39946. enumerable: true,
  39947. configurable: true
  39948. });
  39949. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  39950. get: function () {
  39951. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  39952. },
  39953. enumerable: true,
  39954. configurable: true
  39955. });
  39956. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  39957. get: function () {
  39958. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  39959. },
  39960. enumerable: true,
  39961. configurable: true
  39962. });
  39963. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  39964. set: function (callback) {
  39965. if (this._onAfterUnbindObserver) {
  39966. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  39967. }
  39968. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  39969. },
  39970. enumerable: true,
  39971. configurable: true
  39972. });
  39973. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  39974. set: function (callback) {
  39975. if (this._onBeforeRenderObserver) {
  39976. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  39977. }
  39978. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  39979. },
  39980. enumerable: true,
  39981. configurable: true
  39982. });
  39983. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  39984. set: function (callback) {
  39985. if (this._onAfterRenderObserver) {
  39986. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  39987. }
  39988. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  39989. },
  39990. enumerable: true,
  39991. configurable: true
  39992. });
  39993. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  39994. set: function (callback) {
  39995. if (this._onClearObserver) {
  39996. this.onClearObservable.remove(this._onClearObserver);
  39997. }
  39998. this._onClearObserver = this.onClearObservable.add(callback);
  39999. },
  40000. enumerable: true,
  40001. configurable: true
  40002. });
  40003. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  40004. get: function () {
  40005. return this._samples;
  40006. },
  40007. set: function (value) {
  40008. if (this._samples === value) {
  40009. return;
  40010. }
  40011. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  40012. },
  40013. enumerable: true,
  40014. configurable: true
  40015. });
  40016. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  40017. this._currentRefreshId = -1;
  40018. };
  40019. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  40020. get: function () {
  40021. return this._refreshRate;
  40022. },
  40023. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  40024. set: function (value) {
  40025. this._refreshRate = value;
  40026. this.resetRefreshCounter();
  40027. },
  40028. enumerable: true,
  40029. configurable: true
  40030. });
  40031. RenderTargetTexture.prototype._shouldRender = function () {
  40032. if (this._currentRefreshId === -1) {
  40033. this._currentRefreshId = 1;
  40034. return true;
  40035. }
  40036. if (this.refreshRate === this._currentRefreshId) {
  40037. this._currentRefreshId = 1;
  40038. return true;
  40039. }
  40040. this._currentRefreshId++;
  40041. return false;
  40042. };
  40043. RenderTargetTexture.prototype.isReady = function () {
  40044. if (!this.getScene().renderTargetsEnabled) {
  40045. return false;
  40046. }
  40047. return _super.prototype.isReady.call(this);
  40048. };
  40049. RenderTargetTexture.prototype.getRenderSize = function () {
  40050. return this._size;
  40051. };
  40052. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  40053. get: function () {
  40054. return true;
  40055. },
  40056. enumerable: true,
  40057. configurable: true
  40058. });
  40059. RenderTargetTexture.prototype.scale = function (ratio) {
  40060. var newSize = this._size * ratio;
  40061. this.resize(newSize);
  40062. };
  40063. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  40064. if (this.isCube) {
  40065. return this._textureMatrix;
  40066. }
  40067. return _super.prototype.getReflectionTextureMatrix.call(this);
  40068. };
  40069. RenderTargetTexture.prototype.resize = function (size) {
  40070. this.releaseInternalTexture();
  40071. if (this.isCube) {
  40072. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  40073. }
  40074. else {
  40075. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  40076. }
  40077. };
  40078. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  40079. var scene = this.getScene();
  40080. var engine = scene.getEngine();
  40081. if (this.useCameraPostProcesses !== undefined) {
  40082. useCameraPostProcess = this.useCameraPostProcesses;
  40083. }
  40084. if (this._waitingRenderList) {
  40085. this.renderList = [];
  40086. for (var index = 0; index < this._waitingRenderList.length; index++) {
  40087. var id = this._waitingRenderList[index];
  40088. this.renderList.push(scene.getMeshByID(id));
  40089. }
  40090. delete this._waitingRenderList;
  40091. }
  40092. // Is predicate defined?
  40093. if (this.renderListPredicate) {
  40094. this.renderList.splice(0); // Clear previous renderList
  40095. var sceneMeshes = this.getScene().meshes;
  40096. for (var index = 0; index < sceneMeshes.length; index++) {
  40097. var mesh = sceneMeshes[index];
  40098. if (this.renderListPredicate(mesh)) {
  40099. this.renderList.push(mesh);
  40100. }
  40101. }
  40102. }
  40103. if (this.renderList && this.renderList.length === 0) {
  40104. return;
  40105. }
  40106. // Set custom projection.
  40107. // Needs to be before binding to prevent changing the aspect ratio.
  40108. if (this.activeCamera) {
  40109. engine.setViewport(this.activeCamera.viewport);
  40110. if (this.activeCamera !== scene.activeCamera) {
  40111. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  40112. }
  40113. }
  40114. else {
  40115. engine.setViewport(scene.activeCamera.viewport);
  40116. }
  40117. // Prepare renderingManager
  40118. this._renderingManager.reset();
  40119. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  40120. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  40121. var sceneRenderId = scene.getRenderId();
  40122. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  40123. var mesh = currentRenderList[meshIndex];
  40124. if (mesh) {
  40125. if (!mesh.isReady()) {
  40126. // Reset _currentRefreshId
  40127. this.resetRefreshCounter();
  40128. continue;
  40129. }
  40130. mesh._preActivateForIntermediateRendering(sceneRenderId);
  40131. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  40132. mesh._activate(sceneRenderId);
  40133. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40134. var subMesh = mesh.subMeshes[subIndex];
  40135. scene._activeIndices.addCount(subMesh.indexCount, false);
  40136. this._renderingManager.dispatch(subMesh);
  40137. }
  40138. }
  40139. }
  40140. }
  40141. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  40142. var particleSystem = scene.particleSystems[particleIndex];
  40143. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  40144. continue;
  40145. }
  40146. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  40147. this._renderingManager.dispatchParticles(particleSystem);
  40148. }
  40149. }
  40150. if (this.isCube) {
  40151. for (var face = 0; face < 6; face++) {
  40152. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  40153. scene.incrementRenderId();
  40154. scene.resetCachedMaterial();
  40155. }
  40156. }
  40157. else {
  40158. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  40159. }
  40160. this.onAfterUnbindObservable.notifyObservers(this);
  40161. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  40162. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  40163. }
  40164. engine.setViewport(scene.activeCamera.viewport);
  40165. scene.resetCachedMaterial();
  40166. };
  40167. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  40168. var _this = this;
  40169. var scene = this.getScene();
  40170. var engine = scene.getEngine();
  40171. // Bind
  40172. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  40173. if (this.isCube) {
  40174. engine.bindFramebuffer(this._texture, faceIndex);
  40175. }
  40176. else {
  40177. engine.bindFramebuffer(this._texture);
  40178. }
  40179. }
  40180. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  40181. // Clear
  40182. if (this.onClearObservable.hasObservers()) {
  40183. this.onClearObservable.notifyObservers(engine);
  40184. }
  40185. else {
  40186. engine.clear(scene.clearColor, true, true, true);
  40187. }
  40188. if (!this._doNotChangeAspectRatio) {
  40189. scene.updateTransformMatrix(true);
  40190. }
  40191. // Render
  40192. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  40193. if (useCameraPostProcess) {
  40194. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  40195. }
  40196. if (!this._doNotChangeAspectRatio) {
  40197. scene.updateTransformMatrix(true);
  40198. }
  40199. // Dump ?
  40200. if (dumpForDebug) {
  40201. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  40202. }
  40203. // Unbind
  40204. if (!this.isCube || faceIndex === 5) {
  40205. if (this.isCube) {
  40206. if (faceIndex === 5) {
  40207. engine.generateMipMapsForCubemap(this._texture);
  40208. }
  40209. }
  40210. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  40211. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  40212. });
  40213. }
  40214. else {
  40215. this.onAfterRenderObservable.notifyObservers(faceIndex);
  40216. }
  40217. };
  40218. /**
  40219. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  40220. * This allowed control for front to back rendering or reversly depending of the special needs.
  40221. *
  40222. * @param renderingGroupId The rendering group id corresponding to its index
  40223. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  40224. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  40225. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  40226. */
  40227. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  40228. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  40229. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  40230. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  40231. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  40232. };
  40233. /**
  40234. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  40235. *
  40236. * @param renderingGroupId The rendering group id corresponding to its index
  40237. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  40238. */
  40239. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  40240. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  40241. };
  40242. RenderTargetTexture.prototype.clone = function () {
  40243. var textureSize = this.getSize();
  40244. 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);
  40245. // Base texture
  40246. newTexture.hasAlpha = this.hasAlpha;
  40247. newTexture.level = this.level;
  40248. // RenderTarget Texture
  40249. newTexture.coordinatesMode = this.coordinatesMode;
  40250. newTexture.renderList = this.renderList.slice(0);
  40251. return newTexture;
  40252. };
  40253. RenderTargetTexture.prototype.serialize = function () {
  40254. if (!this.name) {
  40255. return null;
  40256. }
  40257. var serializationObject = _super.prototype.serialize.call(this);
  40258. serializationObject.renderTargetSize = this.getRenderSize();
  40259. serializationObject.renderList = [];
  40260. for (var index = 0; index < this.renderList.length; index++) {
  40261. serializationObject.renderList.push(this.renderList[index].id);
  40262. }
  40263. return serializationObject;
  40264. };
  40265. return RenderTargetTexture;
  40266. }(BABYLON.Texture));
  40267. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  40268. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  40269. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  40270. BABYLON.RenderTargetTexture = RenderTargetTexture;
  40271. })(BABYLON || (BABYLON = {}));
  40272. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  40273. /// <reference path="babylon.renderTargetTexture.ts" />
  40274. var BABYLON;
  40275. (function (BABYLON) {
  40276. var MirrorTexture = (function (_super) {
  40277. __extends(MirrorTexture, _super);
  40278. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  40279. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40280. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40281. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  40282. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  40283. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  40284. _this._transformMatrix = BABYLON.Matrix.Zero();
  40285. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  40286. _this.onBeforeRenderObservable.add(function () {
  40287. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  40288. _this._savedViewMatrix = scene.getViewMatrix();
  40289. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  40290. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  40291. scene.clipPlane = _this.mirrorPlane;
  40292. scene.getEngine().cullBackFaces = false;
  40293. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  40294. });
  40295. _this.onAfterRenderObservable.add(function () {
  40296. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  40297. scene.getEngine().cullBackFaces = true;
  40298. scene._mirroredCameraPosition = null;
  40299. delete scene.clipPlane;
  40300. });
  40301. return _this;
  40302. }
  40303. MirrorTexture.prototype.clone = function () {
  40304. var textureSize = this.getSize();
  40305. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  40306. // Base texture
  40307. newTexture.hasAlpha = this.hasAlpha;
  40308. newTexture.level = this.level;
  40309. // Mirror Texture
  40310. newTexture.mirrorPlane = this.mirrorPlane.clone();
  40311. newTexture.renderList = this.renderList.slice(0);
  40312. return newTexture;
  40313. };
  40314. MirrorTexture.prototype.serialize = function () {
  40315. if (!this.name) {
  40316. return null;
  40317. }
  40318. var serializationObject = _super.prototype.serialize.call(this);
  40319. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  40320. return serializationObject;
  40321. };
  40322. return MirrorTexture;
  40323. }(BABYLON.RenderTargetTexture));
  40324. BABYLON.MirrorTexture = MirrorTexture;
  40325. })(BABYLON || (BABYLON = {}));
  40326. //# sourceMappingURL=babylon.mirrorTexture.js.map
  40327. /// <reference path="babylon.renderTargetTexture.ts" />
  40328. var BABYLON;
  40329. (function (BABYLON) {
  40330. /**
  40331. * Creates a refraction texture used by refraction channel of the standard material.
  40332. * @param name the texture name
  40333. * @param size size of the underlying texture
  40334. * @param scene root scene
  40335. */
  40336. var RefractionTexture = (function (_super) {
  40337. __extends(RefractionTexture, _super);
  40338. function RefractionTexture(name, size, scene, generateMipMaps) {
  40339. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  40340. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  40341. _this.depth = 2.0;
  40342. _this.onBeforeRenderObservable.add(function () {
  40343. scene.clipPlane = _this.refractionPlane;
  40344. });
  40345. _this.onAfterRenderObservable.add(function () {
  40346. delete scene.clipPlane;
  40347. });
  40348. return _this;
  40349. }
  40350. RefractionTexture.prototype.clone = function () {
  40351. var textureSize = this.getSize();
  40352. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  40353. // Base texture
  40354. newTexture.hasAlpha = this.hasAlpha;
  40355. newTexture.level = this.level;
  40356. // Refraction Texture
  40357. newTexture.refractionPlane = this.refractionPlane.clone();
  40358. newTexture.renderList = this.renderList.slice(0);
  40359. newTexture.depth = this.depth;
  40360. return newTexture;
  40361. };
  40362. RefractionTexture.prototype.serialize = function () {
  40363. if (!this.name) {
  40364. return null;
  40365. }
  40366. var serializationObject = _super.prototype.serialize.call(this);
  40367. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  40368. serializationObject.depth = this.depth;
  40369. return serializationObject;
  40370. };
  40371. return RefractionTexture;
  40372. }(BABYLON.RenderTargetTexture));
  40373. BABYLON.RefractionTexture = RefractionTexture;
  40374. })(BABYLON || (BABYLON = {}));
  40375. //# sourceMappingURL=babylon.refractionTexture.js.map
  40376. /// <reference path="babylon.texture.ts" />
  40377. var BABYLON;
  40378. (function (BABYLON) {
  40379. var DynamicTexture = (function (_super) {
  40380. __extends(DynamicTexture, _super);
  40381. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  40382. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40383. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  40384. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  40385. _this.name = name;
  40386. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40387. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40388. _this._generateMipMaps = generateMipMaps;
  40389. if (options.getContext) {
  40390. _this._canvas = options;
  40391. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  40392. }
  40393. else {
  40394. _this._canvas = document.createElement("canvas");
  40395. if (options.width) {
  40396. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  40397. }
  40398. else {
  40399. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  40400. }
  40401. }
  40402. var textureSize = _this.getSize();
  40403. _this._canvas.width = textureSize.width;
  40404. _this._canvas.height = textureSize.height;
  40405. _this._context = _this._canvas.getContext("2d");
  40406. return _this;
  40407. }
  40408. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  40409. get: function () {
  40410. return true;
  40411. },
  40412. enumerable: true,
  40413. configurable: true
  40414. });
  40415. DynamicTexture.prototype.scale = function (ratio) {
  40416. var textureSize = this.getSize();
  40417. textureSize.width *= ratio;
  40418. textureSize.height *= ratio;
  40419. this._canvas.width = textureSize.width;
  40420. this._canvas.height = textureSize.height;
  40421. this.releaseInternalTexture();
  40422. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  40423. };
  40424. DynamicTexture.prototype.getContext = function () {
  40425. return this._context;
  40426. };
  40427. DynamicTexture.prototype.clear = function () {
  40428. var size = this.getSize();
  40429. this._context.fillRect(0, 0, size.width, size.height);
  40430. };
  40431. DynamicTexture.prototype.update = function (invertY) {
  40432. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  40433. };
  40434. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  40435. if (update === void 0) { update = true; }
  40436. var size = this.getSize();
  40437. if (clearColor) {
  40438. this._context.fillStyle = clearColor;
  40439. this._context.fillRect(0, 0, size.width, size.height);
  40440. }
  40441. this._context.font = font;
  40442. if (x === null || x === undefined) {
  40443. var textSize = this._context.measureText(text);
  40444. x = (size.width - textSize.width) / 2;
  40445. }
  40446. if (y === null || y === undefined) {
  40447. var fontSize = parseInt((font.replace(/\D/g, '')));
  40448. ;
  40449. y = (size.height / 2) + (fontSize / 3.65);
  40450. }
  40451. this._context.fillStyle = color;
  40452. this._context.fillText(text, x, y);
  40453. if (update) {
  40454. this.update(invertY);
  40455. }
  40456. };
  40457. DynamicTexture.prototype.clone = function () {
  40458. var textureSize = this.getSize();
  40459. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  40460. // Base texture
  40461. newTexture.hasAlpha = this.hasAlpha;
  40462. newTexture.level = this.level;
  40463. // Dynamic Texture
  40464. newTexture.wrapU = this.wrapU;
  40465. newTexture.wrapV = this.wrapV;
  40466. return newTexture;
  40467. };
  40468. return DynamicTexture;
  40469. }(BABYLON.Texture));
  40470. BABYLON.DynamicTexture = DynamicTexture;
  40471. })(BABYLON || (BABYLON = {}));
  40472. //# sourceMappingURL=babylon.dynamicTexture.js.map
  40473. var BABYLON;
  40474. (function (BABYLON) {
  40475. var VideoTexture = (function (_super) {
  40476. __extends(VideoTexture, _super);
  40477. /**
  40478. * Creates a video texture.
  40479. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  40480. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  40481. * @param {BABYLON.Scene} scene is obviously the current scene.
  40482. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  40483. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  40484. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  40485. */
  40486. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  40487. if (generateMipMaps === void 0) { generateMipMaps = false; }
  40488. if (invertY === void 0) { invertY = false; }
  40489. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40490. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  40491. _this._autoLaunch = true;
  40492. var urls;
  40493. _this.name = name;
  40494. if (urlsOrVideo instanceof HTMLVideoElement) {
  40495. _this.video = urlsOrVideo;
  40496. }
  40497. else {
  40498. urls = urlsOrVideo;
  40499. _this.video = document.createElement("video");
  40500. _this.video.autoplay = false;
  40501. _this.video.loop = true;
  40502. }
  40503. _this._generateMipMaps = generateMipMaps;
  40504. _this._samplingMode = samplingMode;
  40505. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  40506. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  40507. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  40508. }
  40509. else {
  40510. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40511. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40512. _this._generateMipMaps = false;
  40513. }
  40514. if (urls) {
  40515. _this.video.addEventListener("canplay", function () {
  40516. _this._createTexture();
  40517. });
  40518. urls.forEach(function (url) {
  40519. var source = document.createElement("source");
  40520. source.src = url;
  40521. _this.video.appendChild(source);
  40522. });
  40523. }
  40524. else {
  40525. _this._createTexture();
  40526. }
  40527. _this._lastUpdate = BABYLON.Tools.Now;
  40528. return _this;
  40529. }
  40530. VideoTexture.prototype._createTexture = function () {
  40531. var _this = this;
  40532. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  40533. if (this._autoLaunch) {
  40534. this._autoLaunch = false;
  40535. this.video.play();
  40536. }
  40537. this.video.addEventListener("playing", function () {
  40538. _this._texture.isReady = true;
  40539. });
  40540. };
  40541. VideoTexture.prototype.update = function () {
  40542. var now = BABYLON.Tools.Now;
  40543. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  40544. return false;
  40545. }
  40546. this._lastUpdate = now;
  40547. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  40548. return true;
  40549. };
  40550. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  40551. var video = document.createElement("video");
  40552. var constraintsDeviceId;
  40553. if (constraints && constraints.deviceId) {
  40554. constraintsDeviceId = {
  40555. exact: constraints.deviceId
  40556. };
  40557. }
  40558. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  40559. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  40560. if (navigator.getUserMedia) {
  40561. navigator.getUserMedia({
  40562. video: {
  40563. deviceId: constraintsDeviceId,
  40564. width: {
  40565. min: (constraints && constraints.minWidth) || 256,
  40566. max: (constraints && constraints.maxWidth) || 640
  40567. },
  40568. height: {
  40569. min: (constraints && constraints.minHeight) || 256,
  40570. max: (constraints && constraints.maxHeight) || 480
  40571. }
  40572. }
  40573. }, function (stream) {
  40574. if (video.mozSrcObject !== undefined) {
  40575. video.mozSrcObject = stream;
  40576. }
  40577. else {
  40578. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  40579. }
  40580. video.play();
  40581. if (onReady) {
  40582. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  40583. }
  40584. }, function (e) {
  40585. BABYLON.Tools.Error(e.name);
  40586. });
  40587. }
  40588. };
  40589. return VideoTexture;
  40590. }(BABYLON.Texture));
  40591. BABYLON.VideoTexture = VideoTexture;
  40592. })(BABYLON || (BABYLON = {}));
  40593. //# sourceMappingURL=babylon.videoTexture.js.map
  40594. var BABYLON;
  40595. (function (BABYLON) {
  40596. var RawTexture = (function (_super) {
  40597. __extends(RawTexture, _super);
  40598. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  40599. if (generateMipMaps === void 0) { generateMipMaps = true; }
  40600. if (invertY === void 0) { invertY = false; }
  40601. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40602. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  40603. _this.format = format;
  40604. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  40605. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40606. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40607. return _this;
  40608. }
  40609. RawTexture.prototype.update = function (data) {
  40610. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  40611. };
  40612. // Statics
  40613. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  40614. if (generateMipMaps === void 0) { generateMipMaps = true; }
  40615. if (invertY === void 0) { invertY = false; }
  40616. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40617. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  40618. };
  40619. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  40620. if (generateMipMaps === void 0) { generateMipMaps = true; }
  40621. if (invertY === void 0) { invertY = false; }
  40622. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40623. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  40624. };
  40625. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  40626. if (generateMipMaps === void 0) { generateMipMaps = true; }
  40627. if (invertY === void 0) { invertY = false; }
  40628. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40629. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  40630. };
  40631. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  40632. if (generateMipMaps === void 0) { generateMipMaps = true; }
  40633. if (invertY === void 0) { invertY = false; }
  40634. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40635. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  40636. };
  40637. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  40638. if (generateMipMaps === void 0) { generateMipMaps = true; }
  40639. if (invertY === void 0) { invertY = false; }
  40640. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40641. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  40642. };
  40643. return RawTexture;
  40644. }(BABYLON.Texture));
  40645. BABYLON.RawTexture = RawTexture;
  40646. })(BABYLON || (BABYLON = {}));
  40647. //# sourceMappingURL=babylon.rawTexture.js.map
  40648. var BABYLON;
  40649. (function (BABYLON) {
  40650. var PostProcess = (function () {
  40651. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  40652. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  40653. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40654. this.name = name;
  40655. this.width = -1;
  40656. this.height = -1;
  40657. /*
  40658. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  40659. Can only be used on a single postprocess or on the last one of a chain.
  40660. */
  40661. this.enablePixelPerfectMode = false;
  40662. this.samples = 1;
  40663. this._reusable = false;
  40664. this._textures = new BABYLON.SmartArray(2);
  40665. this._currentRenderTextureInd = 0;
  40666. this._scaleRatio = new BABYLON.Vector2(1, 1);
  40667. // Events
  40668. /**
  40669. * An event triggered when the postprocess is activated.
  40670. * @type {BABYLON.Observable}
  40671. */
  40672. this.onActivateObservable = new BABYLON.Observable();
  40673. /**
  40674. * An event triggered when the postprocess changes its size.
  40675. * @type {BABYLON.Observable}
  40676. */
  40677. this.onSizeChangedObservable = new BABYLON.Observable();
  40678. /**
  40679. * An event triggered when the postprocess applies its effect.
  40680. * @type {BABYLON.Observable}
  40681. */
  40682. this.onApplyObservable = new BABYLON.Observable();
  40683. /**
  40684. * An event triggered before rendering the postprocess
  40685. * @type {BABYLON.Observable}
  40686. */
  40687. this.onBeforeRenderObservable = new BABYLON.Observable();
  40688. /**
  40689. * An event triggered after rendering the postprocess
  40690. * @type {BABYLON.Observable}
  40691. */
  40692. this.onAfterRenderObservable = new BABYLON.Observable();
  40693. if (camera != null) {
  40694. this._camera = camera;
  40695. this._scene = camera.getScene();
  40696. camera.attachPostProcess(this);
  40697. this._engine = this._scene.getEngine();
  40698. }
  40699. else {
  40700. this._engine = engine;
  40701. }
  40702. this._options = options;
  40703. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  40704. this._reusable = reusable || false;
  40705. this._textureType = textureType;
  40706. this._samplers = samplers || [];
  40707. this._samplers.push("textureSampler");
  40708. this._fragmentUrl = fragmentUrl;
  40709. this._parameters = parameters || [];
  40710. this._parameters.push("scale");
  40711. this.updateEffect(defines);
  40712. }
  40713. Object.defineProperty(PostProcess.prototype, "onActivate", {
  40714. set: function (callback) {
  40715. if (this._onActivateObserver) {
  40716. this.onActivateObservable.remove(this._onActivateObserver);
  40717. }
  40718. this._onActivateObserver = this.onActivateObservable.add(callback);
  40719. },
  40720. enumerable: true,
  40721. configurable: true
  40722. });
  40723. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  40724. set: function (callback) {
  40725. if (this._onSizeChangedObserver) {
  40726. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  40727. }
  40728. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  40729. },
  40730. enumerable: true,
  40731. configurable: true
  40732. });
  40733. Object.defineProperty(PostProcess.prototype, "onApply", {
  40734. set: function (callback) {
  40735. if (this._onApplyObserver) {
  40736. this.onApplyObservable.remove(this._onApplyObserver);
  40737. }
  40738. this._onApplyObserver = this.onApplyObservable.add(callback);
  40739. },
  40740. enumerable: true,
  40741. configurable: true
  40742. });
  40743. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  40744. set: function (callback) {
  40745. if (this._onBeforeRenderObserver) {
  40746. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40747. }
  40748. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40749. },
  40750. enumerable: true,
  40751. configurable: true
  40752. });
  40753. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  40754. set: function (callback) {
  40755. if (this._onAfterRenderObserver) {
  40756. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40757. }
  40758. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40759. },
  40760. enumerable: true,
  40761. configurable: true
  40762. });
  40763. PostProcess.prototype.updateEffect = function (defines) {
  40764. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  40765. };
  40766. PostProcess.prototype.isReusable = function () {
  40767. return this._reusable;
  40768. };
  40769. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  40770. PostProcess.prototype.markTextureDirty = function () {
  40771. this.width = -1;
  40772. };
  40773. PostProcess.prototype.activate = function (camera, sourceTexture) {
  40774. var _this = this;
  40775. camera = camera || this._camera;
  40776. var scene = camera.getScene();
  40777. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  40778. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  40779. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  40780. var desiredWidth = this._options.width || requiredWidth;
  40781. var desiredHeight = this._options.height || requiredHeight;
  40782. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  40783. if (!this._options.width) {
  40784. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  40785. }
  40786. if (!this._options.height) {
  40787. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  40788. }
  40789. }
  40790. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  40791. if (this._textures.length > 0) {
  40792. for (var i = 0; i < this._textures.length; i++) {
  40793. this._engine._releaseTexture(this._textures.data[i]);
  40794. }
  40795. this._textures.reset();
  40796. }
  40797. this.width = desiredWidth;
  40798. this.height = desiredHeight;
  40799. var textureSize = { width: this.width, height: this.height };
  40800. var textureOptions = {
  40801. generateMipMaps: false,
  40802. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  40803. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  40804. samplingMode: this.renderTargetSamplingMode,
  40805. type: this._textureType
  40806. };
  40807. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  40808. if (this._reusable) {
  40809. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  40810. }
  40811. this.onSizeChangedObservable.notifyObservers(this);
  40812. }
  40813. this._textures.forEach(function (texture) {
  40814. if (texture.samples !== _this.samples) {
  40815. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  40816. }
  40817. });
  40818. if (this.enablePixelPerfectMode) {
  40819. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  40820. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  40821. }
  40822. else {
  40823. this._scaleRatio.copyFromFloats(1, 1);
  40824. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  40825. }
  40826. this.onActivateObservable.notifyObservers(camera);
  40827. // Clear
  40828. if (this.clearColor) {
  40829. this._engine.clear(this.clearColor, true, true, true);
  40830. }
  40831. else {
  40832. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  40833. }
  40834. if (this._reusable) {
  40835. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  40836. }
  40837. };
  40838. Object.defineProperty(PostProcess.prototype, "isSupported", {
  40839. get: function () {
  40840. return this._effect.isSupported;
  40841. },
  40842. enumerable: true,
  40843. configurable: true
  40844. });
  40845. PostProcess.prototype.apply = function () {
  40846. // Check
  40847. if (!this._effect.isReady())
  40848. return null;
  40849. // States
  40850. this._engine.enableEffect(this._effect);
  40851. this._engine.setState(false);
  40852. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40853. this._engine.setDepthBuffer(false);
  40854. this._engine.setDepthWrite(false);
  40855. // Texture
  40856. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  40857. // Parameters
  40858. this._effect.setVector2("scale", this._scaleRatio);
  40859. this.onApplyObservable.notifyObservers(this._effect);
  40860. return this._effect;
  40861. };
  40862. PostProcess.prototype.dispose = function (camera) {
  40863. camera = camera || this._camera;
  40864. if (this._textures.length > 0) {
  40865. for (var i = 0; i < this._textures.length; i++) {
  40866. this._engine._releaseTexture(this._textures.data[i]);
  40867. }
  40868. }
  40869. this._textures.dispose();
  40870. if (!camera) {
  40871. return;
  40872. }
  40873. camera.detachPostProcess(this);
  40874. var index = camera._postProcesses.indexOf(this);
  40875. if (index === 0 && camera._postProcesses.length > 0) {
  40876. this._camera._postProcesses[0].markTextureDirty();
  40877. }
  40878. this.onActivateObservable.clear();
  40879. this.onAfterRenderObservable.clear();
  40880. this.onApplyObservable.clear();
  40881. this.onBeforeRenderObservable.clear();
  40882. this.onSizeChangedObservable.clear();
  40883. };
  40884. return PostProcess;
  40885. }());
  40886. BABYLON.PostProcess = PostProcess;
  40887. })(BABYLON || (BABYLON = {}));
  40888. //# sourceMappingURL=babylon.postProcess.js.map
  40889. var BABYLON;
  40890. (function (BABYLON) {
  40891. var PassPostProcess = (function (_super) {
  40892. __extends(PassPostProcess, _super);
  40893. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  40894. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40895. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  40896. }
  40897. return PassPostProcess;
  40898. }(BABYLON.PostProcess));
  40899. BABYLON.PassPostProcess = PassPostProcess;
  40900. })(BABYLON || (BABYLON = {}));
  40901. //# sourceMappingURL=babylon.passPostProcess.js.map
  40902. var BABYLON;
  40903. (function (BABYLON) {
  40904. var ShadowGenerator = (function () {
  40905. /**
  40906. * Creates a ShadowGenerator object.
  40907. * A ShadowGenerator is the required tool to use the shadows.
  40908. * Each light casting shadows needs to use its own ShadowGenerator.
  40909. * Required parameters :
  40910. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  40911. * - `light` : the light object generating the shadows.
  40912. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  40913. */
  40914. function ShadowGenerator(mapSize, light) {
  40915. var _this = this;
  40916. // Members
  40917. this._filter = ShadowGenerator.FILTER_NONE;
  40918. this.blurScale = 2;
  40919. this._blurBoxOffset = 0;
  40920. this._bias = 0.00005;
  40921. this._lightDirection = BABYLON.Vector3.Zero();
  40922. this.forceBackFacesOnly = false;
  40923. this._darkness = 0;
  40924. this._transparencyShadow = false;
  40925. this._viewMatrix = BABYLON.Matrix.Zero();
  40926. this._projectionMatrix = BABYLON.Matrix.Zero();
  40927. this._transformMatrix = BABYLON.Matrix.Zero();
  40928. this._worldViewProjection = BABYLON.Matrix.Zero();
  40929. this._currentFaceIndex = 0;
  40930. this._currentFaceIndexCache = 0;
  40931. this._useFullFloat = true;
  40932. this._light = light;
  40933. this._scene = light.getScene();
  40934. this._mapSize = mapSize;
  40935. light._shadowGenerator = this;
  40936. light._markMeshesAsLightDirty();
  40937. // Texture type fallback from float to int if not supported.
  40938. var textureType;
  40939. var caps = this._scene.getEngine().getCaps();
  40940. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  40941. this._useFullFloat = true;
  40942. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  40943. }
  40944. else {
  40945. this._useFullFloat = false;
  40946. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  40947. }
  40948. // Render target
  40949. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  40950. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40951. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40952. this._shadowMap.anisotropicFilteringLevel = 1;
  40953. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40954. this._shadowMap.renderParticles = false;
  40955. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  40956. _this._currentFaceIndex = faceIndex;
  40957. });
  40958. this._shadowMap.onAfterUnbindObservable.add(function () {
  40959. if (!_this.useBlurExponentialShadowMap) {
  40960. return;
  40961. }
  40962. if (!_this._shadowMap2) {
  40963. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  40964. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40965. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40966. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40967. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  40968. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  40969. effect.setTexture("textureSampler", _this._shadowMap);
  40970. });
  40971. _this.blurBoxOffset = 1;
  40972. }
  40973. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  40974. });
  40975. // Custom render function
  40976. var renderSubMesh = function (subMesh) {
  40977. var mesh = subMesh.getRenderingMesh();
  40978. var scene = _this._scene;
  40979. var engine = scene.getEngine();
  40980. // Culling
  40981. engine.setState(subMesh.getMaterial().backFaceCulling);
  40982. // Managing instances
  40983. var batch = mesh._getInstancesRenderList(subMesh._id);
  40984. if (batch.mustReturn) {
  40985. return;
  40986. }
  40987. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  40988. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  40989. engine.enableEffect(_this._effect);
  40990. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  40991. var material = subMesh.getMaterial();
  40992. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  40993. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  40994. _this._effect.setVector3("lightPosition", _this.getLight().position);
  40995. if (_this.getLight().needCube()) {
  40996. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  40997. }
  40998. // Alpha test
  40999. if (material && material.needAlphaTesting()) {
  41000. var alphaTexture = material.getAlphaTestTexture();
  41001. _this._effect.setTexture("diffuseSampler", alphaTexture);
  41002. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  41003. }
  41004. // Bones
  41005. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  41006. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  41007. }
  41008. if (_this.forceBackFacesOnly) {
  41009. engine.setState(true, 0, false, true);
  41010. }
  41011. // Draw
  41012. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  41013. if (_this.forceBackFacesOnly) {
  41014. engine.setState(true, 0, false, false);
  41015. }
  41016. }
  41017. else {
  41018. // Need to reset refresh rate of the shadowMap
  41019. _this._shadowMap.resetRefreshCounter();
  41020. }
  41021. };
  41022. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  41023. var index;
  41024. for (index = 0; index < opaqueSubMeshes.length; index++) {
  41025. renderSubMesh(opaqueSubMeshes.data[index]);
  41026. }
  41027. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  41028. renderSubMesh(alphaTestSubMeshes.data[index]);
  41029. }
  41030. if (_this._transparencyShadow) {
  41031. for (index = 0; index < transparentSubMeshes.length; index++) {
  41032. renderSubMesh(transparentSubMeshes.data[index]);
  41033. }
  41034. }
  41035. };
  41036. this._shadowMap.onClearObservable.add(function (engine) {
  41037. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  41038. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  41039. }
  41040. else {
  41041. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  41042. }
  41043. });
  41044. }
  41045. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  41046. // Static
  41047. get: function () {
  41048. return ShadowGenerator._FILTER_NONE;
  41049. },
  41050. enumerable: true,
  41051. configurable: true
  41052. });
  41053. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  41054. get: function () {
  41055. return ShadowGenerator._FILTER_POISSONSAMPLING;
  41056. },
  41057. enumerable: true,
  41058. configurable: true
  41059. });
  41060. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  41061. get: function () {
  41062. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  41063. },
  41064. enumerable: true,
  41065. configurable: true
  41066. });
  41067. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  41068. get: function () {
  41069. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  41070. },
  41071. enumerable: true,
  41072. configurable: true
  41073. });
  41074. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  41075. get: function () {
  41076. return this._bias;
  41077. },
  41078. set: function (bias) {
  41079. this._bias = bias;
  41080. },
  41081. enumerable: true,
  41082. configurable: true
  41083. });
  41084. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  41085. get: function () {
  41086. return this._blurBoxOffset;
  41087. },
  41088. set: function (value) {
  41089. var _this = this;
  41090. if (this._blurBoxOffset === value) {
  41091. return;
  41092. }
  41093. this._blurBoxOffset = value;
  41094. if (this._boxBlurPostprocess) {
  41095. this._boxBlurPostprocess.dispose();
  41096. }
  41097. var textureType;
  41098. var caps = this._scene.getEngine().getCaps();
  41099. if (this._useFullFloat) {
  41100. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  41101. }
  41102. else {
  41103. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  41104. }
  41105. 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, textureType);
  41106. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  41107. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  41108. });
  41109. },
  41110. enumerable: true,
  41111. configurable: true
  41112. });
  41113. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  41114. get: function () {
  41115. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  41116. },
  41117. set: function (value) {
  41118. this._depthScale = value;
  41119. },
  41120. enumerable: true,
  41121. configurable: true
  41122. });
  41123. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  41124. get: function () {
  41125. return this._filter;
  41126. },
  41127. set: function (value) {
  41128. if (this._filter === value) {
  41129. return;
  41130. }
  41131. this._filter = value;
  41132. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  41133. this._shadowMap.anisotropicFilteringLevel = 16;
  41134. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41135. }
  41136. else {
  41137. this._shadowMap.anisotropicFilteringLevel = 1;
  41138. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  41139. }
  41140. this._light._markMeshesAsLightDirty();
  41141. },
  41142. enumerable: true,
  41143. configurable: true
  41144. });
  41145. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  41146. get: function () {
  41147. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  41148. return this.useExponentialShadowMap;
  41149. },
  41150. set: function (value) {
  41151. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  41152. this.useExponentialShadowMap = value;
  41153. },
  41154. enumerable: true,
  41155. configurable: true
  41156. });
  41157. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  41158. get: function () {
  41159. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  41160. },
  41161. set: function (value) {
  41162. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  41163. },
  41164. enumerable: true,
  41165. configurable: true
  41166. });
  41167. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  41168. get: function () {
  41169. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  41170. },
  41171. set: function (value) {
  41172. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  41173. },
  41174. enumerable: true,
  41175. configurable: true
  41176. });
  41177. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  41178. get: function () {
  41179. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  41180. return this.useBlurExponentialShadowMap;
  41181. },
  41182. set: function (value) {
  41183. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  41184. this.useBlurExponentialShadowMap = value;
  41185. },
  41186. enumerable: true,
  41187. configurable: true
  41188. });
  41189. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  41190. get: function () {
  41191. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  41192. },
  41193. set: function (value) {
  41194. if (this._light.needCube() && value) {
  41195. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  41196. }
  41197. else {
  41198. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  41199. }
  41200. },
  41201. enumerable: true,
  41202. configurable: true
  41203. });
  41204. /**
  41205. * Boolean : true when the ShadowGenerator is finally computed.
  41206. */
  41207. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  41208. var defines = [];
  41209. if (this._useFullFloat) {
  41210. defines.push("#define FULLFLOAT");
  41211. }
  41212. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  41213. defines.push("#define ESM");
  41214. }
  41215. if (this.getLight().needCube()) {
  41216. defines.push("#define CUBEMAP");
  41217. }
  41218. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41219. var mesh = subMesh.getMesh();
  41220. var material = subMesh.getMaterial();
  41221. // Alpha test
  41222. if (material && material.needAlphaTesting()) {
  41223. defines.push("#define ALPHATEST");
  41224. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41225. attribs.push(BABYLON.VertexBuffer.UVKind);
  41226. defines.push("#define UV1");
  41227. }
  41228. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41229. var alphaTexture = material.getAlphaTestTexture();
  41230. if (alphaTexture.coordinatesIndex === 1) {
  41231. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41232. defines.push("#define UV2");
  41233. }
  41234. }
  41235. }
  41236. // Bones
  41237. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  41238. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41239. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41240. if (mesh.numBoneInfluencers > 4) {
  41241. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41242. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41243. }
  41244. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  41245. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  41246. }
  41247. else {
  41248. defines.push("#define NUM_BONE_INFLUENCERS 0");
  41249. }
  41250. // Instances
  41251. if (useInstances) {
  41252. defines.push("#define INSTANCES");
  41253. attribs.push("world0");
  41254. attribs.push("world1");
  41255. attribs.push("world2");
  41256. attribs.push("world3");
  41257. }
  41258. // Get correct effect
  41259. var join = defines.join("\n");
  41260. if (this._cachedDefines !== join) {
  41261. this._cachedDefines = join;
  41262. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  41263. }
  41264. return this._effect.isReady();
  41265. };
  41266. /**
  41267. * Returns a RenderTargetTexture object : the shadow map texture.
  41268. */
  41269. ShadowGenerator.prototype.getShadowMap = function () {
  41270. return this._shadowMap;
  41271. };
  41272. /**
  41273. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  41274. */
  41275. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  41276. if (this._shadowMap2) {
  41277. return this._shadowMap2;
  41278. }
  41279. return this._shadowMap;
  41280. };
  41281. /**
  41282. * Returns the associated light object.
  41283. */
  41284. ShadowGenerator.prototype.getLight = function () {
  41285. return this._light;
  41286. };
  41287. // Methods
  41288. /**
  41289. * Returns a Matrix object : the updated transformation matrix.
  41290. */
  41291. ShadowGenerator.prototype.getTransformMatrix = function () {
  41292. var scene = this._scene;
  41293. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  41294. return this._transformMatrix;
  41295. }
  41296. this._currentRenderID = scene.getRenderId();
  41297. this._currentFaceIndexCache = this._currentFaceIndex;
  41298. var lightPosition = this._light.position;
  41299. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  41300. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  41301. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  41302. }
  41303. if (this._light.computeTransformedPosition()) {
  41304. lightPosition = this._light.transformedPosition;
  41305. }
  41306. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  41307. this._cachedPosition = lightPosition.clone();
  41308. this._cachedDirection = this._lightDirection.clone();
  41309. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  41310. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  41311. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  41312. }
  41313. return this._transformMatrix;
  41314. };
  41315. /**
  41316. * Returns the darkness value (float).
  41317. */
  41318. ShadowGenerator.prototype.getDarkness = function () {
  41319. return this._darkness;
  41320. };
  41321. /**
  41322. * Sets the ShadowGenerator darkness value (float <= 1.0).
  41323. * Returns the ShadowGenerator.
  41324. */
  41325. ShadowGenerator.prototype.setDarkness = function (darkness) {
  41326. if (darkness >= 1.0)
  41327. this._darkness = 1.0;
  41328. else if (darkness <= 0.0)
  41329. this._darkness = 0.0;
  41330. else
  41331. this._darkness = darkness;
  41332. return this;
  41333. };
  41334. /**
  41335. * Sets the ability to have transparent shadow (boolean).
  41336. * Returns the ShadowGenerator.
  41337. */
  41338. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  41339. this._transparencyShadow = hasShadow;
  41340. return this;
  41341. };
  41342. ShadowGenerator.prototype._packHalf = function (depth) {
  41343. var scale = depth * 255.0;
  41344. var fract = scale - Math.floor(scale);
  41345. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  41346. };
  41347. /**
  41348. * Disposes the ShadowGenerator.
  41349. * Returns nothing.
  41350. */
  41351. ShadowGenerator.prototype.dispose = function () {
  41352. this._shadowMap.dispose();
  41353. if (this._shadowMap2) {
  41354. this._shadowMap2.dispose();
  41355. }
  41356. if (this._downSamplePostprocess) {
  41357. this._downSamplePostprocess.dispose();
  41358. }
  41359. if (this._boxBlurPostprocess) {
  41360. this._boxBlurPostprocess.dispose();
  41361. }
  41362. this._light._shadowGenerator = null;
  41363. this._light._markMeshesAsLightDirty();
  41364. };
  41365. /**
  41366. * Serializes the ShadowGenerator and returns a serializationObject.
  41367. */
  41368. ShadowGenerator.prototype.serialize = function () {
  41369. var serializationObject = {};
  41370. serializationObject.lightId = this._light.id;
  41371. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  41372. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  41373. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  41374. serializationObject.usePoissonSampling = this.usePoissonSampling;
  41375. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  41376. serializationObject.depthScale = this.depthScale;
  41377. serializationObject.darkness = this.getDarkness();
  41378. serializationObject.renderList = [];
  41379. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  41380. var mesh = this.getShadowMap().renderList[meshIndex];
  41381. serializationObject.renderList.push(mesh.id);
  41382. }
  41383. return serializationObject;
  41384. };
  41385. /**
  41386. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  41387. */
  41388. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  41389. //casting to point light, as light is missing the position attr and typescript complains.
  41390. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  41391. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  41392. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  41393. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  41394. meshes.forEach(function (mesh) {
  41395. shadowGenerator.getShadowMap().renderList.push(mesh);
  41396. });
  41397. }
  41398. if (parsedShadowGenerator.usePoissonSampling) {
  41399. shadowGenerator.usePoissonSampling = true;
  41400. }
  41401. else if (parsedShadowGenerator.useExponentialShadowMap) {
  41402. shadowGenerator.useExponentialShadowMap = true;
  41403. }
  41404. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  41405. shadowGenerator.useBlurExponentialShadowMap = true;
  41406. }
  41407. else if (parsedShadowGenerator.useVarianceShadowMap) {
  41408. shadowGenerator.useExponentialShadowMap = true;
  41409. }
  41410. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  41411. shadowGenerator.useBlurExponentialShadowMap = true;
  41412. }
  41413. if (parsedShadowGenerator.depthScale) {
  41414. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  41415. }
  41416. if (parsedShadowGenerator.blurScale) {
  41417. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  41418. }
  41419. if (parsedShadowGenerator.blurBoxOffset) {
  41420. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  41421. }
  41422. if (parsedShadowGenerator.bias !== undefined) {
  41423. shadowGenerator.bias = parsedShadowGenerator.bias;
  41424. }
  41425. if (parsedShadowGenerator.darkness) {
  41426. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  41427. }
  41428. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  41429. return shadowGenerator;
  41430. };
  41431. return ShadowGenerator;
  41432. }());
  41433. ShadowGenerator._FILTER_NONE = 0;
  41434. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  41435. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  41436. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  41437. BABYLON.ShadowGenerator = ShadowGenerator;
  41438. })(BABYLON || (BABYLON = {}));
  41439. //# sourceMappingURL=babylon.shadowGenerator.js.map
  41440. var BABYLON;
  41441. (function (BABYLON) {
  41442. var DefaultLoadingScreen = (function () {
  41443. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  41444. if (_loadingText === void 0) { _loadingText = ""; }
  41445. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  41446. var _this = this;
  41447. this._renderingCanvas = _renderingCanvas;
  41448. this._loadingText = _loadingText;
  41449. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  41450. // Resize
  41451. this._resizeLoadingUI = function () {
  41452. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  41453. _this._loadingDiv.style.position = "absolute";
  41454. _this._loadingDiv.style.left = canvasRect.left + "px";
  41455. _this._loadingDiv.style.top = canvasRect.top + "px";
  41456. _this._loadingDiv.style.width = canvasRect.width + "px";
  41457. _this._loadingDiv.style.height = canvasRect.height + "px";
  41458. };
  41459. }
  41460. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  41461. var _this = this;
  41462. if (this._loadingDiv) {
  41463. // Do not add a loading screen if there is already one
  41464. return;
  41465. }
  41466. this._loadingDiv = document.createElement("div");
  41467. this._loadingDiv.id = "babylonjsLoadingDiv";
  41468. this._loadingDiv.style.opacity = "0";
  41469. this._loadingDiv.style.transition = "opacity 1.5s ease";
  41470. // Loading text
  41471. this._loadingTextDiv = document.createElement("div");
  41472. this._loadingTextDiv.style.position = "absolute";
  41473. this._loadingTextDiv.style.left = "0";
  41474. this._loadingTextDiv.style.top = "50%";
  41475. this._loadingTextDiv.style.marginTop = "80px";
  41476. this._loadingTextDiv.style.width = "100%";
  41477. this._loadingTextDiv.style.height = "20px";
  41478. this._loadingTextDiv.style.fontFamily = "Arial";
  41479. this._loadingTextDiv.style.fontSize = "14px";
  41480. this._loadingTextDiv.style.color = "white";
  41481. this._loadingTextDiv.style.textAlign = "center";
  41482. this._loadingTextDiv.innerHTML = "Loading";
  41483. this._loadingDiv.appendChild(this._loadingTextDiv);
  41484. //set the predefined text
  41485. this._loadingTextDiv.innerHTML = this._loadingText;
  41486. // Loading img
  41487. var imgBack = new Image();
  41488. 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==";
  41489. imgBack.style.position = "absolute";
  41490. imgBack.style.left = "50%";
  41491. imgBack.style.top = "50%";
  41492. imgBack.style.marginLeft = "-50px";
  41493. imgBack.style.marginTop = "-50px";
  41494. imgBack.style.transition = "transform 1.0s ease";
  41495. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  41496. var deg = 360;
  41497. var onTransitionEnd = function () {
  41498. deg += 360;
  41499. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  41500. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  41501. };
  41502. imgBack.addEventListener("transitionend", onTransitionEnd);
  41503. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  41504. this._loadingDiv.appendChild(imgBack);
  41505. // front image
  41506. var imgFront = new Image();
  41507. 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=";
  41508. imgFront.style.position = "absolute";
  41509. imgFront.style.left = "50%";
  41510. imgFront.style.top = "50%";
  41511. imgFront.style.marginLeft = "-50px";
  41512. imgFront.style.marginTop = "-50px";
  41513. this._loadingDiv.appendChild(imgFront);
  41514. this._resizeLoadingUI();
  41515. window.addEventListener("resize", this._resizeLoadingUI);
  41516. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  41517. document.body.appendChild(this._loadingDiv);
  41518. setTimeout(function () {
  41519. _this._loadingDiv.style.opacity = "1";
  41520. imgBack.style.transform = "rotateZ(360deg)";
  41521. imgBack.style.webkitTransform = "rotateZ(360deg)";
  41522. }, 0);
  41523. };
  41524. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  41525. var _this = this;
  41526. if (!this._loadingDiv) {
  41527. return;
  41528. }
  41529. var onTransitionEnd = function () {
  41530. if (!_this._loadingDiv) {
  41531. return;
  41532. }
  41533. document.body.removeChild(_this._loadingDiv);
  41534. window.removeEventListener("resize", _this._resizeLoadingUI);
  41535. _this._loadingDiv = null;
  41536. };
  41537. this._loadingDiv.style.opacity = "0";
  41538. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  41539. };
  41540. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  41541. set: function (text) {
  41542. this._loadingText = text;
  41543. if (this._loadingTextDiv) {
  41544. this._loadingTextDiv.innerHTML = this._loadingText;
  41545. }
  41546. },
  41547. enumerable: true,
  41548. configurable: true
  41549. });
  41550. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  41551. get: function () {
  41552. return this._loadingDivBackgroundColor;
  41553. },
  41554. set: function (color) {
  41555. this._loadingDivBackgroundColor = color;
  41556. if (!this._loadingDiv) {
  41557. return;
  41558. }
  41559. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  41560. },
  41561. enumerable: true,
  41562. configurable: true
  41563. });
  41564. return DefaultLoadingScreen;
  41565. }());
  41566. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  41567. })(BABYLON || (BABYLON = {}));
  41568. //# sourceMappingURL=babylon.loadingScreen.js.map
  41569. var BABYLON;
  41570. (function (BABYLON) {
  41571. var SceneLoader = (function () {
  41572. function SceneLoader() {
  41573. }
  41574. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  41575. get: function () {
  41576. return 0;
  41577. },
  41578. enumerable: true,
  41579. configurable: true
  41580. });
  41581. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  41582. get: function () {
  41583. return 1;
  41584. },
  41585. enumerable: true,
  41586. configurable: true
  41587. });
  41588. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  41589. get: function () {
  41590. return 2;
  41591. },
  41592. enumerable: true,
  41593. configurable: true
  41594. });
  41595. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  41596. get: function () {
  41597. return 3;
  41598. },
  41599. enumerable: true,
  41600. configurable: true
  41601. });
  41602. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  41603. get: function () {
  41604. return SceneLoader._ForceFullSceneLoadingForIncremental;
  41605. },
  41606. set: function (value) {
  41607. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  41608. },
  41609. enumerable: true,
  41610. configurable: true
  41611. });
  41612. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  41613. get: function () {
  41614. return SceneLoader._ShowLoadingScreen;
  41615. },
  41616. set: function (value) {
  41617. SceneLoader._ShowLoadingScreen = value;
  41618. },
  41619. enumerable: true,
  41620. configurable: true
  41621. });
  41622. Object.defineProperty(SceneLoader, "loggingLevel", {
  41623. get: function () {
  41624. return SceneLoader._loggingLevel;
  41625. },
  41626. set: function (value) {
  41627. SceneLoader._loggingLevel = value;
  41628. },
  41629. enumerable: true,
  41630. configurable: true
  41631. });
  41632. SceneLoader._getDefaultPlugin = function () {
  41633. return SceneLoader._registeredPlugins[".babylon"];
  41634. };
  41635. SceneLoader._getPluginForExtension = function (extension) {
  41636. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  41637. if (registeredPlugin) {
  41638. return registeredPlugin;
  41639. }
  41640. return SceneLoader._getDefaultPlugin();
  41641. };
  41642. SceneLoader._getPluginForFilename = function (sceneFilename) {
  41643. if (sceneFilename.name) {
  41644. sceneFilename = sceneFilename.name;
  41645. }
  41646. var dotPosition = sceneFilename.lastIndexOf(".");
  41647. var queryStringPosition = sceneFilename.indexOf("?");
  41648. if (queryStringPosition === -1) {
  41649. queryStringPosition = sceneFilename.length;
  41650. }
  41651. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  41652. return SceneLoader._getPluginForExtension(extension);
  41653. };
  41654. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  41655. SceneLoader._getDirectLoad = function (sceneFilename) {
  41656. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  41657. return sceneFilename.substr(5);
  41658. }
  41659. return null;
  41660. };
  41661. // Public functions
  41662. SceneLoader.GetPluginForExtension = function (extension) {
  41663. return SceneLoader._getPluginForExtension(extension).plugin;
  41664. };
  41665. SceneLoader.RegisterPlugin = function (plugin) {
  41666. if (typeof plugin.extensions === "string") {
  41667. var extension = plugin.extensions;
  41668. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  41669. plugin: plugin,
  41670. isBinary: false
  41671. };
  41672. }
  41673. else {
  41674. var extensions = plugin.extensions;
  41675. Object.keys(extensions).forEach(function (extension) {
  41676. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  41677. plugin: plugin,
  41678. isBinary: extensions[extension].isBinary
  41679. };
  41680. });
  41681. }
  41682. };
  41683. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  41684. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  41685. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  41686. return;
  41687. }
  41688. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  41689. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  41690. return;
  41691. }
  41692. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  41693. var loadingToken = {};
  41694. scene._addPendingData(loadingToken);
  41695. var manifestChecked = function (success) {
  41696. scene.database = database;
  41697. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  41698. var plugin = registeredPlugin.plugin;
  41699. var useArrayBuffer = registeredPlugin.isBinary;
  41700. var importMeshFromData = function (data) {
  41701. var meshes = [];
  41702. var particleSystems = [];
  41703. var skeletons = [];
  41704. if (scene.isDisposed) {
  41705. if (onerror) {
  41706. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  41707. }
  41708. return;
  41709. }
  41710. try {
  41711. if (plugin.importMesh) {
  41712. var syncedPlugin = plugin;
  41713. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  41714. if (onerror) {
  41715. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  41716. }
  41717. scene._removePendingData(loadingToken);
  41718. return;
  41719. }
  41720. if (onsuccess) {
  41721. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  41722. onsuccess(meshes, particleSystems, skeletons);
  41723. scene._removePendingData(loadingToken);
  41724. }
  41725. }
  41726. else {
  41727. var asyncedPlugin = plugin;
  41728. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  41729. if (onsuccess) {
  41730. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  41731. onsuccess(meshes, particleSystems, skeletons);
  41732. scene._removePendingData(loadingToken);
  41733. }
  41734. }, function () {
  41735. if (onerror) {
  41736. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  41737. }
  41738. scene._removePendingData(loadingToken);
  41739. });
  41740. }
  41741. }
  41742. catch (e) {
  41743. if (onerror) {
  41744. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  41745. }
  41746. scene._removePendingData(loadingToken);
  41747. }
  41748. };
  41749. if (directLoad) {
  41750. importMeshFromData(directLoad);
  41751. return;
  41752. }
  41753. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  41754. importMeshFromData(data);
  41755. }, progressCallBack, database, useArrayBuffer, function () {
  41756. if (onerror) {
  41757. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  41758. }
  41759. });
  41760. };
  41761. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  41762. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  41763. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  41764. }
  41765. else {
  41766. // If the scene is a data stream or offline support is not enabled, it's a direct load
  41767. manifestChecked(true);
  41768. }
  41769. };
  41770. /**
  41771. * Load a scene
  41772. * @param rootUrl a string that defines the root url for scene and resources
  41773. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  41774. * @param engine is the instance of BABYLON.Engine to use to create the scene
  41775. */
  41776. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  41777. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  41778. };
  41779. /**
  41780. * Append a scene
  41781. * @param rootUrl a string that defines the root url for scene and resources
  41782. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  41783. * @param scene is the instance of BABYLON.Scene to append to
  41784. */
  41785. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  41786. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  41787. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  41788. return;
  41789. }
  41790. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  41791. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  41792. var plugin = registeredPlugin.plugin;
  41793. var useArrayBuffer = registeredPlugin.isBinary;
  41794. var database;
  41795. var loadingToken = {};
  41796. scene._addPendingData(loadingToken);
  41797. if (SceneLoader.ShowLoadingScreen) {
  41798. scene.getEngine().displayLoadingUI();
  41799. }
  41800. var loadSceneFromData = function (data) {
  41801. scene.database = database;
  41802. if (plugin.load) {
  41803. var syncedPlugin = plugin;
  41804. if (!syncedPlugin.load(scene, data, rootUrl)) {
  41805. if (onerror) {
  41806. onerror(scene);
  41807. }
  41808. scene._removePendingData(loadingToken);
  41809. scene.getEngine().hideLoadingUI();
  41810. return;
  41811. }
  41812. if (onsuccess) {
  41813. onsuccess(scene);
  41814. }
  41815. scene._removePendingData(loadingToken);
  41816. }
  41817. else {
  41818. var asyncedPlugin = plugin;
  41819. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  41820. if (onsuccess) {
  41821. onsuccess(scene);
  41822. }
  41823. scene._removePendingData(loadingToken);
  41824. }, function () {
  41825. if (onerror) {
  41826. onerror(scene);
  41827. }
  41828. scene._removePendingData(loadingToken);
  41829. scene.getEngine().hideLoadingUI();
  41830. });
  41831. }
  41832. if (SceneLoader.ShowLoadingScreen) {
  41833. scene.executeWhenReady(function () {
  41834. scene.getEngine().hideLoadingUI();
  41835. });
  41836. }
  41837. };
  41838. var manifestChecked = function (success) {
  41839. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  41840. };
  41841. if (directLoad) {
  41842. loadSceneFromData(directLoad);
  41843. return;
  41844. }
  41845. if (rootUrl.indexOf("file:") === -1) {
  41846. if (scene.getEngine().enableOfflineSupport) {
  41847. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  41848. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  41849. }
  41850. else {
  41851. manifestChecked(true);
  41852. }
  41853. }
  41854. else {
  41855. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  41856. }
  41857. };
  41858. return SceneLoader;
  41859. }());
  41860. // Flags
  41861. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  41862. SceneLoader._ShowLoadingScreen = true;
  41863. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  41864. // Members
  41865. SceneLoader._registeredPlugins = {};
  41866. BABYLON.SceneLoader = SceneLoader;
  41867. ;
  41868. })(BABYLON || (BABYLON = {}));
  41869. //# sourceMappingURL=babylon.sceneLoader.js.map
  41870. var BABYLON;
  41871. (function (BABYLON) {
  41872. var Internals;
  41873. (function (Internals) {
  41874. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  41875. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  41876. var parsedMaterial = parsedData.materials[index];
  41877. if (parsedMaterial.id === id) {
  41878. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  41879. }
  41880. }
  41881. return null;
  41882. };
  41883. var isDescendantOf = function (mesh, names, hierarchyIds) {
  41884. names = (names instanceof Array) ? names : [names];
  41885. for (var i in names) {
  41886. if (mesh.name === names[i]) {
  41887. hierarchyIds.push(mesh.id);
  41888. return true;
  41889. }
  41890. }
  41891. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  41892. hierarchyIds.push(mesh.id);
  41893. return true;
  41894. }
  41895. return false;
  41896. };
  41897. var logOperation = function (operation, producer) {
  41898. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  41899. };
  41900. BABYLON.SceneLoader.RegisterPlugin({
  41901. extensions: ".babylon",
  41902. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  41903. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  41904. // when SceneLoader.debugLogging = true (default), or exception encountered.
  41905. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  41906. // and avoid problems with multiple concurrent .babylon loads.
  41907. var log = "importMesh has failed JSON parse";
  41908. try {
  41909. var parsedData = JSON.parse(data);
  41910. log = "";
  41911. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  41912. var loadedSkeletonsIds = [];
  41913. var loadedMaterialsIds = [];
  41914. var hierarchyIds = [];
  41915. var index;
  41916. var cache;
  41917. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  41918. var parsedMesh = parsedData.meshes[index];
  41919. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  41920. if (meshesNames instanceof Array) {
  41921. // Remove found mesh name from list.
  41922. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  41923. }
  41924. //Geometry?
  41925. if (parsedMesh.geometryId) {
  41926. //does the file contain geometries?
  41927. if (parsedData.geometries) {
  41928. //find the correct geometry and add it to the scene
  41929. var found = false;
  41930. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  41931. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  41932. return;
  41933. }
  41934. else {
  41935. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  41936. if (parsedGeometryData.id === parsedMesh.geometryId) {
  41937. switch (geometryType) {
  41938. case "boxes":
  41939. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  41940. break;
  41941. case "spheres":
  41942. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  41943. break;
  41944. case "cylinders":
  41945. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  41946. break;
  41947. case "toruses":
  41948. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  41949. break;
  41950. case "grounds":
  41951. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  41952. break;
  41953. case "planes":
  41954. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  41955. break;
  41956. case "torusKnots":
  41957. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  41958. break;
  41959. case "vertexData":
  41960. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  41961. break;
  41962. }
  41963. found = true;
  41964. }
  41965. });
  41966. }
  41967. });
  41968. if (!found) {
  41969. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  41970. }
  41971. }
  41972. }
  41973. // Material ?
  41974. if (parsedMesh.materialId) {
  41975. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  41976. if (!materialFound && parsedData.multiMaterials) {
  41977. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  41978. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  41979. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  41980. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  41981. var subMatId = parsedMultiMaterial.materials[matIndex];
  41982. loadedMaterialsIds.push(subMatId);
  41983. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  41984. log += "\n\tMaterial " + mat.toString(fullDetails);
  41985. }
  41986. loadedMaterialsIds.push(parsedMultiMaterial.id);
  41987. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  41988. materialFound = true;
  41989. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  41990. break;
  41991. }
  41992. }
  41993. }
  41994. if (!materialFound) {
  41995. loadedMaterialsIds.push(parsedMesh.materialId);
  41996. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  41997. if (!mat) {
  41998. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  41999. }
  42000. else {
  42001. log += "\n\tMaterial " + mat.toString(fullDetails);
  42002. }
  42003. }
  42004. }
  42005. // Skeleton ?
  42006. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  42007. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  42008. if (!skeletonAlreadyLoaded) {
  42009. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  42010. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  42011. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  42012. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  42013. skeletons.push(skeleton);
  42014. loadedSkeletonsIds.push(parsedSkeleton.id);
  42015. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  42016. }
  42017. }
  42018. }
  42019. }
  42020. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  42021. meshes.push(mesh);
  42022. log += "\n\tMesh " + mesh.toString(fullDetails);
  42023. }
  42024. }
  42025. // Connecting parents
  42026. var currentMesh;
  42027. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  42028. currentMesh = scene.meshes[index];
  42029. if (currentMesh._waitingParentId) {
  42030. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  42031. currentMesh._waitingParentId = undefined;
  42032. }
  42033. }
  42034. // freeze and compute world matrix application
  42035. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  42036. currentMesh = scene.meshes[index];
  42037. if (currentMesh._waitingFreezeWorldMatrix) {
  42038. currentMesh.freezeWorldMatrix();
  42039. currentMesh._waitingFreezeWorldMatrix = undefined;
  42040. }
  42041. else {
  42042. currentMesh.computeWorldMatrix(true);
  42043. }
  42044. }
  42045. // Particles
  42046. if (parsedData.particleSystems) {
  42047. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  42048. var parsedParticleSystem = parsedData.particleSystems[index];
  42049. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  42050. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  42051. }
  42052. }
  42053. }
  42054. return true;
  42055. }
  42056. catch (err) {
  42057. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  42058. log = null;
  42059. throw err;
  42060. }
  42061. finally {
  42062. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  42063. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  42064. }
  42065. }
  42066. },
  42067. load: function (scene, data, rootUrl) {
  42068. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  42069. // when SceneLoader.debugLogging = true (default), or exception encountered.
  42070. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  42071. // and avoid problems with multiple concurrent .babylon loads.
  42072. var log = "importScene has failed JSON parse";
  42073. try {
  42074. var parsedData = JSON.parse(data);
  42075. log = "";
  42076. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  42077. // Scene
  42078. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  42079. scene.autoClear = parsedData.autoClear;
  42080. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  42081. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  42082. if (parsedData.gravity) {
  42083. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  42084. }
  42085. // Fog
  42086. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  42087. scene.fogMode = parsedData.fogMode;
  42088. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  42089. scene.fogStart = parsedData.fogStart;
  42090. scene.fogEnd = parsedData.fogEnd;
  42091. scene.fogDensity = parsedData.fogDensity;
  42092. log += "\tFog mode for scene: ";
  42093. switch (scene.fogMode) {
  42094. // getters not compiling, so using hardcoded
  42095. case 1:
  42096. log += "exp\n";
  42097. break;
  42098. case 2:
  42099. log += "exp2\n";
  42100. break;
  42101. case 3:
  42102. log += "linear\n";
  42103. break;
  42104. }
  42105. }
  42106. //Physics
  42107. if (parsedData.physicsEnabled) {
  42108. var physicsPlugin;
  42109. if (parsedData.physicsEngine === "cannon") {
  42110. physicsPlugin = new BABYLON.CannonJSPlugin();
  42111. }
  42112. else if (parsedData.physicsEngine === "oimo") {
  42113. physicsPlugin = new BABYLON.OimoJSPlugin();
  42114. }
  42115. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  42116. //else - default engine, which is currently oimo
  42117. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  42118. scene.enablePhysics(physicsGravity, physicsPlugin);
  42119. }
  42120. // Metadata
  42121. if (parsedData.metadata !== undefined) {
  42122. scene.metadata = parsedData.metadata;
  42123. }
  42124. //collisions, if defined. otherwise, default is true
  42125. if (parsedData.collisionsEnabled != undefined) {
  42126. scene.collisionsEnabled = parsedData.collisionsEnabled;
  42127. }
  42128. scene.workerCollisions = !!parsedData.workerCollisions;
  42129. var index;
  42130. var cache;
  42131. // Lights
  42132. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  42133. var parsedLight = parsedData.lights[index];
  42134. var light = BABYLON.Light.Parse(parsedLight, scene);
  42135. log += (index === 0 ? "\n\tLights:" : "");
  42136. log += "\n\t\t" + light.toString(fullDetails);
  42137. }
  42138. // Animations
  42139. if (parsedData.animations) {
  42140. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  42141. var parsedAnimation = parsedData.animations[index];
  42142. var animation = BABYLON.Animation.Parse(parsedAnimation);
  42143. scene.animations.push(animation);
  42144. log += (index === 0 ? "\n\tAnimations:" : "");
  42145. log += "\n\t\t" + animation.toString(fullDetails);
  42146. }
  42147. }
  42148. if (parsedData.autoAnimate) {
  42149. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  42150. }
  42151. // Materials
  42152. if (parsedData.materials) {
  42153. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  42154. var parsedMaterial = parsedData.materials[index];
  42155. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  42156. log += (index === 0 ? "\n\tMaterials:" : "");
  42157. log += "\n\t\t" + mat.toString(fullDetails);
  42158. }
  42159. }
  42160. if (parsedData.multiMaterials) {
  42161. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  42162. var parsedMultiMaterial = parsedData.multiMaterials[index];
  42163. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  42164. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  42165. log += "\n\t\t" + mmat.toString(fullDetails);
  42166. }
  42167. }
  42168. // Morph targets
  42169. if (parsedData.morphTargetManagers) {
  42170. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  42171. var managerData = _a[_i];
  42172. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  42173. }
  42174. }
  42175. // Skeletons
  42176. if (parsedData.skeletons) {
  42177. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  42178. var parsedSkeleton = parsedData.skeletons[index];
  42179. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  42180. log += (index === 0 ? "\n\tSkeletons:" : "");
  42181. log += "\n\t\t" + skeleton.toString(fullDetails);
  42182. }
  42183. }
  42184. // Geometries
  42185. var geometries = parsedData.geometries;
  42186. if (geometries) {
  42187. // Boxes
  42188. var boxes = geometries.boxes;
  42189. if (boxes) {
  42190. for (index = 0, cache = boxes.length; index < cache; index++) {
  42191. var parsedBox = boxes[index];
  42192. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  42193. }
  42194. }
  42195. // Spheres
  42196. var spheres = geometries.spheres;
  42197. if (spheres) {
  42198. for (index = 0, cache = spheres.length; index < cache; index++) {
  42199. var parsedSphere = spheres[index];
  42200. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  42201. }
  42202. }
  42203. // Cylinders
  42204. var cylinders = geometries.cylinders;
  42205. if (cylinders) {
  42206. for (index = 0, cache = cylinders.length; index < cache; index++) {
  42207. var parsedCylinder = cylinders[index];
  42208. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  42209. }
  42210. }
  42211. // Toruses
  42212. var toruses = geometries.toruses;
  42213. if (toruses) {
  42214. for (index = 0, cache = toruses.length; index < cache; index++) {
  42215. var parsedTorus = toruses[index];
  42216. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  42217. }
  42218. }
  42219. // Grounds
  42220. var grounds = geometries.grounds;
  42221. if (grounds) {
  42222. for (index = 0, cache = grounds.length; index < cache; index++) {
  42223. var parsedGround = grounds[index];
  42224. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  42225. }
  42226. }
  42227. // Planes
  42228. var planes = geometries.planes;
  42229. if (planes) {
  42230. for (index = 0, cache = planes.length; index < cache; index++) {
  42231. var parsedPlane = planes[index];
  42232. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  42233. }
  42234. }
  42235. // TorusKnots
  42236. var torusKnots = geometries.torusKnots;
  42237. if (torusKnots) {
  42238. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  42239. var parsedTorusKnot = torusKnots[index];
  42240. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  42241. }
  42242. }
  42243. // VertexData
  42244. var vertexData = geometries.vertexData;
  42245. if (vertexData) {
  42246. for (index = 0, cache = vertexData.length; index < cache; index++) {
  42247. var parsedVertexData = vertexData[index];
  42248. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  42249. }
  42250. }
  42251. }
  42252. // Meshes
  42253. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  42254. var parsedMesh = parsedData.meshes[index];
  42255. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  42256. log += (index === 0 ? "\n\tMeshes:" : "");
  42257. log += "\n\t\t" + mesh.toString(fullDetails);
  42258. }
  42259. // Cameras
  42260. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  42261. var parsedCamera = parsedData.cameras[index];
  42262. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  42263. log += (index === 0 ? "\n\tCameras:" : "");
  42264. log += "\n\t\t" + camera.toString(fullDetails);
  42265. }
  42266. if (parsedData.activeCameraID) {
  42267. scene.setActiveCameraByID(parsedData.activeCameraID);
  42268. }
  42269. // Browsing all the graph to connect the dots
  42270. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  42271. var camera = scene.cameras[index];
  42272. if (camera._waitingParentId) {
  42273. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  42274. camera._waitingParentId = undefined;
  42275. }
  42276. }
  42277. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  42278. var light = scene.lights[index];
  42279. if (light._waitingParentId) {
  42280. light.parent = scene.getLastEntryByID(light._waitingParentId);
  42281. light._waitingParentId = undefined;
  42282. }
  42283. }
  42284. // Sounds
  42285. var loadedSounds = [];
  42286. var loadedSound;
  42287. if (BABYLON.AudioEngine && parsedData.sounds) {
  42288. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  42289. var parsedSound = parsedData.sounds[index];
  42290. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42291. if (!parsedSound.url)
  42292. parsedSound.url = parsedSound.name;
  42293. if (!loadedSounds[parsedSound.url]) {
  42294. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  42295. loadedSounds[parsedSound.url] = loadedSound;
  42296. }
  42297. else {
  42298. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  42299. }
  42300. }
  42301. else {
  42302. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  42303. }
  42304. }
  42305. }
  42306. loadedSounds = [];
  42307. // Connect parents & children and parse actions
  42308. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  42309. var mesh = scene.meshes[index];
  42310. if (mesh._waitingParentId) {
  42311. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  42312. mesh._waitingParentId = undefined;
  42313. }
  42314. if (mesh._waitingActions) {
  42315. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  42316. mesh._waitingActions = undefined;
  42317. }
  42318. }
  42319. // freeze world matrix application
  42320. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  42321. var currentMesh = scene.meshes[index];
  42322. if (currentMesh._waitingFreezeWorldMatrix) {
  42323. currentMesh.freezeWorldMatrix();
  42324. currentMesh._waitingFreezeWorldMatrix = undefined;
  42325. }
  42326. else {
  42327. currentMesh.computeWorldMatrix(true);
  42328. }
  42329. }
  42330. // Particles Systems
  42331. if (parsedData.particleSystems) {
  42332. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  42333. var parsedParticleSystem = parsedData.particleSystems[index];
  42334. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  42335. }
  42336. }
  42337. // Lens flares
  42338. if (parsedData.lensFlareSystems) {
  42339. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  42340. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  42341. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  42342. }
  42343. }
  42344. // Shadows
  42345. if (parsedData.shadowGenerators) {
  42346. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  42347. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  42348. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  42349. }
  42350. }
  42351. // Lights exclusions / inclusions
  42352. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  42353. var light = scene.lights[index];
  42354. // Excluded check
  42355. if (light._excludedMeshesIds.length > 0) {
  42356. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  42357. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  42358. if (excludedMesh) {
  42359. light.excludedMeshes.push(excludedMesh);
  42360. }
  42361. }
  42362. light._excludedMeshesIds = [];
  42363. }
  42364. // Included check
  42365. if (light._includedOnlyMeshesIds.length > 0) {
  42366. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  42367. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  42368. if (includedOnlyMesh) {
  42369. light.includedOnlyMeshes.push(includedOnlyMesh);
  42370. }
  42371. }
  42372. light._includedOnlyMeshesIds = [];
  42373. }
  42374. }
  42375. // Actions (scene)
  42376. if (parsedData.actions) {
  42377. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  42378. }
  42379. // Finish
  42380. return true;
  42381. }
  42382. catch (err) {
  42383. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  42384. log = null;
  42385. throw err;
  42386. }
  42387. finally {
  42388. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  42389. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  42390. }
  42391. }
  42392. }
  42393. });
  42394. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42395. })(BABYLON || (BABYLON = {}));
  42396. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  42397. var BABYLON;
  42398. (function (BABYLON) {
  42399. var FilesInput = (function () {
  42400. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  42401. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  42402. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  42403. this._engine = p_engine;
  42404. this._canvas = p_canvas;
  42405. this._currentScene = p_scene;
  42406. this._sceneLoadedCallback = p_sceneLoadedCallback;
  42407. this._progressCallback = p_progressCallback;
  42408. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  42409. this._textureLoadingCallback = p_textureLoadingCallback;
  42410. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  42411. }
  42412. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  42413. var _this = this;
  42414. if (p_elementToMonitor) {
  42415. this._elementToMonitor = p_elementToMonitor;
  42416. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  42417. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  42418. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  42419. }
  42420. };
  42421. FilesInput.prototype.renderFunction = function () {
  42422. if (this._additionnalRenderLoopLogicCallback) {
  42423. this._additionnalRenderLoopLogicCallback();
  42424. }
  42425. if (this._currentScene) {
  42426. if (this._textureLoadingCallback) {
  42427. var remaining = this._currentScene.getWaitingItemsCount();
  42428. if (remaining > 0) {
  42429. this._textureLoadingCallback(remaining);
  42430. }
  42431. }
  42432. this._currentScene.render();
  42433. }
  42434. };
  42435. FilesInput.prototype.drag = function (e) {
  42436. e.stopPropagation();
  42437. e.preventDefault();
  42438. };
  42439. FilesInput.prototype.drop = function (eventDrop) {
  42440. eventDrop.stopPropagation();
  42441. eventDrop.preventDefault();
  42442. this.loadFiles(eventDrop);
  42443. };
  42444. FilesInput.prototype.loadFiles = function (event) {
  42445. if (this._startingProcessingFilesCallback)
  42446. this._startingProcessingFilesCallback();
  42447. // Handling data transfer via drag'n'drop
  42448. if (event && event.dataTransfer && event.dataTransfer.files) {
  42449. this._filesToLoad = event.dataTransfer.files;
  42450. }
  42451. // Handling files from input files
  42452. if (event && event.target && event.target.files) {
  42453. this._filesToLoad = event.target.files;
  42454. }
  42455. if (this._filesToLoad && this._filesToLoad.length > 0) {
  42456. for (var i = 0; i < this._filesToLoad.length; i++) {
  42457. var name_1 = this._filesToLoad[i].name.toLowerCase();
  42458. var extension = name_1.split('.').pop();
  42459. var type = this._filesToLoad[i].type;
  42460. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  42461. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  42462. this._sceneFileToLoad = this._filesToLoad[i];
  42463. }
  42464. else {
  42465. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  42466. }
  42467. }
  42468. this.reload();
  42469. }
  42470. };
  42471. FilesInput.prototype.reload = function () {
  42472. var _this = this;
  42473. var that = this;
  42474. // If a ".babylon" file has been provided
  42475. if (this._sceneFileToLoad) {
  42476. if (this._currentScene) {
  42477. if (BABYLON.Tools.errorsCount > 0) {
  42478. BABYLON.Tools.ClearLogCache();
  42479. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  42480. }
  42481. this._engine.stopRenderLoop();
  42482. this._currentScene.dispose();
  42483. }
  42484. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  42485. that._currentScene = newScene;
  42486. // Wait for textures and shaders to be ready
  42487. that._currentScene.executeWhenReady(function () {
  42488. if (that._sceneLoadedCallback) {
  42489. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  42490. }
  42491. that._engine.runRenderLoop(function () { that.renderFunction(); });
  42492. });
  42493. }, function (progress) {
  42494. if (_this._progressCallback) {
  42495. _this._progressCallback(progress);
  42496. }
  42497. });
  42498. }
  42499. else {
  42500. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  42501. }
  42502. };
  42503. return FilesInput;
  42504. }());
  42505. FilesInput.FilesToLoad = new Array();
  42506. BABYLON.FilesInput = FilesInput;
  42507. })(BABYLON || (BABYLON = {}));
  42508. //# sourceMappingURL=babylon.filesInput.js.map
  42509. var BABYLON;
  42510. (function (BABYLON) {
  42511. /**
  42512. * This class implement a typical dictionary using a string as key and the generic type T as value.
  42513. * The underlying implementation relies on an associative array to ensure the best performances.
  42514. * The value can be anything including 'null' but except 'undefined'
  42515. */
  42516. var StringDictionary = (function () {
  42517. function StringDictionary() {
  42518. this._count = 0;
  42519. this._data = {};
  42520. }
  42521. /**
  42522. * This will clear this dictionary and copy the content from the 'source' one.
  42523. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  42524. * @param source the dictionary to take the content from and copy to this dictionary
  42525. */
  42526. StringDictionary.prototype.copyFrom = function (source) {
  42527. var _this = this;
  42528. this.clear();
  42529. source.forEach(function (t, v) { return _this.add(t, v); });
  42530. };
  42531. /**
  42532. * Get a value based from its key
  42533. * @param key the given key to get the matching value from
  42534. * @return the value if found, otherwise undefined is returned
  42535. */
  42536. StringDictionary.prototype.get = function (key) {
  42537. var val = this._data[key];
  42538. if (val !== undefined) {
  42539. return val;
  42540. }
  42541. return undefined;
  42542. };
  42543. /**
  42544. * Get a value from its key or add it if it doesn't exist.
  42545. * This method will ensure you that a given key/data will be present in the dictionary.
  42546. * @param key the given key to get the matching value from
  42547. * @param factory the factory that will create the value if the key is not present in the dictionary.
  42548. * The factory will only be invoked if there's no data for the given key.
  42549. * @return the value corresponding to the key.
  42550. */
  42551. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  42552. var val = this.get(key);
  42553. if (val !== undefined) {
  42554. return val;
  42555. }
  42556. val = factory(key);
  42557. if (val) {
  42558. this.add(key, val);
  42559. }
  42560. return val;
  42561. };
  42562. /**
  42563. * Get a value from its key if present in the dictionary otherwise add it
  42564. * @param key the key to get the value from
  42565. * @param val if there's no such key/value pair in the dictionary add it with this value
  42566. * @return the value corresponding to the key
  42567. */
  42568. StringDictionary.prototype.getOrAdd = function (key, val) {
  42569. var curVal = this.get(key);
  42570. if (curVal !== undefined) {
  42571. return curVal;
  42572. }
  42573. this.add(key, val);
  42574. return val;
  42575. };
  42576. /**
  42577. * Check if there's a given key in the dictionary
  42578. * @param key the key to check for
  42579. * @return true if the key is present, false otherwise
  42580. */
  42581. StringDictionary.prototype.contains = function (key) {
  42582. return this._data[key] !== undefined;
  42583. };
  42584. /**
  42585. * Add a new key and its corresponding value
  42586. * @param key the key to add
  42587. * @param value the value corresponding to the key
  42588. * @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
  42589. */
  42590. StringDictionary.prototype.add = function (key, value) {
  42591. if (this._data[key] !== undefined) {
  42592. return false;
  42593. }
  42594. this._data[key] = value;
  42595. ++this._count;
  42596. return true;
  42597. };
  42598. StringDictionary.prototype.set = function (key, value) {
  42599. if (this._data[key] === undefined) {
  42600. return false;
  42601. }
  42602. this._data[key] = value;
  42603. return true;
  42604. };
  42605. /**
  42606. * Get the element of the given key and remove it from the dictionary
  42607. * @param key
  42608. */
  42609. StringDictionary.prototype.getAndRemove = function (key) {
  42610. var val = this.get(key);
  42611. if (val !== undefined) {
  42612. delete this._data[key];
  42613. --this._count;
  42614. return val;
  42615. }
  42616. return null;
  42617. };
  42618. /**
  42619. * Remove a key/value from the dictionary.
  42620. * @param key the key to remove
  42621. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  42622. */
  42623. StringDictionary.prototype.remove = function (key) {
  42624. if (this.contains(key)) {
  42625. delete this._data[key];
  42626. --this._count;
  42627. return true;
  42628. }
  42629. return false;
  42630. };
  42631. /**
  42632. * Clear the whole content of the dictionary
  42633. */
  42634. StringDictionary.prototype.clear = function () {
  42635. this._data = {};
  42636. this._count = 0;
  42637. };
  42638. Object.defineProperty(StringDictionary.prototype, "count", {
  42639. get: function () {
  42640. return this._count;
  42641. },
  42642. enumerable: true,
  42643. configurable: true
  42644. });
  42645. /**
  42646. * Execute a callback on each key/val of the dictionary.
  42647. * Note that you can remove any element in this dictionary in the callback implementation
  42648. * @param callback the callback to execute on a given key/value pair
  42649. */
  42650. StringDictionary.prototype.forEach = function (callback) {
  42651. for (var cur in this._data) {
  42652. var val = this._data[cur];
  42653. callback(cur, val);
  42654. }
  42655. };
  42656. /**
  42657. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  42658. * If the callback returns null or undefined the method will iterate to the next key/value pair
  42659. * Note that you can remove any element in this dictionary in the callback implementation
  42660. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  42661. */
  42662. StringDictionary.prototype.first = function (callback) {
  42663. for (var cur in this._data) {
  42664. var val = this._data[cur];
  42665. var res = callback(cur, val);
  42666. if (res) {
  42667. return res;
  42668. }
  42669. }
  42670. return null;
  42671. };
  42672. return StringDictionary;
  42673. }());
  42674. BABYLON.StringDictionary = StringDictionary;
  42675. })(BABYLON || (BABYLON = {}));
  42676. //# sourceMappingURL=babylon.stringDictionary.js.map
  42677. var BABYLON;
  42678. (function (BABYLON) {
  42679. var Tags = (function () {
  42680. function Tags() {
  42681. }
  42682. Tags.EnableFor = function (obj) {
  42683. obj._tags = obj._tags || {};
  42684. obj.hasTags = function () {
  42685. return Tags.HasTags(obj);
  42686. };
  42687. obj.addTags = function (tagsString) {
  42688. return Tags.AddTagsTo(obj, tagsString);
  42689. };
  42690. obj.removeTags = function (tagsString) {
  42691. return Tags.RemoveTagsFrom(obj, tagsString);
  42692. };
  42693. obj.matchesTagsQuery = function (tagsQuery) {
  42694. return Tags.MatchesQuery(obj, tagsQuery);
  42695. };
  42696. };
  42697. Tags.DisableFor = function (obj) {
  42698. delete obj._tags;
  42699. delete obj.hasTags;
  42700. delete obj.addTags;
  42701. delete obj.removeTags;
  42702. delete obj.matchesTagsQuery;
  42703. };
  42704. Tags.HasTags = function (obj) {
  42705. if (!obj._tags) {
  42706. return false;
  42707. }
  42708. return !BABYLON.Tools.IsEmpty(obj._tags);
  42709. };
  42710. Tags.GetTags = function (obj, asString) {
  42711. if (asString === void 0) { asString = true; }
  42712. if (!obj._tags) {
  42713. return null;
  42714. }
  42715. if (asString) {
  42716. var tagsArray = [];
  42717. for (var tag in obj._tags) {
  42718. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  42719. tagsArray.push(tag);
  42720. }
  42721. }
  42722. return tagsArray.join(" ");
  42723. }
  42724. else {
  42725. return obj._tags;
  42726. }
  42727. };
  42728. // the tags 'true' and 'false' are reserved and cannot be used as tags
  42729. // a tag cannot start with '||', '&&', and '!'
  42730. // it cannot contain whitespaces
  42731. Tags.AddTagsTo = function (obj, tagsString) {
  42732. if (!tagsString) {
  42733. return;
  42734. }
  42735. if (typeof tagsString !== "string") {
  42736. return;
  42737. }
  42738. var tags = tagsString.split(" ");
  42739. tags.forEach(function (tag, index, array) {
  42740. Tags._AddTagTo(obj, tag);
  42741. });
  42742. };
  42743. Tags._AddTagTo = function (obj, tag) {
  42744. tag = tag.trim();
  42745. if (tag === "" || tag === "true" || tag === "false") {
  42746. return;
  42747. }
  42748. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  42749. return;
  42750. }
  42751. Tags.EnableFor(obj);
  42752. obj._tags[tag] = true;
  42753. };
  42754. Tags.RemoveTagsFrom = function (obj, tagsString) {
  42755. if (!Tags.HasTags(obj)) {
  42756. return;
  42757. }
  42758. var tags = tagsString.split(" ");
  42759. for (var t in tags) {
  42760. Tags._RemoveTagFrom(obj, tags[t]);
  42761. }
  42762. };
  42763. Tags._RemoveTagFrom = function (obj, tag) {
  42764. delete obj._tags[tag];
  42765. };
  42766. Tags.MatchesQuery = function (obj, tagsQuery) {
  42767. if (tagsQuery === undefined) {
  42768. return true;
  42769. }
  42770. if (tagsQuery === "") {
  42771. return Tags.HasTags(obj);
  42772. }
  42773. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  42774. };
  42775. return Tags;
  42776. }());
  42777. BABYLON.Tags = Tags;
  42778. })(BABYLON || (BABYLON = {}));
  42779. //# sourceMappingURL=babylon.tags.js.map
  42780. var BABYLON;
  42781. (function (BABYLON) {
  42782. var Internals;
  42783. (function (Internals) {
  42784. var AndOrNotEvaluator = (function () {
  42785. function AndOrNotEvaluator() {
  42786. }
  42787. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  42788. if (!query.match(/\([^\(\)]*\)/g)) {
  42789. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  42790. }
  42791. else {
  42792. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  42793. // remove parenthesis
  42794. r = r.slice(1, r.length - 1);
  42795. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  42796. });
  42797. }
  42798. if (query === "true") {
  42799. return true;
  42800. }
  42801. if (query === "false") {
  42802. return false;
  42803. }
  42804. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  42805. };
  42806. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  42807. evaluateCallback = evaluateCallback || (function (r) {
  42808. return r === "true" ? true : false;
  42809. });
  42810. var result;
  42811. var or = parenthesisContent.split("||");
  42812. for (var i in or) {
  42813. if (or.hasOwnProperty(i)) {
  42814. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  42815. var and = ori.split("&&");
  42816. if (and.length > 1) {
  42817. for (var j = 0; j < and.length; ++j) {
  42818. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  42819. if (andj !== "true" && andj !== "false") {
  42820. if (andj[0] === "!") {
  42821. result = !evaluateCallback(andj.substring(1));
  42822. }
  42823. else {
  42824. result = evaluateCallback(andj);
  42825. }
  42826. }
  42827. else {
  42828. result = andj === "true" ? true : false;
  42829. }
  42830. if (!result) {
  42831. ori = "false";
  42832. break;
  42833. }
  42834. }
  42835. }
  42836. if (result || ori === "true") {
  42837. result = true;
  42838. break;
  42839. }
  42840. // result equals false (or undefined)
  42841. if (ori !== "true" && ori !== "false") {
  42842. if (ori[0] === "!") {
  42843. result = !evaluateCallback(ori.substring(1));
  42844. }
  42845. else {
  42846. result = evaluateCallback(ori);
  42847. }
  42848. }
  42849. else {
  42850. result = ori === "true" ? true : false;
  42851. }
  42852. }
  42853. }
  42854. // the whole parenthesis scope is replaced by 'true' or 'false'
  42855. return result ? "true" : "false";
  42856. };
  42857. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  42858. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  42859. // remove whitespaces
  42860. r = r.replace(/[\s]/g, function () { return ""; });
  42861. return r.length % 2 ? "!" : "";
  42862. });
  42863. booleanString = booleanString.trim();
  42864. if (booleanString === "!true") {
  42865. booleanString = "false";
  42866. }
  42867. else if (booleanString === "!false") {
  42868. booleanString = "true";
  42869. }
  42870. return booleanString;
  42871. };
  42872. return AndOrNotEvaluator;
  42873. }());
  42874. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  42875. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42876. })(BABYLON || (BABYLON = {}));
  42877. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  42878. var BABYLON;
  42879. (function (BABYLON) {
  42880. var Database = (function () {
  42881. function Database(urlToScene, callbackManifestChecked) {
  42882. // Handling various flavors of prefixed version of IndexedDB
  42883. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  42884. this.callbackManifestChecked = callbackManifestChecked;
  42885. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  42886. this.db = null;
  42887. this.enableSceneOffline = false;
  42888. this.enableTexturesOffline = false;
  42889. this.manifestVersionFound = 0;
  42890. this.mustUpdateRessources = false;
  42891. this.hasReachedQuota = false;
  42892. if (!Database.IDBStorageEnabled) {
  42893. this.callbackManifestChecked(true);
  42894. }
  42895. else {
  42896. this.checkManifestFile();
  42897. }
  42898. }
  42899. Database.prototype.checkManifestFile = function () {
  42900. var _this = this;
  42901. function noManifestFile() {
  42902. that.enableSceneOffline = false;
  42903. that.enableTexturesOffline = false;
  42904. that.callbackManifestChecked(false);
  42905. }
  42906. var that = this;
  42907. var timeStampUsed = false;
  42908. var manifestURL = this.currentSceneUrl + ".manifest";
  42909. var xhr = new XMLHttpRequest();
  42910. if (navigator.onLine) {
  42911. // Adding a timestamp to by-pass browsers' cache
  42912. timeStampUsed = true;
  42913. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  42914. }
  42915. xhr.open("GET", manifestURL, true);
  42916. xhr.addEventListener("load", function () {
  42917. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  42918. try {
  42919. var manifestFile = JSON.parse(xhr.response);
  42920. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  42921. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  42922. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  42923. _this.manifestVersionFound = manifestFile.version;
  42924. }
  42925. if (_this.callbackManifestChecked) {
  42926. _this.callbackManifestChecked(true);
  42927. }
  42928. }
  42929. catch (ex) {
  42930. noManifestFile();
  42931. }
  42932. }
  42933. else {
  42934. noManifestFile();
  42935. }
  42936. }, false);
  42937. xhr.addEventListener("error", function (event) {
  42938. if (timeStampUsed) {
  42939. timeStampUsed = false;
  42940. // Let's retry without the timeStamp
  42941. // It could fail when coupled with HTML5 Offline API
  42942. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  42943. xhr.open("GET", retryManifestURL, true);
  42944. xhr.send();
  42945. }
  42946. else {
  42947. noManifestFile();
  42948. }
  42949. }, false);
  42950. try {
  42951. xhr.send();
  42952. }
  42953. catch (ex) {
  42954. BABYLON.Tools.Error("Error on XHR send request.");
  42955. that.callbackManifestChecked(false);
  42956. }
  42957. };
  42958. Database.prototype.openAsync = function (successCallback, errorCallback) {
  42959. var _this = this;
  42960. function handleError() {
  42961. that.isSupported = false;
  42962. if (errorCallback)
  42963. errorCallback();
  42964. }
  42965. var that = this;
  42966. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  42967. // Your browser doesn't support IndexedDB
  42968. this.isSupported = false;
  42969. if (errorCallback)
  42970. errorCallback();
  42971. }
  42972. else {
  42973. // If the DB hasn't been opened or created yet
  42974. if (!this.db) {
  42975. this.hasReachedQuota = false;
  42976. this.isSupported = true;
  42977. var request = this.idbFactory.open("babylonjs", 1);
  42978. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  42979. request.onerror = function (event) {
  42980. handleError();
  42981. };
  42982. // executes when a version change transaction cannot complete due to other active transactions
  42983. request.onblocked = function (event) {
  42984. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  42985. handleError();
  42986. };
  42987. // DB has been opened successfully
  42988. request.onsuccess = function (event) {
  42989. _this.db = request.result;
  42990. successCallback();
  42991. };
  42992. // Initialization of the DB. Creating Scenes & Textures stores
  42993. request.onupgradeneeded = function (event) {
  42994. _this.db = (event.target).result;
  42995. try {
  42996. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  42997. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  42998. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  42999. }
  43000. catch (ex) {
  43001. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  43002. handleError();
  43003. }
  43004. };
  43005. }
  43006. else {
  43007. if (successCallback)
  43008. successCallback();
  43009. }
  43010. }
  43011. };
  43012. Database.prototype.loadImageFromDB = function (url, image) {
  43013. var _this = this;
  43014. var completeURL = Database.ReturnFullUrlLocation(url);
  43015. var saveAndLoadImage = function () {
  43016. if (!_this.hasReachedQuota && _this.db !== null) {
  43017. // the texture is not yet in the DB, let's try to save it
  43018. _this._saveImageIntoDBAsync(completeURL, image);
  43019. }
  43020. else {
  43021. image.src = url;
  43022. }
  43023. };
  43024. if (!this.mustUpdateRessources) {
  43025. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  43026. }
  43027. else {
  43028. saveAndLoadImage();
  43029. }
  43030. };
  43031. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  43032. if (this.isSupported && this.db !== null) {
  43033. var texture;
  43034. var transaction = this.db.transaction(["textures"]);
  43035. transaction.onabort = function (event) {
  43036. image.src = url;
  43037. };
  43038. transaction.oncomplete = function (event) {
  43039. var blobTextureURL;
  43040. if (texture) {
  43041. var URL = window.URL || window.webkitURL;
  43042. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  43043. image.onerror = function () {
  43044. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  43045. image.src = url;
  43046. };
  43047. image.src = blobTextureURL;
  43048. }
  43049. else {
  43050. notInDBCallback();
  43051. }
  43052. };
  43053. var getRequest = transaction.objectStore("textures").get(url);
  43054. getRequest.onsuccess = function (event) {
  43055. texture = (event.target).result;
  43056. };
  43057. getRequest.onerror = function (event) {
  43058. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  43059. image.src = url;
  43060. };
  43061. }
  43062. else {
  43063. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  43064. image.src = url;
  43065. }
  43066. };
  43067. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  43068. var _this = this;
  43069. if (this.isSupported) {
  43070. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  43071. var generateBlobUrl = function () {
  43072. var blobTextureURL;
  43073. if (blob) {
  43074. var URL = window.URL || window.webkitURL;
  43075. try {
  43076. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  43077. }
  43078. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  43079. catch (ex) {
  43080. blobTextureURL = URL.createObjectURL(blob);
  43081. }
  43082. }
  43083. image.src = blobTextureURL;
  43084. };
  43085. if (Database.IsUASupportingBlobStorage) {
  43086. var xhr = new XMLHttpRequest(), blob;
  43087. xhr.open("GET", url, true);
  43088. xhr.responseType = "blob";
  43089. xhr.addEventListener("load", function () {
  43090. if (xhr.status === 200) {
  43091. // Blob as response (XHR2)
  43092. blob = xhr.response;
  43093. var transaction = _this.db.transaction(["textures"], "readwrite");
  43094. // the transaction could abort because of a QuotaExceededError error
  43095. transaction.onabort = function (event) {
  43096. try {
  43097. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  43098. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  43099. _this.hasReachedQuota = true;
  43100. }
  43101. }
  43102. catch (ex) { }
  43103. generateBlobUrl();
  43104. };
  43105. transaction.oncomplete = function (event) {
  43106. generateBlobUrl();
  43107. };
  43108. var newTexture = { textureUrl: url, data: blob };
  43109. try {
  43110. // Put the blob into the dabase
  43111. var addRequest = transaction.objectStore("textures").put(newTexture);
  43112. addRequest.onsuccess = function (event) {
  43113. };
  43114. addRequest.onerror = function (event) {
  43115. generateBlobUrl();
  43116. };
  43117. }
  43118. catch (ex) {
  43119. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  43120. if (ex.code === 25) {
  43121. Database.IsUASupportingBlobStorage = false;
  43122. }
  43123. image.src = url;
  43124. }
  43125. }
  43126. else {
  43127. image.src = url;
  43128. }
  43129. }, false);
  43130. xhr.addEventListener("error", function (event) {
  43131. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  43132. image.src = url;
  43133. }, false);
  43134. xhr.send();
  43135. }
  43136. else {
  43137. image.src = url;
  43138. }
  43139. }
  43140. else {
  43141. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  43142. image.src = url;
  43143. }
  43144. };
  43145. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  43146. var _this = this;
  43147. var updateVersion = function (event) {
  43148. // the version is not yet in the DB or we need to update it
  43149. _this._saveVersionIntoDBAsync(url, versionLoaded);
  43150. };
  43151. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  43152. };
  43153. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  43154. var _this = this;
  43155. if (this.isSupported) {
  43156. var version;
  43157. try {
  43158. var transaction = this.db.transaction(["versions"]);
  43159. transaction.oncomplete = function (event) {
  43160. if (version) {
  43161. // If the version in the JSON file is > than the version in DB
  43162. if (_this.manifestVersionFound > version.data) {
  43163. _this.mustUpdateRessources = true;
  43164. updateInDBCallback();
  43165. }
  43166. else {
  43167. callback(version.data);
  43168. }
  43169. }
  43170. else {
  43171. _this.mustUpdateRessources = true;
  43172. updateInDBCallback();
  43173. }
  43174. };
  43175. transaction.onabort = function (event) {
  43176. callback(-1);
  43177. };
  43178. var getRequest = transaction.objectStore("versions").get(url);
  43179. getRequest.onsuccess = function (event) {
  43180. version = (event.target).result;
  43181. };
  43182. getRequest.onerror = function (event) {
  43183. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  43184. callback(-1);
  43185. };
  43186. }
  43187. catch (ex) {
  43188. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  43189. callback(-1);
  43190. }
  43191. }
  43192. else {
  43193. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  43194. callback(-1);
  43195. }
  43196. };
  43197. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  43198. var _this = this;
  43199. if (this.isSupported && !this.hasReachedQuota) {
  43200. try {
  43201. // Open a transaction to the database
  43202. var transaction = this.db.transaction(["versions"], "readwrite");
  43203. // the transaction could abort because of a QuotaExceededError error
  43204. transaction.onabort = function (event) {
  43205. try {
  43206. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  43207. _this.hasReachedQuota = true;
  43208. }
  43209. }
  43210. catch (ex) { }
  43211. callback(-1);
  43212. };
  43213. transaction.oncomplete = function (event) {
  43214. callback(_this.manifestVersionFound);
  43215. };
  43216. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  43217. // Put the scene into the database
  43218. var addRequest = transaction.objectStore("versions").put(newVersion);
  43219. addRequest.onsuccess = function (event) {
  43220. };
  43221. addRequest.onerror = function (event) {
  43222. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  43223. };
  43224. }
  43225. catch (ex) {
  43226. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  43227. callback(-1);
  43228. }
  43229. }
  43230. else {
  43231. callback(-1);
  43232. }
  43233. };
  43234. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  43235. var _this = this;
  43236. var completeUrl = Database.ReturnFullUrlLocation(url);
  43237. var saveAndLoadFile = function (event) {
  43238. // the scene is not yet in the DB, let's try to save it
  43239. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  43240. };
  43241. this._checkVersionFromDB(completeUrl, function (version) {
  43242. if (version !== -1) {
  43243. if (!_this.mustUpdateRessources) {
  43244. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  43245. }
  43246. else {
  43247. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  43248. }
  43249. }
  43250. else {
  43251. errorCallback();
  43252. }
  43253. });
  43254. };
  43255. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  43256. if (this.isSupported) {
  43257. var targetStore;
  43258. if (url.indexOf(".babylon") !== -1) {
  43259. targetStore = "scenes";
  43260. }
  43261. else {
  43262. targetStore = "textures";
  43263. }
  43264. var file;
  43265. var transaction = this.db.transaction([targetStore]);
  43266. transaction.oncomplete = function (event) {
  43267. if (file) {
  43268. callback(file.data);
  43269. }
  43270. else {
  43271. notInDBCallback();
  43272. }
  43273. };
  43274. transaction.onabort = function (event) {
  43275. notInDBCallback();
  43276. };
  43277. var getRequest = transaction.objectStore(targetStore).get(url);
  43278. getRequest.onsuccess = function (event) {
  43279. file = (event.target).result;
  43280. };
  43281. getRequest.onerror = function (event) {
  43282. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  43283. notInDBCallback();
  43284. };
  43285. }
  43286. else {
  43287. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  43288. callback();
  43289. }
  43290. };
  43291. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  43292. var _this = this;
  43293. if (this.isSupported) {
  43294. var targetStore;
  43295. if (url.indexOf(".babylon") !== -1) {
  43296. targetStore = "scenes";
  43297. }
  43298. else {
  43299. targetStore = "textures";
  43300. }
  43301. // Create XHR
  43302. var xhr = new XMLHttpRequest(), fileData;
  43303. xhr.open("GET", url, true);
  43304. if (useArrayBuffer) {
  43305. xhr.responseType = "arraybuffer";
  43306. }
  43307. xhr.onprogress = progressCallback;
  43308. xhr.addEventListener("load", function () {
  43309. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  43310. // Blob as response (XHR2)
  43311. //fileData = xhr.responseText;
  43312. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  43313. if (!_this.hasReachedQuota) {
  43314. // Open a transaction to the database
  43315. var transaction = _this.db.transaction([targetStore], "readwrite");
  43316. // the transaction could abort because of a QuotaExceededError error
  43317. transaction.onabort = function (event) {
  43318. try {
  43319. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  43320. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  43321. _this.hasReachedQuota = true;
  43322. }
  43323. }
  43324. catch (ex) { }
  43325. callback(fileData);
  43326. };
  43327. transaction.oncomplete = function (event) {
  43328. callback(fileData);
  43329. };
  43330. var newFile;
  43331. if (targetStore === "scenes") {
  43332. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  43333. }
  43334. else {
  43335. newFile = { textureUrl: url, data: fileData };
  43336. }
  43337. try {
  43338. // Put the scene into the database
  43339. var addRequest = transaction.objectStore(targetStore).put(newFile);
  43340. addRequest.onsuccess = function (event) {
  43341. };
  43342. addRequest.onerror = function (event) {
  43343. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  43344. };
  43345. }
  43346. catch (ex) {
  43347. callback(fileData);
  43348. }
  43349. }
  43350. else {
  43351. callback(fileData);
  43352. }
  43353. }
  43354. else {
  43355. callback();
  43356. }
  43357. }, false);
  43358. xhr.addEventListener("error", function (event) {
  43359. BABYLON.Tools.Error("error on XHR request.");
  43360. callback();
  43361. }, false);
  43362. xhr.send();
  43363. }
  43364. else {
  43365. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  43366. callback();
  43367. }
  43368. };
  43369. return Database;
  43370. }());
  43371. Database.IsUASupportingBlobStorage = true;
  43372. Database.IDBStorageEnabled = true;
  43373. Database.parseURL = function (url) {
  43374. var a = document.createElement('a');
  43375. a.href = url;
  43376. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  43377. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  43378. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  43379. return absLocation;
  43380. };
  43381. Database.ReturnFullUrlLocation = function (url) {
  43382. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  43383. return (Database.parseURL(window.location.href) + url);
  43384. }
  43385. else {
  43386. return url;
  43387. }
  43388. };
  43389. BABYLON.Database = Database;
  43390. })(BABYLON || (BABYLON = {}));
  43391. //# sourceMappingURL=babylon.database.js.map
  43392. var BABYLON;
  43393. (function (BABYLON) {
  43394. var FresnelParameters = (function () {
  43395. function FresnelParameters() {
  43396. this._isEnabled = true;
  43397. this.leftColor = BABYLON.Color3.White();
  43398. this.rightColor = BABYLON.Color3.Black();
  43399. this.bias = 0;
  43400. this.power = 1;
  43401. }
  43402. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  43403. get: function () {
  43404. return this._isEnabled;
  43405. },
  43406. set: function (value) {
  43407. if (this._isEnabled === value) {
  43408. return;
  43409. }
  43410. this._isEnabled = value;
  43411. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43412. },
  43413. enumerable: true,
  43414. configurable: true
  43415. });
  43416. FresnelParameters.prototype.clone = function () {
  43417. var newFresnelParameters = new FresnelParameters();
  43418. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  43419. return newFresnelParameters;
  43420. };
  43421. FresnelParameters.prototype.serialize = function () {
  43422. var serializationObject = {};
  43423. serializationObject.isEnabled = this.isEnabled;
  43424. serializationObject.leftColor = this.leftColor;
  43425. serializationObject.rightColor = this.rightColor;
  43426. serializationObject.bias = this.bias;
  43427. serializationObject.power = this.power;
  43428. return serializationObject;
  43429. };
  43430. FresnelParameters.Parse = function (parsedFresnelParameters) {
  43431. var fresnelParameters = new FresnelParameters();
  43432. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  43433. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  43434. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  43435. fresnelParameters.bias = parsedFresnelParameters.bias;
  43436. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  43437. return fresnelParameters;
  43438. };
  43439. return FresnelParameters;
  43440. }());
  43441. BABYLON.FresnelParameters = FresnelParameters;
  43442. })(BABYLON || (BABYLON = {}));
  43443. //# sourceMappingURL=babylon.fresnelParameters.js.map
  43444. var BABYLON;
  43445. (function (BABYLON) {
  43446. var MultiMaterial = (function (_super) {
  43447. __extends(MultiMaterial, _super);
  43448. function MultiMaterial(name, scene) {
  43449. var _this = _super.call(this, name, scene, true) || this;
  43450. _this.subMaterials = new Array();
  43451. scene.multiMaterials.push(_this);
  43452. return _this;
  43453. }
  43454. // Properties
  43455. MultiMaterial.prototype.getSubMaterial = function (index) {
  43456. if (index < 0 || index >= this.subMaterials.length) {
  43457. return this.getScene().defaultMaterial;
  43458. }
  43459. return this.subMaterials[index];
  43460. };
  43461. // Methods
  43462. MultiMaterial.prototype.getClassName = function () {
  43463. return "MultiMaterial";
  43464. };
  43465. MultiMaterial.prototype.isReady = function (mesh) {
  43466. for (var index = 0; index < this.subMaterials.length; index++) {
  43467. var subMaterial = this.subMaterials[index];
  43468. if (subMaterial) {
  43469. if (!this.subMaterials[index].isReady(mesh)) {
  43470. return false;
  43471. }
  43472. }
  43473. }
  43474. return true;
  43475. };
  43476. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  43477. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  43478. for (var index = 0; index < this.subMaterials.length; index++) {
  43479. var subMaterial = null;
  43480. if (cloneChildren) {
  43481. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  43482. }
  43483. else {
  43484. subMaterial = this.subMaterials[index];
  43485. }
  43486. newMultiMaterial.subMaterials.push(subMaterial);
  43487. }
  43488. return newMultiMaterial;
  43489. };
  43490. MultiMaterial.prototype.serialize = function () {
  43491. var serializationObject = {};
  43492. serializationObject.name = this.name;
  43493. serializationObject.id = this.id;
  43494. serializationObject.tags = BABYLON.Tags.GetTags(this);
  43495. serializationObject.materials = [];
  43496. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  43497. var subMat = this.subMaterials[matIndex];
  43498. if (subMat) {
  43499. serializationObject.materials.push(subMat.id);
  43500. }
  43501. else {
  43502. serializationObject.materials.push(null);
  43503. }
  43504. }
  43505. return serializationObject;
  43506. };
  43507. return MultiMaterial;
  43508. }(BABYLON.Material));
  43509. BABYLON.MultiMaterial = MultiMaterial;
  43510. })(BABYLON || (BABYLON = {}));
  43511. //# sourceMappingURL=babylon.multiMaterial.js.map
  43512. var BABYLON;
  43513. (function (BABYLON) {
  43514. var FreeCameraTouchInput = (function () {
  43515. function FreeCameraTouchInput() {
  43516. this._offsetX = null;
  43517. this._offsetY = null;
  43518. this._pointerCount = 0;
  43519. this._pointerPressed = [];
  43520. this.touchAngularSensibility = 200000.0;
  43521. this.touchMoveSensibility = 250.0;
  43522. }
  43523. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  43524. var _this = this;
  43525. var previousPosition;
  43526. if (this._pointerInput === undefined) {
  43527. this._onLostFocus = function (evt) {
  43528. _this._offsetX = null;
  43529. _this._offsetY = null;
  43530. };
  43531. this._pointerInput = function (p, s) {
  43532. var evt = p.event;
  43533. if (evt.pointerType === "mouse") {
  43534. return;
  43535. }
  43536. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  43537. if (!noPreventDefault) {
  43538. evt.preventDefault();
  43539. }
  43540. _this._pointerPressed.push(evt.pointerId);
  43541. if (_this._pointerPressed.length !== 1) {
  43542. return;
  43543. }
  43544. previousPosition = {
  43545. x: evt.clientX,
  43546. y: evt.clientY
  43547. };
  43548. }
  43549. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  43550. if (!noPreventDefault) {
  43551. evt.preventDefault();
  43552. }
  43553. var index = _this._pointerPressed.indexOf(evt.pointerId);
  43554. if (index === -1) {
  43555. return;
  43556. }
  43557. _this._pointerPressed.splice(index, 1);
  43558. if (index != 0) {
  43559. return;
  43560. }
  43561. previousPosition = null;
  43562. _this._offsetX = null;
  43563. _this._offsetY = null;
  43564. }
  43565. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43566. if (!noPreventDefault) {
  43567. evt.preventDefault();
  43568. }
  43569. if (!previousPosition) {
  43570. return;
  43571. }
  43572. var index = _this._pointerPressed.indexOf(evt.pointerId);
  43573. if (index != 0) {
  43574. return;
  43575. }
  43576. _this._offsetX = evt.clientX - previousPosition.x;
  43577. _this._offsetY = -(evt.clientY - previousPosition.y);
  43578. }
  43579. };
  43580. }
  43581. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43582. element.addEventListener("blur", this._onLostFocus);
  43583. };
  43584. FreeCameraTouchInput.prototype.detachControl = function (element) {
  43585. if (this._pointerInput && element) {
  43586. this.camera.getScene().onPointerObservable.remove(this._observer);
  43587. this._observer = null;
  43588. element.removeEventListener("blur", this._onLostFocus);
  43589. this._onLostFocus = null;
  43590. this._pointerPressed = [];
  43591. this._offsetX = null;
  43592. this._offsetY = null;
  43593. this._pointerCount = 0;
  43594. }
  43595. };
  43596. FreeCameraTouchInput.prototype.checkInputs = function () {
  43597. if (this._offsetX) {
  43598. var camera = this.camera;
  43599. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  43600. if (this._pointerPressed.length > 1) {
  43601. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  43602. }
  43603. else {
  43604. var speed = camera._computeLocalCameraSpeed();
  43605. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  43606. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  43607. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  43608. }
  43609. }
  43610. };
  43611. FreeCameraTouchInput.prototype.getTypeName = function () {
  43612. return "FreeCameraTouchInput";
  43613. };
  43614. FreeCameraTouchInput.prototype.getSimpleName = function () {
  43615. return "touch";
  43616. };
  43617. return FreeCameraTouchInput;
  43618. }());
  43619. __decorate([
  43620. BABYLON.serialize()
  43621. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  43622. __decorate([
  43623. BABYLON.serialize()
  43624. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  43625. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  43626. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  43627. })(BABYLON || (BABYLON = {}));
  43628. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  43629. /// <reference path="babylon.freeCamera.ts" />
  43630. var BABYLON;
  43631. (function (BABYLON) {
  43632. // We're mainly based on the logic defined into the FreeCamera code
  43633. var TouchCamera = (function (_super) {
  43634. __extends(TouchCamera, _super);
  43635. //-- end properties for backward compatibility for inputs
  43636. function TouchCamera(name, position, scene) {
  43637. var _this = _super.call(this, name, position, scene) || this;
  43638. _this.inputs.addTouch();
  43639. _this._setupInputs();
  43640. return _this;
  43641. }
  43642. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  43643. //-- Begin properties for backward compatibility for inputs
  43644. get: function () {
  43645. var touch = this.inputs.attached["touch"];
  43646. if (touch)
  43647. return touch.touchAngularSensibility;
  43648. },
  43649. set: function (value) {
  43650. var touch = this.inputs.attached["touch"];
  43651. if (touch)
  43652. touch.touchAngularSensibility = value;
  43653. },
  43654. enumerable: true,
  43655. configurable: true
  43656. });
  43657. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  43658. get: function () {
  43659. var touch = this.inputs.attached["touch"];
  43660. if (touch)
  43661. return touch.touchMoveSensibility;
  43662. },
  43663. set: function (value) {
  43664. var touch = this.inputs.attached["touch"];
  43665. if (touch)
  43666. touch.touchMoveSensibility = value;
  43667. },
  43668. enumerable: true,
  43669. configurable: true
  43670. });
  43671. TouchCamera.prototype.getClassName = function () {
  43672. return "TouchCamera";
  43673. };
  43674. TouchCamera.prototype._setupInputs = function () {
  43675. var mouse = this.inputs.attached["mouse"];
  43676. if (mouse) {
  43677. mouse.touchEnabled = false;
  43678. }
  43679. };
  43680. return TouchCamera;
  43681. }(BABYLON.FreeCamera));
  43682. BABYLON.TouchCamera = TouchCamera;
  43683. })(BABYLON || (BABYLON = {}));
  43684. //# sourceMappingURL=babylon.touchCamera.js.map
  43685. var BABYLON;
  43686. (function (BABYLON) {
  43687. var ProceduralTexture = (function (_super) {
  43688. __extends(ProceduralTexture, _super);
  43689. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  43690. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43691. if (isCube === void 0) { isCube = false; }
  43692. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  43693. _this.isCube = isCube;
  43694. _this.isEnabled = true;
  43695. _this._currentRefreshId = -1;
  43696. _this._refreshRate = 1;
  43697. _this._vertexBuffers = {};
  43698. _this._uniforms = new Array();
  43699. _this._samplers = new Array();
  43700. _this._textures = new Array();
  43701. _this._floats = new Array();
  43702. _this._floatsArrays = {};
  43703. _this._colors3 = new Array();
  43704. _this._colors4 = new Array();
  43705. _this._vectors2 = new Array();
  43706. _this._vectors3 = new Array();
  43707. _this._matrices = new Array();
  43708. _this._fallbackTextureUsed = false;
  43709. scene._proceduralTextures.push(_this);
  43710. _this.name = name;
  43711. _this.isRenderTarget = true;
  43712. _this._size = size;
  43713. _this._generateMipMaps = generateMipMaps;
  43714. _this.setFragment(fragment);
  43715. _this._fallbackTexture = fallbackTexture;
  43716. var engine = scene.getEngine();
  43717. if (isCube) {
  43718. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  43719. _this.setFloat("face", 0);
  43720. }
  43721. else {
  43722. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  43723. }
  43724. // VBO
  43725. var vertices = [];
  43726. vertices.push(1, 1);
  43727. vertices.push(-1, 1);
  43728. vertices.push(-1, -1);
  43729. vertices.push(1, -1);
  43730. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  43731. // Indices
  43732. var indices = [];
  43733. indices.push(0);
  43734. indices.push(1);
  43735. indices.push(2);
  43736. indices.push(0);
  43737. indices.push(2);
  43738. indices.push(3);
  43739. _this._indexBuffer = engine.createIndexBuffer(indices);
  43740. return _this;
  43741. }
  43742. ProceduralTexture.prototype.reset = function () {
  43743. if (this._effect === undefined) {
  43744. return;
  43745. }
  43746. var engine = this.getScene().getEngine();
  43747. engine._releaseEffect(this._effect);
  43748. };
  43749. ProceduralTexture.prototype.isReady = function () {
  43750. var _this = this;
  43751. var engine = this.getScene().getEngine();
  43752. var shaders;
  43753. if (!this._fragment) {
  43754. return false;
  43755. }
  43756. if (this._fallbackTextureUsed) {
  43757. return true;
  43758. }
  43759. if (this._fragment.fragmentElement !== undefined) {
  43760. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  43761. }
  43762. else {
  43763. shaders = { vertex: "procedural", fragment: this._fragment };
  43764. }
  43765. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  43766. _this.releaseInternalTexture();
  43767. if (_this._fallbackTexture) {
  43768. _this._texture = _this._fallbackTexture._texture;
  43769. _this._texture.references++;
  43770. }
  43771. _this._fallbackTextureUsed = true;
  43772. });
  43773. return this._effect.isReady();
  43774. };
  43775. ProceduralTexture.prototype.resetRefreshCounter = function () {
  43776. this._currentRefreshId = -1;
  43777. };
  43778. ProceduralTexture.prototype.setFragment = function (fragment) {
  43779. this._fragment = fragment;
  43780. };
  43781. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  43782. get: function () {
  43783. return this._refreshRate;
  43784. },
  43785. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  43786. set: function (value) {
  43787. this._refreshRate = value;
  43788. this.resetRefreshCounter();
  43789. },
  43790. enumerable: true,
  43791. configurable: true
  43792. });
  43793. ProceduralTexture.prototype._shouldRender = function () {
  43794. if (!this.isEnabled || !this.isReady() || !this._texture) {
  43795. return false;
  43796. }
  43797. if (this._fallbackTextureUsed) {
  43798. return false;
  43799. }
  43800. if (this._currentRefreshId === -1) {
  43801. this._currentRefreshId = 1;
  43802. return true;
  43803. }
  43804. if (this.refreshRate === this._currentRefreshId) {
  43805. this._currentRefreshId = 1;
  43806. return true;
  43807. }
  43808. this._currentRefreshId++;
  43809. return false;
  43810. };
  43811. ProceduralTexture.prototype.getRenderSize = function () {
  43812. return this._size;
  43813. };
  43814. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  43815. if (this._fallbackTextureUsed) {
  43816. return;
  43817. }
  43818. this.releaseInternalTexture();
  43819. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  43820. };
  43821. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  43822. if (this._uniforms.indexOf(uniformName) === -1) {
  43823. this._uniforms.push(uniformName);
  43824. }
  43825. };
  43826. ProceduralTexture.prototype.setTexture = function (name, texture) {
  43827. if (this._samplers.indexOf(name) === -1) {
  43828. this._samplers.push(name);
  43829. }
  43830. this._textures[name] = texture;
  43831. return this;
  43832. };
  43833. ProceduralTexture.prototype.setFloat = function (name, value) {
  43834. this._checkUniform(name);
  43835. this._floats[name] = value;
  43836. return this;
  43837. };
  43838. ProceduralTexture.prototype.setFloats = function (name, value) {
  43839. this._checkUniform(name);
  43840. this._floatsArrays[name] = value;
  43841. return this;
  43842. };
  43843. ProceduralTexture.prototype.setColor3 = function (name, value) {
  43844. this._checkUniform(name);
  43845. this._colors3[name] = value;
  43846. return this;
  43847. };
  43848. ProceduralTexture.prototype.setColor4 = function (name, value) {
  43849. this._checkUniform(name);
  43850. this._colors4[name] = value;
  43851. return this;
  43852. };
  43853. ProceduralTexture.prototype.setVector2 = function (name, value) {
  43854. this._checkUniform(name);
  43855. this._vectors2[name] = value;
  43856. return this;
  43857. };
  43858. ProceduralTexture.prototype.setVector3 = function (name, value) {
  43859. this._checkUniform(name);
  43860. this._vectors3[name] = value;
  43861. return this;
  43862. };
  43863. ProceduralTexture.prototype.setMatrix = function (name, value) {
  43864. this._checkUniform(name);
  43865. this._matrices[name] = value;
  43866. return this;
  43867. };
  43868. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  43869. var scene = this.getScene();
  43870. var engine = scene.getEngine();
  43871. // Render
  43872. engine.enableEffect(this._effect);
  43873. engine.setState(false);
  43874. // Texture
  43875. for (var name in this._textures) {
  43876. this._effect.setTexture(name, this._textures[name]);
  43877. }
  43878. // Float
  43879. for (name in this._floats) {
  43880. this._effect.setFloat(name, this._floats[name]);
  43881. }
  43882. // Floats
  43883. for (name in this._floatsArrays) {
  43884. this._effect.setArray(name, this._floatsArrays[name]);
  43885. }
  43886. // Color3
  43887. for (name in this._colors3) {
  43888. this._effect.setColor3(name, this._colors3[name]);
  43889. }
  43890. // Color4
  43891. for (name in this._colors4) {
  43892. var color = this._colors4[name];
  43893. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  43894. }
  43895. // Vector2
  43896. for (name in this._vectors2) {
  43897. this._effect.setVector2(name, this._vectors2[name]);
  43898. }
  43899. // Vector3
  43900. for (name in this._vectors3) {
  43901. this._effect.setVector3(name, this._vectors3[name]);
  43902. }
  43903. // Matrix
  43904. for (name in this._matrices) {
  43905. this._effect.setMatrix(name, this._matrices[name]);
  43906. }
  43907. if (this.isCube) {
  43908. for (var face = 0; face < 6; face++) {
  43909. engine.bindFramebuffer(this._texture, face);
  43910. // VBOs
  43911. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  43912. this._effect.setFloat("face", face);
  43913. // Clear
  43914. engine.clear(scene.clearColor, true, true, true);
  43915. // Draw order
  43916. engine.draw(true, 0, 6);
  43917. // Mipmaps
  43918. if (face === 5) {
  43919. engine.generateMipMapsForCubemap(this._texture);
  43920. }
  43921. }
  43922. }
  43923. else {
  43924. engine.bindFramebuffer(this._texture);
  43925. // VBOs
  43926. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  43927. // Clear
  43928. engine.clear(scene.clearColor, true, true, true);
  43929. // Draw order
  43930. engine.draw(true, 0, 6);
  43931. }
  43932. // Unbind
  43933. engine.unBindFramebuffer(this._texture, this.isCube);
  43934. if (this.onGenerated) {
  43935. this.onGenerated();
  43936. }
  43937. };
  43938. ProceduralTexture.prototype.clone = function () {
  43939. var textureSize = this.getSize();
  43940. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  43941. // Base texture
  43942. newTexture.hasAlpha = this.hasAlpha;
  43943. newTexture.level = this.level;
  43944. // RenderTarget Texture
  43945. newTexture.coordinatesMode = this.coordinatesMode;
  43946. return newTexture;
  43947. };
  43948. ProceduralTexture.prototype.dispose = function () {
  43949. var index = this.getScene()._proceduralTextures.indexOf(this);
  43950. if (index >= 0) {
  43951. this.getScene()._proceduralTextures.splice(index, 1);
  43952. }
  43953. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  43954. if (vertexBuffer) {
  43955. vertexBuffer.dispose();
  43956. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  43957. }
  43958. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  43959. this._indexBuffer = null;
  43960. }
  43961. _super.prototype.dispose.call(this);
  43962. };
  43963. return ProceduralTexture;
  43964. }(BABYLON.Texture));
  43965. BABYLON.ProceduralTexture = ProceduralTexture;
  43966. })(BABYLON || (BABYLON = {}));
  43967. //# sourceMappingURL=babylon.proceduralTexture.js.map
  43968. /// <reference path="babylon.proceduralTexture.ts" />
  43969. var BABYLON;
  43970. (function (BABYLON) {
  43971. var CustomProceduralTexture = (function (_super) {
  43972. __extends(CustomProceduralTexture, _super);
  43973. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  43974. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  43975. _this._animate = true;
  43976. _this._time = 0;
  43977. _this._texturePath = texturePath;
  43978. //Try to load json
  43979. _this.loadJson(texturePath);
  43980. _this.refreshRate = 1;
  43981. return _this;
  43982. }
  43983. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  43984. var _this = this;
  43985. var that = this;
  43986. function noConfigFile() {
  43987. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  43988. try {
  43989. that.setFragment(that._texturePath);
  43990. }
  43991. catch (ex) {
  43992. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  43993. }
  43994. }
  43995. var configFileUrl = jsonUrl + "/config.json";
  43996. var xhr = new XMLHttpRequest();
  43997. xhr.open("GET", configFileUrl, true);
  43998. xhr.addEventListener("load", function () {
  43999. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  44000. try {
  44001. _this._config = JSON.parse(xhr.response);
  44002. _this.updateShaderUniforms();
  44003. _this.updateTextures();
  44004. _this.setFragment(_this._texturePath + "/custom");
  44005. _this._animate = _this._config.animate;
  44006. _this.refreshRate = _this._config.refreshrate;
  44007. }
  44008. catch (ex) {
  44009. noConfigFile();
  44010. }
  44011. }
  44012. else {
  44013. noConfigFile();
  44014. }
  44015. }, false);
  44016. xhr.addEventListener("error", function () {
  44017. noConfigFile();
  44018. }, false);
  44019. try {
  44020. xhr.send();
  44021. }
  44022. catch (ex) {
  44023. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  44024. }
  44025. };
  44026. CustomProceduralTexture.prototype.isReady = function () {
  44027. if (!_super.prototype.isReady.call(this)) {
  44028. return false;
  44029. }
  44030. for (var name in this._textures) {
  44031. var texture = this._textures[name];
  44032. if (!texture.isReady()) {
  44033. return false;
  44034. }
  44035. }
  44036. return true;
  44037. };
  44038. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  44039. if (this._animate) {
  44040. this._time += this.getScene().getAnimationRatio() * 0.03;
  44041. this.updateShaderUniforms();
  44042. }
  44043. _super.prototype.render.call(this, useCameraPostProcess);
  44044. };
  44045. CustomProceduralTexture.prototype.updateTextures = function () {
  44046. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  44047. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  44048. }
  44049. };
  44050. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  44051. if (this._config) {
  44052. for (var j = 0; j < this._config.uniforms.length; j++) {
  44053. var uniform = this._config.uniforms[j];
  44054. switch (uniform.type) {
  44055. case "float":
  44056. this.setFloat(uniform.name, uniform.value);
  44057. break;
  44058. case "color3":
  44059. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  44060. break;
  44061. case "color4":
  44062. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  44063. break;
  44064. case "vector2":
  44065. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  44066. break;
  44067. case "vector3":
  44068. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  44069. break;
  44070. }
  44071. }
  44072. }
  44073. this.setFloat("time", this._time);
  44074. };
  44075. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  44076. get: function () {
  44077. return this._animate;
  44078. },
  44079. set: function (value) {
  44080. this._animate = value;
  44081. },
  44082. enumerable: true,
  44083. configurable: true
  44084. });
  44085. return CustomProceduralTexture;
  44086. }(BABYLON.ProceduralTexture));
  44087. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  44088. })(BABYLON || (BABYLON = {}));
  44089. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  44090. var BABYLON;
  44091. (function (BABYLON) {
  44092. var FreeCameraGamepadInput = (function () {
  44093. function FreeCameraGamepadInput() {
  44094. this.gamepadAngularSensibility = 200;
  44095. this.gamepadMoveSensibility = 40;
  44096. // private members
  44097. this._cameraTransform = BABYLON.Matrix.Identity();
  44098. this._deltaTransform = BABYLON.Vector3.Zero();
  44099. this._vector3 = BABYLON.Vector3.Zero();
  44100. this._vector2 = BABYLON.Vector2.Zero();
  44101. }
  44102. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  44103. var _this = this;
  44104. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  44105. };
  44106. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  44107. if (this._gamepads) {
  44108. this._gamepads.dispose();
  44109. }
  44110. this.gamepad = null;
  44111. };
  44112. FreeCameraGamepadInput.prototype.checkInputs = function () {
  44113. if (this.gamepad && this.gamepad.leftStick) {
  44114. var camera = this.camera;
  44115. var LSValues = this.gamepad.leftStick;
  44116. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  44117. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  44118. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  44119. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  44120. var RSValues = this.gamepad.rightStick;
  44121. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  44122. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  44123. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  44124. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  44125. if (!camera.rotationQuaternion) {
  44126. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  44127. }
  44128. else {
  44129. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  44130. }
  44131. var speed = camera._computeLocalCameraSpeed() * 50.0;
  44132. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  44133. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  44134. camera.cameraDirection.addInPlace(this._deltaTransform);
  44135. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  44136. camera.cameraRotation.addInPlace(this._vector2);
  44137. }
  44138. };
  44139. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  44140. // Only the first gamepad found can control the camera
  44141. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  44142. // prioritize XBOX gamepads.
  44143. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  44144. this.gamepad = gamepad;
  44145. }
  44146. }
  44147. };
  44148. FreeCameraGamepadInput.prototype.getTypeName = function () {
  44149. return "FreeCameraGamepadInput";
  44150. };
  44151. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  44152. return "gamepad";
  44153. };
  44154. return FreeCameraGamepadInput;
  44155. }());
  44156. __decorate([
  44157. BABYLON.serialize()
  44158. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  44159. __decorate([
  44160. BABYLON.serialize()
  44161. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  44162. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  44163. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  44164. })(BABYLON || (BABYLON = {}));
  44165. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  44166. var BABYLON;
  44167. (function (BABYLON) {
  44168. var ArcRotateCameraGamepadInput = (function () {
  44169. function ArcRotateCameraGamepadInput() {
  44170. this.gamepadRotationSensibility = 80;
  44171. this.gamepadMoveSensibility = 40;
  44172. }
  44173. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  44174. var _this = this;
  44175. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  44176. };
  44177. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  44178. if (this._gamepads) {
  44179. this._gamepads.dispose();
  44180. }
  44181. this.gamepad = null;
  44182. };
  44183. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  44184. if (this.gamepad) {
  44185. var camera = this.camera;
  44186. var RSValues = this.gamepad.rightStick;
  44187. if (RSValues.x != 0) {
  44188. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  44189. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  44190. camera.inertialAlphaOffset += normalizedRX;
  44191. }
  44192. }
  44193. if (RSValues.y != 0) {
  44194. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  44195. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  44196. camera.inertialBetaOffset += normalizedRY;
  44197. }
  44198. }
  44199. var LSValues = this.gamepad.leftStick;
  44200. if (LSValues.y != 0) {
  44201. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  44202. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  44203. this.camera.inertialRadiusOffset -= normalizedLY;
  44204. }
  44205. }
  44206. }
  44207. };
  44208. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  44209. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  44210. // prioritize XBOX gamepads.
  44211. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  44212. this.gamepad = gamepad;
  44213. }
  44214. }
  44215. };
  44216. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  44217. return "ArcRotateCameraGamepadInput";
  44218. };
  44219. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  44220. return "gamepad";
  44221. };
  44222. return ArcRotateCameraGamepadInput;
  44223. }());
  44224. __decorate([
  44225. BABYLON.serialize()
  44226. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  44227. __decorate([
  44228. BABYLON.serialize()
  44229. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  44230. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  44231. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  44232. })(BABYLON || (BABYLON = {}));
  44233. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  44234. var BABYLON;
  44235. (function (BABYLON) {
  44236. var Gamepads = (function () {
  44237. function Gamepads(ongamedpadconnected) {
  44238. var _this = this;
  44239. this.babylonGamepads = [];
  44240. this.oneGamepadConnected = false;
  44241. this.isMonitoring = false;
  44242. this.gamepadEventSupported = 'GamepadEvent' in window;
  44243. this.gamepadSupport = (navigator.getGamepads ||
  44244. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  44245. this._callbackGamepadConnected = ongamedpadconnected;
  44246. if (this.gamepadSupport) {
  44247. //first add already-connected gamepads
  44248. this._updateGamepadObjects();
  44249. if (this.babylonGamepads.length) {
  44250. this._startMonitoringGamepads();
  44251. }
  44252. // Checking if the gamepad connected event is supported (like in Firefox)
  44253. if (this.gamepadEventSupported) {
  44254. this._onGamepadConnectedEvent = function (evt) {
  44255. _this._onGamepadConnected(evt.gamepad);
  44256. };
  44257. this._onGamepadDisonnectedEvent = function (evt) {
  44258. _this._onGamepadDisconnected(evt);
  44259. };
  44260. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  44261. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  44262. }
  44263. else {
  44264. this._startMonitoringGamepads();
  44265. }
  44266. }
  44267. }
  44268. Gamepads.prototype.dispose = function () {
  44269. if (Gamepads.gamepadDOMInfo) {
  44270. document.body.removeChild(Gamepads.gamepadDOMInfo);
  44271. }
  44272. if (this._onGamepadConnectedEvent) {
  44273. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  44274. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  44275. this._onGamepadConnectedEvent = null;
  44276. this._onGamepadDisonnectedEvent = null;
  44277. }
  44278. };
  44279. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  44280. var newGamepad = this._addNewGamepad(gamepad);
  44281. if (this._callbackGamepadConnected)
  44282. this._callbackGamepadConnected(newGamepad);
  44283. this._startMonitoringGamepads();
  44284. };
  44285. Gamepads.prototype._addNewGamepad = function (gamepad) {
  44286. if (!this.oneGamepadConnected) {
  44287. this.oneGamepadConnected = true;
  44288. if (Gamepads.gamepadDOMInfo) {
  44289. document.body.removeChild(Gamepads.gamepadDOMInfo);
  44290. Gamepads.gamepadDOMInfo = null;
  44291. }
  44292. }
  44293. var newGamepad;
  44294. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  44295. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  44296. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  44297. }
  44298. else if (gamepad.pose) {
  44299. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  44300. }
  44301. else {
  44302. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  44303. }
  44304. this.babylonGamepads.push(newGamepad);
  44305. return newGamepad;
  44306. };
  44307. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  44308. // Remove the gamepad from the list of gamepads to monitor.
  44309. for (var i in this.babylonGamepads) {
  44310. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  44311. this.babylonGamepads.splice(+i, 1);
  44312. break;
  44313. }
  44314. }
  44315. // If no gamepads are left, stop the polling loop.
  44316. if (this.babylonGamepads.length == 0) {
  44317. this._stopMonitoringGamepads();
  44318. }
  44319. };
  44320. Gamepads.prototype._startMonitoringGamepads = function () {
  44321. if (!this.isMonitoring) {
  44322. this.isMonitoring = true;
  44323. this._checkGamepadsStatus();
  44324. }
  44325. };
  44326. Gamepads.prototype._stopMonitoringGamepads = function () {
  44327. this.isMonitoring = false;
  44328. };
  44329. Gamepads.prototype._checkGamepadsStatus = function () {
  44330. var _this = this;
  44331. // updating gamepad objects
  44332. this._updateGamepadObjects();
  44333. for (var i in this.babylonGamepads) {
  44334. this.babylonGamepads[i].update();
  44335. }
  44336. if (this.isMonitoring) {
  44337. if (window.requestAnimationFrame) {
  44338. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  44339. }
  44340. else if (window.mozRequestAnimationFrame) {
  44341. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  44342. }
  44343. else if (window.webkitRequestAnimationFrame) {
  44344. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  44345. }
  44346. }
  44347. };
  44348. // This function is called only on Chrome, which does not yet support
  44349. // connection/disconnection events, but requires you to monitor
  44350. // an array for changes.
  44351. Gamepads.prototype._updateGamepadObjects = function () {
  44352. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  44353. for (var i = 0; i < gamepads.length; i++) {
  44354. if (gamepads[i]) {
  44355. if (!(gamepads[i].index in this.babylonGamepads)) {
  44356. var newGamepad = this._addNewGamepad(gamepads[i]);
  44357. if (this._callbackGamepadConnected) {
  44358. this._callbackGamepadConnected(newGamepad);
  44359. }
  44360. }
  44361. else {
  44362. this.babylonGamepads[i].browserGamepad = gamepads[i];
  44363. }
  44364. }
  44365. }
  44366. };
  44367. return Gamepads;
  44368. }());
  44369. BABYLON.Gamepads = Gamepads;
  44370. var StickValues = (function () {
  44371. function StickValues(x, y) {
  44372. this.x = x;
  44373. this.y = y;
  44374. }
  44375. return StickValues;
  44376. }());
  44377. BABYLON.StickValues = StickValues;
  44378. var Gamepad = (function () {
  44379. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  44380. if (leftStickX === void 0) { leftStickX = 0; }
  44381. if (leftStickY === void 0) { leftStickY = 1; }
  44382. if (rightStickX === void 0) { rightStickX = 2; }
  44383. if (rightStickY === void 0) { rightStickY = 3; }
  44384. this.id = id;
  44385. this.index = index;
  44386. this.browserGamepad = browserGamepad;
  44387. this.type = Gamepad.GAMEPAD;
  44388. this._leftStickAxisX = leftStickX;
  44389. this._leftStickAxisY = leftStickY;
  44390. this._rightStickAxisX = rightStickX;
  44391. this._rightStickAxisY = rightStickY;
  44392. if (this.browserGamepad.axes.length >= 2) {
  44393. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  44394. }
  44395. if (this.browserGamepad.axes.length >= 4) {
  44396. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  44397. }
  44398. }
  44399. Gamepad.prototype.onleftstickchanged = function (callback) {
  44400. this._onleftstickchanged = callback;
  44401. };
  44402. Gamepad.prototype.onrightstickchanged = function (callback) {
  44403. this._onrightstickchanged = callback;
  44404. };
  44405. Object.defineProperty(Gamepad.prototype, "leftStick", {
  44406. get: function () {
  44407. return this._leftStick;
  44408. },
  44409. set: function (newValues) {
  44410. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  44411. this._onleftstickchanged(newValues);
  44412. }
  44413. this._leftStick = newValues;
  44414. },
  44415. enumerable: true,
  44416. configurable: true
  44417. });
  44418. Object.defineProperty(Gamepad.prototype, "rightStick", {
  44419. get: function () {
  44420. return this._rightStick;
  44421. },
  44422. set: function (newValues) {
  44423. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  44424. this._onrightstickchanged(newValues);
  44425. }
  44426. this._rightStick = newValues;
  44427. },
  44428. enumerable: true,
  44429. configurable: true
  44430. });
  44431. Gamepad.prototype.update = function () {
  44432. if (this._leftStick) {
  44433. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  44434. }
  44435. if (this._rightStick) {
  44436. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  44437. }
  44438. };
  44439. return Gamepad;
  44440. }());
  44441. Gamepad.GAMEPAD = 0;
  44442. Gamepad.GENERIC = 1;
  44443. Gamepad.XBOX = 2;
  44444. Gamepad.POSE_ENABLED = 3;
  44445. BABYLON.Gamepad = Gamepad;
  44446. var GenericPad = (function (_super) {
  44447. __extends(GenericPad, _super);
  44448. function GenericPad(id, index, gamepad) {
  44449. var _this = _super.call(this, id, index, gamepad) || this;
  44450. _this.id = id;
  44451. _this.index = index;
  44452. _this.gamepad = gamepad;
  44453. _this.type = Gamepad.GENERIC;
  44454. _this._buttons = new Array(gamepad.buttons.length);
  44455. return _this;
  44456. }
  44457. GenericPad.prototype.onbuttondown = function (callback) {
  44458. this._onbuttondown = callback;
  44459. };
  44460. GenericPad.prototype.onbuttonup = function (callback) {
  44461. this._onbuttonup = callback;
  44462. };
  44463. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  44464. if (newValue !== currentValue) {
  44465. if (this._onbuttondown && newValue === 1) {
  44466. this._onbuttondown(buttonIndex);
  44467. }
  44468. if (this._onbuttonup && newValue === 0) {
  44469. this._onbuttonup(buttonIndex);
  44470. }
  44471. }
  44472. return newValue;
  44473. };
  44474. GenericPad.prototype.update = function () {
  44475. _super.prototype.update.call(this);
  44476. for (var index = 0; index < this._buttons.length; index++) {
  44477. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  44478. }
  44479. };
  44480. return GenericPad;
  44481. }(Gamepad));
  44482. BABYLON.GenericPad = GenericPad;
  44483. var Xbox360Button;
  44484. (function (Xbox360Button) {
  44485. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  44486. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  44487. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  44488. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  44489. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  44490. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  44491. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  44492. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  44493. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  44494. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  44495. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  44496. var Xbox360Dpad;
  44497. (function (Xbox360Dpad) {
  44498. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  44499. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  44500. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  44501. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  44502. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  44503. var Xbox360Pad = (function (_super) {
  44504. __extends(Xbox360Pad, _super);
  44505. function Xbox360Pad(id, index, gamepad, xboxOne) {
  44506. if (xboxOne === void 0) { xboxOne = false; }
  44507. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  44508. _this._leftTrigger = 0;
  44509. _this._rightTrigger = 0;
  44510. _this._buttonA = 0;
  44511. _this._buttonB = 0;
  44512. _this._buttonX = 0;
  44513. _this._buttonY = 0;
  44514. _this._buttonBack = 0;
  44515. _this._buttonStart = 0;
  44516. _this._buttonLB = 0;
  44517. _this._buttonRB = 0;
  44518. _this._buttonLeftStick = 0;
  44519. _this._buttonRightStick = 0;
  44520. _this._dPadUp = 0;
  44521. _this._dPadDown = 0;
  44522. _this._dPadLeft = 0;
  44523. _this._dPadRight = 0;
  44524. _this._isXboxOnePad = false;
  44525. _this.type = Gamepad.XBOX;
  44526. _this._isXboxOnePad = xboxOne;
  44527. return _this;
  44528. }
  44529. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  44530. this._onlefttriggerchanged = callback;
  44531. };
  44532. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  44533. this._onrighttriggerchanged = callback;
  44534. };
  44535. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  44536. get: function () {
  44537. return this._leftTrigger;
  44538. },
  44539. set: function (newValue) {
  44540. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  44541. this._onlefttriggerchanged(newValue);
  44542. }
  44543. this._leftTrigger = newValue;
  44544. },
  44545. enumerable: true,
  44546. configurable: true
  44547. });
  44548. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  44549. get: function () {
  44550. return this._rightTrigger;
  44551. },
  44552. set: function (newValue) {
  44553. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  44554. this._onrighttriggerchanged(newValue);
  44555. }
  44556. this._rightTrigger = newValue;
  44557. },
  44558. enumerable: true,
  44559. configurable: true
  44560. });
  44561. Xbox360Pad.prototype.onbuttondown = function (callback) {
  44562. this._onbuttondown = callback;
  44563. };
  44564. Xbox360Pad.prototype.onbuttonup = function (callback) {
  44565. this._onbuttonup = callback;
  44566. };
  44567. Xbox360Pad.prototype.ondpaddown = function (callback) {
  44568. this._ondpaddown = callback;
  44569. };
  44570. Xbox360Pad.prototype.ondpadup = function (callback) {
  44571. this._ondpadup = callback;
  44572. };
  44573. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  44574. if (newValue !== currentValue) {
  44575. if (this._onbuttondown && newValue === 1) {
  44576. this._onbuttondown(buttonType);
  44577. }
  44578. if (this._onbuttonup && newValue === 0) {
  44579. this._onbuttonup(buttonType);
  44580. }
  44581. }
  44582. return newValue;
  44583. };
  44584. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  44585. if (newValue !== currentValue) {
  44586. if (this._ondpaddown && newValue === 1) {
  44587. this._ondpaddown(buttonType);
  44588. }
  44589. if (this._ondpadup && newValue === 0) {
  44590. this._ondpadup(buttonType);
  44591. }
  44592. }
  44593. return newValue;
  44594. };
  44595. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  44596. get: function () {
  44597. return this._buttonA;
  44598. },
  44599. set: function (value) {
  44600. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  44601. },
  44602. enumerable: true,
  44603. configurable: true
  44604. });
  44605. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  44606. get: function () {
  44607. return this._buttonB;
  44608. },
  44609. set: function (value) {
  44610. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  44611. },
  44612. enumerable: true,
  44613. configurable: true
  44614. });
  44615. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  44616. get: function () {
  44617. return this._buttonX;
  44618. },
  44619. set: function (value) {
  44620. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  44621. },
  44622. enumerable: true,
  44623. configurable: true
  44624. });
  44625. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  44626. get: function () {
  44627. return this._buttonY;
  44628. },
  44629. set: function (value) {
  44630. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  44631. },
  44632. enumerable: true,
  44633. configurable: true
  44634. });
  44635. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  44636. get: function () {
  44637. return this._buttonStart;
  44638. },
  44639. set: function (value) {
  44640. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  44641. },
  44642. enumerable: true,
  44643. configurable: true
  44644. });
  44645. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  44646. get: function () {
  44647. return this._buttonBack;
  44648. },
  44649. set: function (value) {
  44650. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  44651. },
  44652. enumerable: true,
  44653. configurable: true
  44654. });
  44655. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  44656. get: function () {
  44657. return this._buttonLB;
  44658. },
  44659. set: function (value) {
  44660. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  44661. },
  44662. enumerable: true,
  44663. configurable: true
  44664. });
  44665. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  44666. get: function () {
  44667. return this._buttonRB;
  44668. },
  44669. set: function (value) {
  44670. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  44671. },
  44672. enumerable: true,
  44673. configurable: true
  44674. });
  44675. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  44676. get: function () {
  44677. return this._buttonLeftStick;
  44678. },
  44679. set: function (value) {
  44680. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  44681. },
  44682. enumerable: true,
  44683. configurable: true
  44684. });
  44685. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  44686. get: function () {
  44687. return this._buttonRightStick;
  44688. },
  44689. set: function (value) {
  44690. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  44691. },
  44692. enumerable: true,
  44693. configurable: true
  44694. });
  44695. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  44696. get: function () {
  44697. return this._dPadUp;
  44698. },
  44699. set: function (value) {
  44700. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  44701. },
  44702. enumerable: true,
  44703. configurable: true
  44704. });
  44705. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  44706. get: function () {
  44707. return this._dPadDown;
  44708. },
  44709. set: function (value) {
  44710. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  44711. },
  44712. enumerable: true,
  44713. configurable: true
  44714. });
  44715. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  44716. get: function () {
  44717. return this._dPadLeft;
  44718. },
  44719. set: function (value) {
  44720. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  44721. },
  44722. enumerable: true,
  44723. configurable: true
  44724. });
  44725. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  44726. get: function () {
  44727. return this._dPadRight;
  44728. },
  44729. set: function (value) {
  44730. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  44731. },
  44732. enumerable: true,
  44733. configurable: true
  44734. });
  44735. Xbox360Pad.prototype.update = function () {
  44736. _super.prototype.update.call(this);
  44737. if (this._isXboxOnePad) {
  44738. this.buttonA = this.browserGamepad.buttons[0].value;
  44739. this.buttonB = this.browserGamepad.buttons[1].value;
  44740. this.buttonX = this.browserGamepad.buttons[2].value;
  44741. this.buttonY = this.browserGamepad.buttons[3].value;
  44742. this.buttonLB = this.browserGamepad.buttons[4].value;
  44743. this.buttonRB = this.browserGamepad.buttons[5].value;
  44744. this.leftTrigger = this.browserGamepad.axes[2];
  44745. this.rightTrigger = this.browserGamepad.axes[5];
  44746. this.buttonBack = this.browserGamepad.buttons[9].value;
  44747. this.buttonStart = this.browserGamepad.buttons[8].value;
  44748. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  44749. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  44750. this.dPadUp = this.browserGamepad.buttons[11].value;
  44751. this.dPadDown = this.browserGamepad.buttons[12].value;
  44752. this.dPadLeft = this.browserGamepad.buttons[13].value;
  44753. this.dPadRight = this.browserGamepad.buttons[14].value;
  44754. }
  44755. else {
  44756. this.buttonA = this.browserGamepad.buttons[0].value;
  44757. this.buttonB = this.browserGamepad.buttons[1].value;
  44758. this.buttonX = this.browserGamepad.buttons[2].value;
  44759. this.buttonY = this.browserGamepad.buttons[3].value;
  44760. this.buttonLB = this.browserGamepad.buttons[4].value;
  44761. this.buttonRB = this.browserGamepad.buttons[5].value;
  44762. this.leftTrigger = this.browserGamepad.buttons[6].value;
  44763. this.rightTrigger = this.browserGamepad.buttons[7].value;
  44764. this.buttonBack = this.browserGamepad.buttons[8].value;
  44765. this.buttonStart = this.browserGamepad.buttons[9].value;
  44766. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  44767. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  44768. this.dPadUp = this.browserGamepad.buttons[12].value;
  44769. this.dPadDown = this.browserGamepad.buttons[13].value;
  44770. this.dPadLeft = this.browserGamepad.buttons[14].value;
  44771. this.dPadRight = this.browserGamepad.buttons[15].value;
  44772. }
  44773. };
  44774. return Xbox360Pad;
  44775. }(Gamepad));
  44776. BABYLON.Xbox360Pad = Xbox360Pad;
  44777. })(BABYLON || (BABYLON = {}));
  44778. //# sourceMappingURL=babylon.gamepads.js.map
  44779. var BABYLON;
  44780. (function (BABYLON) {
  44781. var PoseEnabledControllerType;
  44782. (function (PoseEnabledControllerType) {
  44783. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  44784. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  44785. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  44786. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  44787. var PoseEnabledControllerHelper = (function () {
  44788. function PoseEnabledControllerHelper() {
  44789. }
  44790. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  44791. // for now, only Oculus and Vive are supported
  44792. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  44793. return new OculusTouchController(vrGamepad);
  44794. }
  44795. else {
  44796. return new ViveController(vrGamepad);
  44797. }
  44798. };
  44799. return PoseEnabledControllerHelper;
  44800. }());
  44801. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  44802. var PoseEnabledController = (function (_super) {
  44803. __extends(PoseEnabledController, _super);
  44804. function PoseEnabledController(vrGamepad) {
  44805. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  44806. _this.vrGamepad = vrGamepad;
  44807. _this.deviceScaleFactor = 1;
  44808. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  44809. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  44810. _this.controllerType = PoseEnabledControllerType.GENERIC;
  44811. _this.position = BABYLON.Vector3.Zero();
  44812. _this.rotationQuaternion = new BABYLON.Quaternion();
  44813. _this.devicePosition = BABYLON.Vector3.Zero();
  44814. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  44815. _this._calculatedPosition = BABYLON.Vector3.Zero();
  44816. _this._calculatedRotation = new BABYLON.Quaternion();
  44817. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  44818. return _this;
  44819. }
  44820. PoseEnabledController.prototype.update = function () {
  44821. _super.prototype.update.call(this);
  44822. var pose = this.vrGamepad.pose;
  44823. this.updateFromDevice(pose);
  44824. if (this._mesh) {
  44825. this._mesh.position.copyFrom(this._calculatedPosition);
  44826. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  44827. }
  44828. };
  44829. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  44830. if (poseData) {
  44831. this.rawPose = poseData;
  44832. if (poseData.position) {
  44833. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  44834. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  44835. this.devicePosition.z *= -1;
  44836. }
  44837. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  44838. this._calculatedPosition.addInPlace(this.position);
  44839. }
  44840. if (poseData.orientation) {
  44841. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  44842. if (this._mesh) {
  44843. if (this._mesh.getScene().useRightHandedSystem) {
  44844. this.deviceRotationQuaternion.z *= -1;
  44845. this.deviceRotationQuaternion.w *= -1;
  44846. }
  44847. else {
  44848. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  44849. }
  44850. }
  44851. // if the camera is set, rotate to the camera's rotation
  44852. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  44853. }
  44854. }
  44855. };
  44856. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  44857. if (this._mesh) {
  44858. this._mesh.parent = undefined;
  44859. }
  44860. this._mesh = mesh;
  44861. if (this._poseControlledCamera) {
  44862. this._mesh.parent = this._poseControlledCamera;
  44863. }
  44864. if (!this._mesh.rotationQuaternion) {
  44865. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  44866. }
  44867. };
  44868. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  44869. this._poseControlledCamera = camera;
  44870. if (this._mesh) {
  44871. this._mesh.parent = this._poseControlledCamera;
  44872. }
  44873. };
  44874. PoseEnabledController.prototype.detachMesh = function () {
  44875. this._mesh = undefined;
  44876. };
  44877. return PoseEnabledController;
  44878. }(BABYLON.Gamepad));
  44879. BABYLON.PoseEnabledController = PoseEnabledController;
  44880. var WebVRController = (function (_super) {
  44881. __extends(WebVRController, _super);
  44882. function WebVRController(vrGamepad) {
  44883. var _this = _super.call(this, vrGamepad) || this;
  44884. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  44885. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  44886. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  44887. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  44888. _this.onPadStateChangedObservable = new BABYLON.Observable();
  44889. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  44890. _this.pad = { x: 0, y: 0 };
  44891. // avoid GC, store state in a tmp object
  44892. _this._changes = {
  44893. pressChanged: false,
  44894. touchChanged: false,
  44895. valueChanged: false,
  44896. changed: false
  44897. };
  44898. _this._buttons = new Array(vrGamepad.buttons.length);
  44899. _this.hand = vrGamepad.hand;
  44900. return _this;
  44901. }
  44902. WebVRController.prototype.onButtonStateChange = function (callback) {
  44903. this._onButtonStateChange = callback;
  44904. };
  44905. WebVRController.prototype.update = function () {
  44906. _super.prototype.update.call(this);
  44907. for (var index = 0; index < this._buttons.length; index++) {
  44908. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  44909. }
  44910. ;
  44911. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  44912. this.pad.x = this.leftStick.x;
  44913. this.pad.y = this.leftStick.y;
  44914. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  44915. }
  44916. };
  44917. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  44918. if (!currentState) {
  44919. this._buttons[buttonIndex] = {
  44920. pressed: newState.pressed,
  44921. touched: newState.touched,
  44922. value: newState.value
  44923. };
  44924. return;
  44925. }
  44926. this._checkChanges(newState, currentState);
  44927. if (this._changes.changed) {
  44928. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  44929. this.handleButtonChange(buttonIndex, newState, this._changes);
  44930. }
  44931. this._buttons[buttonIndex].pressed = newState.pressed;
  44932. this._buttons[buttonIndex].touched = newState.touched;
  44933. // oculus triggers are never 0, thou not touched.
  44934. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  44935. };
  44936. WebVRController.prototype._checkChanges = function (newState, currentState) {
  44937. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  44938. this._changes.touchChanged = newState.touched !== currentState.touched;
  44939. this._changes.valueChanged = newState.value !== currentState.value;
  44940. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  44941. return this._changes;
  44942. };
  44943. return WebVRController;
  44944. }(PoseEnabledController));
  44945. BABYLON.WebVRController = WebVRController;
  44946. var OculusTouchController = (function (_super) {
  44947. __extends(OculusTouchController, _super);
  44948. function OculusTouchController(vrGamepad) {
  44949. var _this = _super.call(this, vrGamepad) || this;
  44950. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  44951. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  44952. _this.controllerType = PoseEnabledControllerType.OCULUS;
  44953. return _this;
  44954. }
  44955. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  44956. var _this = this;
  44957. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  44958. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  44959. /*
  44960. Parent Mesh name: oculus_touch_left
  44961. - body
  44962. - trigger
  44963. - thumbstick
  44964. - grip
  44965. - button_y
  44966. - button_x
  44967. - button_enter
  44968. */
  44969. _this._defaultModel = newMeshes[1];
  44970. if (meshLoaded) {
  44971. meshLoaded(_this._defaultModel);
  44972. }
  44973. _this.attachToMesh(_this._defaultModel);
  44974. });
  44975. };
  44976. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  44977. // helper getters for left and right hand.
  44978. get: function () {
  44979. if (this.hand === 'right') {
  44980. return this.onMainButtonStateChangedObservable;
  44981. }
  44982. else {
  44983. throw new Error('No A button on left hand');
  44984. }
  44985. },
  44986. enumerable: true,
  44987. configurable: true
  44988. });
  44989. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  44990. get: function () {
  44991. if (this.hand === 'right') {
  44992. return this.onSecondaryButtonStateChangedObservable;
  44993. }
  44994. else {
  44995. throw new Error('No B button on left hand');
  44996. }
  44997. },
  44998. enumerable: true,
  44999. configurable: true
  45000. });
  45001. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  45002. get: function () {
  45003. if (this.hand === 'left') {
  45004. return this.onMainButtonStateChangedObservable;
  45005. }
  45006. else {
  45007. throw new Error('No X button on right hand');
  45008. }
  45009. },
  45010. enumerable: true,
  45011. configurable: true
  45012. });
  45013. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  45014. get: function () {
  45015. if (this.hand === 'left') {
  45016. return this.onSecondaryButtonStateChangedObservable;
  45017. }
  45018. else {
  45019. throw new Error('No Y button on right hand');
  45020. }
  45021. },
  45022. enumerable: true,
  45023. configurable: true
  45024. });
  45025. /*
  45026. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  45027. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  45028. 2) secondary trigger (same)
  45029. 3) A (right) X (left), touch, pressed = value
  45030. 4) B / Y
  45031. 5) thumb rest
  45032. */
  45033. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  45034. var notifyObject = state; //{ state: state, changes: changes };
  45035. switch (buttonIdx) {
  45036. case 0:
  45037. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  45038. return;
  45039. case 1:
  45040. if (this._defaultModel) {
  45041. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  45042. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  45043. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  45044. }
  45045. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  45046. return;
  45047. case 2:
  45048. if (this._defaultModel) {
  45049. (this._defaultModel.getChildren()[4]).position.x = notifyObject.value * 0.0035;
  45050. }
  45051. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  45052. return;
  45053. case 3:
  45054. if (this._defaultModel) {
  45055. if (notifyObject.pressed) {
  45056. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  45057. }
  45058. else {
  45059. (this._defaultModel.getChildren()[1]).position.y = 0;
  45060. }
  45061. }
  45062. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  45063. return;
  45064. case 4:
  45065. if (this._defaultModel) {
  45066. if (notifyObject.pressed) {
  45067. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  45068. }
  45069. else {
  45070. (this._defaultModel.getChildren()[2]).position.y = 0;
  45071. }
  45072. }
  45073. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  45074. return;
  45075. case 5:
  45076. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  45077. return;
  45078. }
  45079. };
  45080. return OculusTouchController;
  45081. }(WebVRController));
  45082. BABYLON.OculusTouchController = OculusTouchController;
  45083. var ViveController = (function (_super) {
  45084. __extends(ViveController, _super);
  45085. function ViveController(vrGamepad) {
  45086. var _this = _super.call(this, vrGamepad) || this;
  45087. _this.controllerType = PoseEnabledControllerType.VIVE;
  45088. return _this;
  45089. }
  45090. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  45091. var _this = this;
  45092. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  45093. /*
  45094. Parent Mesh name: ViveWand
  45095. - body
  45096. - r_gripper
  45097. - l_gripper
  45098. - menu_button
  45099. - system_button
  45100. - trackpad
  45101. - trigger
  45102. - LED
  45103. */
  45104. _this._defaultModel = newMeshes[1];
  45105. if (meshLoaded) {
  45106. meshLoaded(_this._defaultModel);
  45107. }
  45108. _this.attachToMesh(_this._defaultModel);
  45109. });
  45110. };
  45111. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  45112. get: function () {
  45113. return this.onMainButtonStateChangedObservable;
  45114. },
  45115. enumerable: true,
  45116. configurable: true
  45117. });
  45118. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  45119. get: function () {
  45120. return this.onMainButtonStateChangedObservable;
  45121. },
  45122. enumerable: true,
  45123. configurable: true
  45124. });
  45125. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  45126. get: function () {
  45127. return this.onSecondaryButtonStateChangedObservable;
  45128. },
  45129. enumerable: true,
  45130. configurable: true
  45131. });
  45132. /**
  45133. * Vive mapping:
  45134. * 0: touchpad
  45135. * 1: trigger
  45136. * 2: left AND right buttons
  45137. * 3: menu button
  45138. */
  45139. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  45140. var notifyObject = state; //{ state: state, changes: changes };
  45141. switch (buttonIdx) {
  45142. case 0:
  45143. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  45144. return;
  45145. case 1:
  45146. if (this._defaultModel) {
  45147. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  45148. }
  45149. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  45150. return;
  45151. case 2:
  45152. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  45153. return;
  45154. case 3:
  45155. if (this._defaultModel) {
  45156. if (notifyObject.pressed) {
  45157. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  45158. }
  45159. else {
  45160. (this._defaultModel.getChildren()[2]).position.y = 0;
  45161. }
  45162. }
  45163. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  45164. return;
  45165. }
  45166. };
  45167. return ViveController;
  45168. }(WebVRController));
  45169. BABYLON.ViveController = ViveController;
  45170. })(BABYLON || (BABYLON = {}));
  45171. //# sourceMappingURL=babylon.extendedGamepad.js.map
  45172. /// <reference path="babylon.targetCamera.ts" />
  45173. var BABYLON;
  45174. (function (BABYLON) {
  45175. var FollowCamera = (function (_super) {
  45176. __extends(FollowCamera, _super);
  45177. function FollowCamera(name, position, scene, lockedTarget) {
  45178. var _this = _super.call(this, name, position, scene) || this;
  45179. _this.radius = 12;
  45180. _this.rotationOffset = 0;
  45181. _this.heightOffset = 4;
  45182. _this.cameraAcceleration = 0.05;
  45183. _this.maxCameraSpeed = 20;
  45184. _this.lockedTarget = lockedTarget;
  45185. return _this;
  45186. }
  45187. FollowCamera.prototype.getRadians = function (degrees) {
  45188. return degrees * Math.PI / 180;
  45189. };
  45190. FollowCamera.prototype.follow = function (cameraTarget) {
  45191. if (!cameraTarget)
  45192. return;
  45193. var yRotation;
  45194. if (cameraTarget.rotationQuaternion) {
  45195. var rotMatrix = new BABYLON.Matrix();
  45196. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  45197. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  45198. }
  45199. else {
  45200. yRotation = cameraTarget.rotation.y;
  45201. }
  45202. var radians = this.getRadians(this.rotationOffset) + yRotation;
  45203. var targetPosition = cameraTarget.getAbsolutePosition();
  45204. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  45205. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  45206. var dx = targetX - this.position.x;
  45207. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  45208. var dz = (targetZ) - this.position.z;
  45209. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  45210. var vy = dy * this.cameraAcceleration;
  45211. var vz = dz * this.cameraAcceleration * 2;
  45212. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  45213. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  45214. }
  45215. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  45216. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  45217. }
  45218. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  45219. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  45220. }
  45221. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  45222. this.setTarget(targetPosition);
  45223. };
  45224. FollowCamera.prototype._checkInputs = function () {
  45225. _super.prototype._checkInputs.call(this);
  45226. this.follow(this.lockedTarget);
  45227. };
  45228. FollowCamera.prototype.getClassName = function () {
  45229. return "FollowCamera";
  45230. };
  45231. return FollowCamera;
  45232. }(BABYLON.TargetCamera));
  45233. __decorate([
  45234. BABYLON.serialize()
  45235. ], FollowCamera.prototype, "radius", void 0);
  45236. __decorate([
  45237. BABYLON.serialize()
  45238. ], FollowCamera.prototype, "rotationOffset", void 0);
  45239. __decorate([
  45240. BABYLON.serialize()
  45241. ], FollowCamera.prototype, "heightOffset", void 0);
  45242. __decorate([
  45243. BABYLON.serialize()
  45244. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  45245. __decorate([
  45246. BABYLON.serialize()
  45247. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  45248. __decorate([
  45249. BABYLON.serializeAsMeshReference("lockedTargetId")
  45250. ], FollowCamera.prototype, "lockedTarget", void 0);
  45251. BABYLON.FollowCamera = FollowCamera;
  45252. var ArcFollowCamera = (function (_super) {
  45253. __extends(ArcFollowCamera, _super);
  45254. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  45255. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  45256. _this.alpha = alpha;
  45257. _this.beta = beta;
  45258. _this.radius = radius;
  45259. _this.target = target;
  45260. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  45261. _this.follow();
  45262. return _this;
  45263. }
  45264. ArcFollowCamera.prototype.follow = function () {
  45265. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  45266. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  45267. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  45268. var targetPosition = this.target.getAbsolutePosition();
  45269. this.position = targetPosition.add(this._cartesianCoordinates);
  45270. this.setTarget(targetPosition);
  45271. };
  45272. ArcFollowCamera.prototype._checkInputs = function () {
  45273. _super.prototype._checkInputs.call(this);
  45274. this.follow();
  45275. };
  45276. ArcFollowCamera.prototype.getClassName = function () {
  45277. return "ArcFollowCamera";
  45278. };
  45279. return ArcFollowCamera;
  45280. }(BABYLON.TargetCamera));
  45281. BABYLON.ArcFollowCamera = ArcFollowCamera;
  45282. })(BABYLON || (BABYLON = {}));
  45283. //# sourceMappingURL=babylon.followCamera.js.map
  45284. /// <reference path="babylon.touchCamera.ts" />
  45285. var BABYLON;
  45286. (function (BABYLON) {
  45287. // We're mainly based on the logic defined into the FreeCamera code
  45288. var UniversalCamera = (function (_super) {
  45289. __extends(UniversalCamera, _super);
  45290. //-- end properties for backward compatibility for inputs
  45291. function UniversalCamera(name, position, scene) {
  45292. var _this = _super.call(this, name, position, scene) || this;
  45293. _this.inputs.addGamepad();
  45294. return _this;
  45295. }
  45296. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  45297. //-- Begin properties for backward compatibility for inputs
  45298. get: function () {
  45299. var gamepad = this.inputs.attached["gamepad"];
  45300. if (gamepad)
  45301. return gamepad.gamepadAngularSensibility;
  45302. },
  45303. set: function (value) {
  45304. var gamepad = this.inputs.attached["gamepad"];
  45305. if (gamepad)
  45306. gamepad.gamepadAngularSensibility = value;
  45307. },
  45308. enumerable: true,
  45309. configurable: true
  45310. });
  45311. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  45312. get: function () {
  45313. var gamepad = this.inputs.attached["gamepad"];
  45314. if (gamepad)
  45315. return gamepad.gamepadMoveSensibility;
  45316. },
  45317. set: function (value) {
  45318. var gamepad = this.inputs.attached["gamepad"];
  45319. if (gamepad)
  45320. gamepad.gamepadMoveSensibility = value;
  45321. },
  45322. enumerable: true,
  45323. configurable: true
  45324. });
  45325. UniversalCamera.prototype.getClassName = function () {
  45326. return "UniversalCamera";
  45327. };
  45328. return UniversalCamera;
  45329. }(BABYLON.TouchCamera));
  45330. BABYLON.UniversalCamera = UniversalCamera;
  45331. })(BABYLON || (BABYLON = {}));
  45332. //# sourceMappingURL=babylon.universalCamera.js.map
  45333. /// <reference path="babylon.universalCamera.ts" />
  45334. var BABYLON;
  45335. (function (BABYLON) {
  45336. // We're mainly based on the logic defined into the FreeCamera code
  45337. var GamepadCamera = (function (_super) {
  45338. __extends(GamepadCamera, _super);
  45339. //-- end properties for backward compatibility for inputs
  45340. function GamepadCamera(name, position, scene) {
  45341. return _super.call(this, name, position, scene) || this;
  45342. }
  45343. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  45344. //-- Begin properties for backward compatibility for inputs
  45345. get: function () {
  45346. var gamepad = this.inputs.attached["gamepad"];
  45347. if (gamepad)
  45348. return gamepad.gamepadAngularSensibility;
  45349. },
  45350. set: function (value) {
  45351. var gamepad = this.inputs.attached["gamepad"];
  45352. if (gamepad)
  45353. gamepad.gamepadAngularSensibility = value;
  45354. },
  45355. enumerable: true,
  45356. configurable: true
  45357. });
  45358. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  45359. get: function () {
  45360. var gamepad = this.inputs.attached["gamepad"];
  45361. if (gamepad)
  45362. return gamepad.gamepadMoveSensibility;
  45363. },
  45364. set: function (value) {
  45365. var gamepad = this.inputs.attached["gamepad"];
  45366. if (gamepad)
  45367. gamepad.gamepadMoveSensibility = value;
  45368. },
  45369. enumerable: true,
  45370. configurable: true
  45371. });
  45372. GamepadCamera.prototype.getClassName = function () {
  45373. return "GamepadCamera";
  45374. };
  45375. return GamepadCamera;
  45376. }(BABYLON.UniversalCamera));
  45377. BABYLON.GamepadCamera = GamepadCamera;
  45378. })(BABYLON || (BABYLON = {}));
  45379. //# sourceMappingURL=babylon.gamepadCamera.js.map
  45380. var BABYLON;
  45381. (function (BABYLON) {
  45382. var PostProcessRenderPipelineManager = (function () {
  45383. function PostProcessRenderPipelineManager() {
  45384. this._renderPipelines = {};
  45385. }
  45386. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  45387. this._renderPipelines[renderPipeline._name] = renderPipeline;
  45388. };
  45389. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  45390. var renderPipeline = this._renderPipelines[renderPipelineName];
  45391. if (!renderPipeline) {
  45392. return;
  45393. }
  45394. renderPipeline._attachCameras(cameras, unique);
  45395. };
  45396. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  45397. var renderPipeline = this._renderPipelines[renderPipelineName];
  45398. if (!renderPipeline) {
  45399. return;
  45400. }
  45401. renderPipeline._detachCameras(cameras);
  45402. };
  45403. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  45404. var renderPipeline = this._renderPipelines[renderPipelineName];
  45405. if (!renderPipeline) {
  45406. return;
  45407. }
  45408. renderPipeline._enableEffect(renderEffectName, cameras);
  45409. };
  45410. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  45411. var renderPipeline = this._renderPipelines[renderPipelineName];
  45412. if (!renderPipeline) {
  45413. return;
  45414. }
  45415. renderPipeline._disableEffect(renderEffectName, cameras);
  45416. };
  45417. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  45418. var renderPipeline = this._renderPipelines[renderPipelineName];
  45419. if (!renderPipeline) {
  45420. return;
  45421. }
  45422. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  45423. };
  45424. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  45425. var renderPipeline = this._renderPipelines[renderPipelineName];
  45426. if (!renderPipeline) {
  45427. return;
  45428. }
  45429. renderPipeline._disableDisplayOnlyPass(cameras);
  45430. };
  45431. PostProcessRenderPipelineManager.prototype.update = function () {
  45432. for (var renderPipelineName in this._renderPipelines) {
  45433. var pipeline = this._renderPipelines[renderPipelineName];
  45434. if (!pipeline.isSupported) {
  45435. pipeline.dispose();
  45436. delete this._renderPipelines[renderPipelineName];
  45437. }
  45438. else {
  45439. pipeline._update();
  45440. }
  45441. }
  45442. };
  45443. return PostProcessRenderPipelineManager;
  45444. }());
  45445. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  45446. })(BABYLON || (BABYLON = {}));
  45447. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  45448. var BABYLON;
  45449. (function (BABYLON) {
  45450. var PostProcessRenderPass = (function () {
  45451. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  45452. this._enabled = true;
  45453. this._refCount = 0;
  45454. this._name = name;
  45455. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  45456. this.setRenderList(renderList);
  45457. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  45458. this._renderTexture.onAfterRenderObservable.add(afterRender);
  45459. this._scene = scene;
  45460. this._renderList = renderList;
  45461. }
  45462. // private
  45463. PostProcessRenderPass.prototype._incRefCount = function () {
  45464. if (this._refCount === 0) {
  45465. this._scene.customRenderTargets.push(this._renderTexture);
  45466. }
  45467. return ++this._refCount;
  45468. };
  45469. PostProcessRenderPass.prototype._decRefCount = function () {
  45470. this._refCount--;
  45471. if (this._refCount <= 0) {
  45472. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  45473. }
  45474. return this._refCount;
  45475. };
  45476. PostProcessRenderPass.prototype._update = function () {
  45477. this.setRenderList(this._renderList);
  45478. };
  45479. // public
  45480. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  45481. this._renderTexture.renderList = renderList;
  45482. };
  45483. PostProcessRenderPass.prototype.getRenderTexture = function () {
  45484. return this._renderTexture;
  45485. };
  45486. return PostProcessRenderPass;
  45487. }());
  45488. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  45489. })(BABYLON || (BABYLON = {}));
  45490. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  45491. var BABYLON;
  45492. (function (BABYLON) {
  45493. var PostProcessRenderEffect = (function () {
  45494. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  45495. this._engine = engine;
  45496. this._name = name;
  45497. this._singleInstance = singleInstance || true;
  45498. this._getPostProcess = getPostProcess;
  45499. this._cameras = [];
  45500. this._indicesForCamera = [];
  45501. this._postProcesses = {};
  45502. this._renderPasses = {};
  45503. this._renderEffectAsPasses = {};
  45504. }
  45505. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  45506. get: function () {
  45507. for (var index in this._postProcesses) {
  45508. if (!this._postProcesses[index].isSupported) {
  45509. return false;
  45510. }
  45511. }
  45512. return true;
  45513. },
  45514. enumerable: true,
  45515. configurable: true
  45516. });
  45517. PostProcessRenderEffect.prototype._update = function () {
  45518. for (var renderPassName in this._renderPasses) {
  45519. this._renderPasses[renderPassName]._update();
  45520. }
  45521. };
  45522. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  45523. this._renderPasses[renderPass._name] = renderPass;
  45524. this._linkParameters();
  45525. };
  45526. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  45527. delete this._renderPasses[renderPass._name];
  45528. this._linkParameters();
  45529. };
  45530. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  45531. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  45532. this._linkParameters();
  45533. };
  45534. PostProcessRenderEffect.prototype.getPass = function (passName) {
  45535. for (var renderPassName in this._renderPasses) {
  45536. if (renderPassName === passName) {
  45537. return this._renderPasses[passName];
  45538. }
  45539. }
  45540. };
  45541. PostProcessRenderEffect.prototype.emptyPasses = function () {
  45542. this._renderPasses = {};
  45543. this._linkParameters();
  45544. };
  45545. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  45546. var cameraKey;
  45547. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  45548. for (var i = 0; i < _cam.length; i++) {
  45549. var camera = _cam[i];
  45550. var cameraName = camera.name;
  45551. if (this._singleInstance) {
  45552. cameraKey = 0;
  45553. }
  45554. else {
  45555. cameraKey = cameraName;
  45556. }
  45557. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  45558. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  45559. if (!this._indicesForCamera[cameraName]) {
  45560. this._indicesForCamera[cameraName] = [];
  45561. }
  45562. this._indicesForCamera[cameraName].push(index);
  45563. if (this._cameras.indexOf(camera) === -1) {
  45564. this._cameras[cameraName] = camera;
  45565. }
  45566. for (var passName in this._renderPasses) {
  45567. this._renderPasses[passName]._incRefCount();
  45568. }
  45569. }
  45570. this._linkParameters();
  45571. };
  45572. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  45573. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  45574. for (var i = 0; i < _cam.length; i++) {
  45575. var camera = _cam[i];
  45576. var cameraName = camera.name;
  45577. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  45578. var index = this._cameras.indexOf(cameraName);
  45579. this._indicesForCamera.splice(index, 1);
  45580. this._cameras.splice(index, 1);
  45581. for (var passName in this._renderPasses) {
  45582. this._renderPasses[passName]._decRefCount();
  45583. }
  45584. }
  45585. };
  45586. PostProcessRenderEffect.prototype._enable = function (cameras) {
  45587. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  45588. for (var i = 0; i < _cam.length; i++) {
  45589. var camera = _cam[i];
  45590. var cameraName = camera.name;
  45591. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  45592. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  45593. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  45594. }
  45595. }
  45596. for (var passName in this._renderPasses) {
  45597. this._renderPasses[passName]._incRefCount();
  45598. }
  45599. }
  45600. };
  45601. PostProcessRenderEffect.prototype._disable = function (cameras) {
  45602. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  45603. for (var i = 0; i < _cam.length; i++) {
  45604. var camera = _cam[i];
  45605. var cameraName = camera.Name;
  45606. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  45607. for (var passName in this._renderPasses) {
  45608. this._renderPasses[passName]._decRefCount();
  45609. }
  45610. }
  45611. };
  45612. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  45613. if (this._singleInstance) {
  45614. return this._postProcesses[0];
  45615. }
  45616. else {
  45617. return this._postProcesses[camera.name];
  45618. }
  45619. };
  45620. PostProcessRenderEffect.prototype._linkParameters = function () {
  45621. var _this = this;
  45622. for (var index in this._postProcesses) {
  45623. if (this.applyParameters) {
  45624. this.applyParameters(this._postProcesses[index]);
  45625. }
  45626. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  45627. _this._linkTextures(effect);
  45628. });
  45629. }
  45630. };
  45631. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  45632. for (var renderPassName in this._renderPasses) {
  45633. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  45634. }
  45635. for (var renderEffectName in this._renderEffectAsPasses) {
  45636. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  45637. }
  45638. };
  45639. return PostProcessRenderEffect;
  45640. }());
  45641. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  45642. })(BABYLON || (BABYLON = {}));
  45643. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  45644. var BABYLON;
  45645. (function (BABYLON) {
  45646. var PostProcessRenderPipeline = (function () {
  45647. function PostProcessRenderPipeline(engine, name) {
  45648. this._engine = engine;
  45649. this._name = name;
  45650. this._renderEffects = {};
  45651. this._renderEffectsForIsolatedPass = {};
  45652. this._cameras = [];
  45653. }
  45654. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  45655. get: function () {
  45656. for (var renderEffectName in this._renderEffects) {
  45657. if (!this._renderEffects[renderEffectName].isSupported) {
  45658. return false;
  45659. }
  45660. }
  45661. return true;
  45662. },
  45663. enumerable: true,
  45664. configurable: true
  45665. });
  45666. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  45667. this._renderEffects[renderEffect._name] = renderEffect;
  45668. };
  45669. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  45670. var renderEffects = this._renderEffects[renderEffectName];
  45671. if (!renderEffects) {
  45672. return;
  45673. }
  45674. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  45675. };
  45676. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  45677. var renderEffects = this._renderEffects[renderEffectName];
  45678. if (!renderEffects) {
  45679. return;
  45680. }
  45681. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  45682. };
  45683. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  45684. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  45685. var indicesToDelete = [];
  45686. var i;
  45687. for (i = 0; i < _cam.length; i++) {
  45688. var camera = _cam[i];
  45689. var cameraName = camera.name;
  45690. if (this._cameras.indexOf(camera) === -1) {
  45691. this._cameras[cameraName] = camera;
  45692. }
  45693. else if (unique) {
  45694. indicesToDelete.push(i);
  45695. }
  45696. }
  45697. for (i = 0; i < indicesToDelete.length; i++) {
  45698. cameras.splice(indicesToDelete[i], 1);
  45699. }
  45700. for (var renderEffectName in this._renderEffects) {
  45701. this._renderEffects[renderEffectName]._attachCameras(_cam);
  45702. }
  45703. };
  45704. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  45705. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  45706. for (var renderEffectName in this._renderEffects) {
  45707. this._renderEffects[renderEffectName]._detachCameras(_cam);
  45708. }
  45709. for (var i = 0; i < _cam.length; i++) {
  45710. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  45711. }
  45712. };
  45713. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  45714. var _this = this;
  45715. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  45716. var pass = null;
  45717. var renderEffectName;
  45718. for (renderEffectName in this._renderEffects) {
  45719. pass = this._renderEffects[renderEffectName].getPass(passName);
  45720. if (pass != null) {
  45721. break;
  45722. }
  45723. }
  45724. if (pass === null) {
  45725. return;
  45726. }
  45727. for (renderEffectName in this._renderEffects) {
  45728. this._renderEffects[renderEffectName]._disable(_cam);
  45729. }
  45730. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  45731. for (var i = 0; i < _cam.length; i++) {
  45732. var camera = _cam[i];
  45733. var cameraName = camera.name;
  45734. 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); });
  45735. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  45736. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  45737. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  45738. }
  45739. };
  45740. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  45741. var _this = this;
  45742. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  45743. for (var i = 0; i < _cam.length; i++) {
  45744. var camera = _cam[i];
  45745. var cameraName = camera.name;
  45746. 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); });
  45747. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  45748. }
  45749. for (var renderEffectName in this._renderEffects) {
  45750. this._renderEffects[renderEffectName]._enable(_cam);
  45751. }
  45752. };
  45753. PostProcessRenderPipeline.prototype._update = function () {
  45754. for (var renderEffectName in this._renderEffects) {
  45755. this._renderEffects[renderEffectName]._update();
  45756. }
  45757. for (var i = 0; i < this._cameras.length; i++) {
  45758. var cameraName = this._cameras[i].name;
  45759. if (this._renderEffectsForIsolatedPass[cameraName]) {
  45760. this._renderEffectsForIsolatedPass[cameraName]._update();
  45761. }
  45762. }
  45763. };
  45764. PostProcessRenderPipeline.prototype.dispose = function () {
  45765. // Must be implemented by children
  45766. };
  45767. return PostProcessRenderPipeline;
  45768. }());
  45769. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  45770. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  45771. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  45772. })(BABYLON || (BABYLON = {}));
  45773. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  45774. var BABYLON;
  45775. (function (BABYLON) {
  45776. var DepthRenderer = (function () {
  45777. function DepthRenderer(scene, type) {
  45778. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  45779. var _this = this;
  45780. this._viewMatrix = BABYLON.Matrix.Zero();
  45781. this._projectionMatrix = BABYLON.Matrix.Zero();
  45782. this._transformMatrix = BABYLON.Matrix.Zero();
  45783. this._worldViewProjection = BABYLON.Matrix.Zero();
  45784. this._scene = scene;
  45785. var engine = scene.getEngine();
  45786. // Render target
  45787. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  45788. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45789. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45790. this._depthMap.refreshRate = 1;
  45791. this._depthMap.renderParticles = false;
  45792. this._depthMap.renderList = null;
  45793. // set default depth value to 1.0 (far away)
  45794. this._depthMap.onClearObservable.add(function (engine) {
  45795. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  45796. });
  45797. // Custom render function
  45798. var renderSubMesh = function (subMesh) {
  45799. var mesh = subMesh.getRenderingMesh();
  45800. var scene = _this._scene;
  45801. var engine = scene.getEngine();
  45802. // Culling
  45803. engine.setState(subMesh.getMaterial().backFaceCulling);
  45804. // Managing instances
  45805. var batch = mesh._getInstancesRenderList(subMesh._id);
  45806. if (batch.mustReturn) {
  45807. return;
  45808. }
  45809. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  45810. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  45811. engine.enableEffect(_this._effect);
  45812. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  45813. var material = subMesh.getMaterial();
  45814. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  45815. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  45816. // Alpha test
  45817. if (material && material.needAlphaTesting()) {
  45818. var alphaTexture = material.getAlphaTestTexture();
  45819. _this._effect.setTexture("diffuseSampler", alphaTexture);
  45820. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  45821. }
  45822. // Bones
  45823. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45824. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45825. }
  45826. // Draw
  45827. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  45828. }
  45829. };
  45830. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  45831. var index;
  45832. for (index = 0; index < opaqueSubMeshes.length; index++) {
  45833. renderSubMesh(opaqueSubMeshes.data[index]);
  45834. }
  45835. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  45836. renderSubMesh(alphaTestSubMeshes.data[index]);
  45837. }
  45838. };
  45839. }
  45840. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  45841. var material = subMesh.getMaterial();
  45842. if (material.disableDepthWrite) {
  45843. return false;
  45844. }
  45845. var defines = [];
  45846. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45847. var mesh = subMesh.getMesh();
  45848. var scene = mesh.getScene();
  45849. // Alpha test
  45850. if (material && material.needAlphaTesting()) {
  45851. defines.push("#define ALPHATEST");
  45852. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45853. attribs.push(BABYLON.VertexBuffer.UVKind);
  45854. defines.push("#define UV1");
  45855. }
  45856. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45857. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45858. defines.push("#define UV2");
  45859. }
  45860. }
  45861. // Bones
  45862. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45863. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45864. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45865. if (mesh.numBoneInfluencers > 4) {
  45866. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45867. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45868. }
  45869. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45870. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45871. }
  45872. else {
  45873. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45874. }
  45875. // Instances
  45876. if (useInstances) {
  45877. defines.push("#define INSTANCES");
  45878. attribs.push("world0");
  45879. attribs.push("world1");
  45880. attribs.push("world2");
  45881. attribs.push("world3");
  45882. }
  45883. // Get correct effect
  45884. var join = defines.join("\n");
  45885. if (this._cachedDefines !== join) {
  45886. this._cachedDefines = join;
  45887. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  45888. }
  45889. return this._effect.isReady();
  45890. };
  45891. DepthRenderer.prototype.getDepthMap = function () {
  45892. return this._depthMap;
  45893. };
  45894. // Methods
  45895. DepthRenderer.prototype.dispose = function () {
  45896. this._depthMap.dispose();
  45897. };
  45898. return DepthRenderer;
  45899. }());
  45900. BABYLON.DepthRenderer = DepthRenderer;
  45901. })(BABYLON || (BABYLON = {}));
  45902. //# sourceMappingURL=babylon.depthRenderer.js.map
  45903. var BABYLON;
  45904. (function (BABYLON) {
  45905. var SSAORenderingPipeline = (function (_super) {
  45906. __extends(SSAORenderingPipeline, _super);
  45907. /**
  45908. * @constructor
  45909. * @param {string} name - The rendering pipeline name
  45910. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  45911. * @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 }
  45912. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  45913. */
  45914. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  45915. var _this = _super.call(this, scene.getEngine(), name) || this;
  45916. // Members
  45917. /**
  45918. * The PassPostProcess id in the pipeline that contains the original scene color
  45919. * @type {string}
  45920. */
  45921. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  45922. /**
  45923. * The SSAO PostProcess id in the pipeline
  45924. * @type {string}
  45925. */
  45926. _this.SSAORenderEffect = "SSAORenderEffect";
  45927. /**
  45928. * The horizontal blur PostProcess id in the pipeline
  45929. * @type {string}
  45930. */
  45931. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  45932. /**
  45933. * The vertical blur PostProcess id in the pipeline
  45934. * @type {string}
  45935. */
  45936. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  45937. /**
  45938. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  45939. * @type {string}
  45940. */
  45941. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  45942. /**
  45943. * The output strength of the SSAO post-process. Default value is 1.0.
  45944. * @type {number}
  45945. */
  45946. _this.totalStrength = 1.0;
  45947. /**
  45948. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  45949. * @type {number}
  45950. */
  45951. _this.radius = 0.0001;
  45952. /**
  45953. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  45954. * Must not be equal to fallOff and superior to fallOff.
  45955. * Default value is 0.975
  45956. * @type {number}
  45957. */
  45958. _this.area = 0.0075;
  45959. /**
  45960. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  45961. * Must not be equal to area and inferior to area.
  45962. * Default value is 0.0
  45963. * @type {number}
  45964. */
  45965. _this.fallOff = 0.000001;
  45966. /**
  45967. * The base color of the SSAO post-process
  45968. * The final result is "base + ssao" between [0, 1]
  45969. * @type {number}
  45970. */
  45971. _this.base = 0.5;
  45972. _this._firstUpdate = true;
  45973. _this._scene = scene;
  45974. // Set up assets
  45975. _this._createRandomTexture();
  45976. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  45977. var ssaoRatio = ratio.ssaoRatio || ratio;
  45978. var combineRatio = ratio.combineRatio || ratio;
  45979. _this._ratio = {
  45980. ssaoRatio: ssaoRatio,
  45981. combineRatio: combineRatio
  45982. };
  45983. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  45984. _this._createSSAOPostProcess(ssaoRatio);
  45985. _this._createBlurPostProcess(ssaoRatio);
  45986. _this._createSSAOCombinePostProcess(combineRatio);
  45987. // Set up pipeline
  45988. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  45989. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  45990. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  45991. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  45992. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  45993. // Finish
  45994. scene.postProcessRenderPipelineManager.addPipeline(_this);
  45995. if (cameras)
  45996. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  45997. return _this;
  45998. }
  45999. // Public Methods
  46000. /**
  46001. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  46002. */
  46003. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  46004. if (disableDepthRender === void 0) { disableDepthRender = false; }
  46005. for (var i = 0; i < this._scene.cameras.length; i++) {
  46006. var camera = this._scene.cameras[i];
  46007. this._originalColorPostProcess.dispose(camera);
  46008. this._ssaoPostProcess.dispose(camera);
  46009. this._blurHPostProcess.dispose(camera);
  46010. this._blurVPostProcess.dispose(camera);
  46011. this._ssaoCombinePostProcess.dispose(camera);
  46012. }
  46013. this._randomTexture.dispose();
  46014. if (disableDepthRender)
  46015. this._scene.disableDepthRenderer();
  46016. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46017. _super.prototype.dispose.call(this);
  46018. };
  46019. // Private Methods
  46020. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  46021. var _this = this;
  46022. /*
  46023. var samplerOffsets = [
  46024. -8.0, -6.0, -4.0, -2.0,
  46025. 0.0,
  46026. 2.0, 4.0, 6.0, 8.0
  46027. ];
  46028. */
  46029. var samples = 16;
  46030. var samplerOffsets = [];
  46031. for (var i = -8; i < 8; i++) {
  46032. samplerOffsets.push(i * 2);
  46033. }
  46034. 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");
  46035. this._blurHPostProcess.onApply = function (effect) {
  46036. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  46037. effect.setTexture("depthSampler", _this._depthTexture);
  46038. if (_this._firstUpdate) {
  46039. effect.setArray("samplerOffsets", samplerOffsets);
  46040. }
  46041. };
  46042. 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");
  46043. this._blurVPostProcess.onApply = function (effect) {
  46044. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  46045. effect.setTexture("depthSampler", _this._depthTexture);
  46046. if (_this._firstUpdate) {
  46047. effect.setArray("samplerOffsets", samplerOffsets);
  46048. _this._firstUpdate = false;
  46049. }
  46050. };
  46051. };
  46052. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  46053. var _this = this;
  46054. var numSamples = 16;
  46055. var sampleSphere = [
  46056. 0.5381, 0.1856, -0.4319,
  46057. 0.1379, 0.2486, 0.4430,
  46058. 0.3371, 0.5679, -0.0057,
  46059. -0.6999, -0.0451, -0.0019,
  46060. 0.0689, -0.1598, -0.8547,
  46061. 0.0560, 0.0069, -0.1843,
  46062. -0.0146, 0.1402, 0.0762,
  46063. 0.0100, -0.1924, -0.0344,
  46064. -0.3577, -0.5301, -0.4358,
  46065. -0.3169, 0.1063, 0.0158,
  46066. 0.0103, -0.5869, 0.0046,
  46067. -0.0897, -0.4940, 0.3287,
  46068. 0.7119, -0.0154, -0.0918,
  46069. -0.0533, 0.0596, -0.5411,
  46070. 0.0352, -0.0631, 0.5460,
  46071. -0.4776, 0.2847, -0.0271
  46072. ];
  46073. var samplesFactor = 1.0 / numSamples;
  46074. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  46075. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  46076. "area", "fallOff", "base", "range", "viewport"
  46077. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  46078. var viewport = new BABYLON.Vector2(0, 0);
  46079. this._ssaoPostProcess.onApply = function (effect) {
  46080. if (_this._firstUpdate) {
  46081. effect.setArray3("sampleSphere", sampleSphere);
  46082. effect.setFloat("samplesFactor", samplesFactor);
  46083. effect.setFloat("randTextureTiles", 4.0);
  46084. }
  46085. effect.setFloat("totalStrength", _this.totalStrength);
  46086. effect.setFloat("radius", _this.radius);
  46087. effect.setFloat("area", _this.area);
  46088. effect.setFloat("fallOff", _this.fallOff);
  46089. effect.setFloat("base", _this.base);
  46090. effect.setTexture("textureSampler", _this._depthTexture);
  46091. effect.setTexture("randomSampler", _this._randomTexture);
  46092. };
  46093. };
  46094. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  46095. var _this = this;
  46096. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46097. this._ssaoCombinePostProcess.onApply = function (effect) {
  46098. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  46099. };
  46100. };
  46101. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  46102. var size = 512;
  46103. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  46104. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46105. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46106. var context = this._randomTexture.getContext();
  46107. var rand = function (min, max) {
  46108. return Math.random() * (max - min) + min;
  46109. };
  46110. var randVector = BABYLON.Vector3.Zero();
  46111. for (var x = 0; x < size; x++) {
  46112. for (var y = 0; y < size; y++) {
  46113. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  46114. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  46115. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  46116. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  46117. context.fillRect(x, y, 1, 1);
  46118. }
  46119. }
  46120. this._randomTexture.update(false);
  46121. };
  46122. return SSAORenderingPipeline;
  46123. }(BABYLON.PostProcessRenderPipeline));
  46124. __decorate([
  46125. BABYLON.serialize()
  46126. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  46127. __decorate([
  46128. BABYLON.serialize()
  46129. ], SSAORenderingPipeline.prototype, "radius", void 0);
  46130. __decorate([
  46131. BABYLON.serialize()
  46132. ], SSAORenderingPipeline.prototype, "area", void 0);
  46133. __decorate([
  46134. BABYLON.serialize()
  46135. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  46136. __decorate([
  46137. BABYLON.serialize()
  46138. ], SSAORenderingPipeline.prototype, "base", void 0);
  46139. __decorate([
  46140. BABYLON.serialize()
  46141. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  46142. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  46143. })(BABYLON || (BABYLON = {}));
  46144. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  46145. // BABYLON.JS Chromatic Aberration GLSL Shader
  46146. // Author: Olivier Guyot
  46147. // Separates very slightly R, G and B colors on the edges of the screen
  46148. // Inspired by Francois Tarlier & Martins Upitis
  46149. var BABYLON;
  46150. (function (BABYLON) {
  46151. var LensRenderingPipeline = (function (_super) {
  46152. __extends(LensRenderingPipeline, _super);
  46153. /**
  46154. * @constructor
  46155. *
  46156. * Effect parameters are as follow:
  46157. * {
  46158. * chromatic_aberration: number; // from 0 to x (1 for realism)
  46159. * edge_blur: number; // from 0 to x (1 for realism)
  46160. * distortion: number; // from 0 to x (1 for realism)
  46161. * grain_amount: number; // from 0 to 1
  46162. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  46163. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  46164. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  46165. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  46166. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  46167. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  46168. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  46169. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  46170. * }
  46171. * Note: if an effect parameter is unset, effect is disabled
  46172. *
  46173. * @param {string} name - The rendering pipeline name
  46174. * @param {object} parameters - An object containing all parameters (see above)
  46175. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46176. * @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)
  46177. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46178. */
  46179. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  46180. if (ratio === void 0) { ratio = 1.0; }
  46181. var _this = _super.call(this, scene.getEngine(), name) || this;
  46182. // Lens effects can be of the following:
  46183. // - chromatic aberration (slight shift of RGB colors)
  46184. // - blur on the edge of the lens
  46185. // - lens distortion
  46186. // - depth-of-field blur & highlights enhancing
  46187. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  46188. // - grain effect (noise or custom texture)
  46189. // Two additional texture samplers are needed:
  46190. // - depth map (for depth-of-field)
  46191. // - grain texture
  46192. /**
  46193. * The chromatic aberration PostProcess id in the pipeline
  46194. * @type {string}
  46195. */
  46196. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  46197. /**
  46198. * The highlights enhancing PostProcess id in the pipeline
  46199. * @type {string}
  46200. */
  46201. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  46202. /**
  46203. * The depth-of-field PostProcess id in the pipeline
  46204. * @type {string}
  46205. */
  46206. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  46207. _this._scene = scene;
  46208. // Fetch texture samplers
  46209. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  46210. if (parameters.grain_texture) {
  46211. _this._grainTexture = parameters.grain_texture;
  46212. }
  46213. else {
  46214. _this._createGrainTexture();
  46215. }
  46216. // save parameters
  46217. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  46218. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  46219. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  46220. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  46221. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  46222. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  46223. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  46224. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  46225. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  46226. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  46227. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  46228. // Create effects
  46229. _this._createChromaticAberrationPostProcess(ratio);
  46230. _this._createHighlightsPostProcess(ratio);
  46231. _this._createDepthOfFieldPostProcess(ratio / 4);
  46232. // Set up pipeline
  46233. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  46234. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  46235. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  46236. if (_this._highlightsGain === -1) {
  46237. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  46238. }
  46239. // Finish
  46240. scene.postProcessRenderPipelineManager.addPipeline(_this);
  46241. if (cameras) {
  46242. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46243. }
  46244. return _this;
  46245. }
  46246. // public methods (self explanatory)
  46247. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  46248. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  46249. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  46250. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  46251. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  46252. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  46253. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  46254. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  46255. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  46256. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  46257. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  46258. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  46259. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  46260. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  46261. };
  46262. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  46263. this._highlightsPostProcess.updateEffect();
  46264. };
  46265. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  46266. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  46267. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  46268. this._highlightsGain = amount;
  46269. };
  46270. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  46271. if (this._highlightsGain === -1) {
  46272. this._highlightsGain = 1.0;
  46273. }
  46274. this._highlightsThreshold = amount;
  46275. };
  46276. LensRenderingPipeline.prototype.disableHighlights = function () {
  46277. this._highlightsGain = -1;
  46278. };
  46279. /**
  46280. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  46281. */
  46282. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  46283. if (disableDepthRender === void 0) { disableDepthRender = false; }
  46284. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46285. this._chromaticAberrationPostProcess = undefined;
  46286. this._highlightsPostProcess = undefined;
  46287. this._depthOfFieldPostProcess = undefined;
  46288. this._grainTexture.dispose();
  46289. if (disableDepthRender)
  46290. this._scene.disableDepthRenderer();
  46291. };
  46292. // colors shifting and distortion
  46293. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  46294. var _this = this;
  46295. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  46296. [], // samplers
  46297. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46298. this._chromaticAberrationPostProcess.onApply = function (effect) {
  46299. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  46300. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46301. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46302. };
  46303. };
  46304. // highlights enhancing
  46305. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  46306. var _this = this;
  46307. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  46308. [], // samplers
  46309. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  46310. this._highlightsPostProcess.onApply = function (effect) {
  46311. effect.setFloat('gain', _this._highlightsGain);
  46312. effect.setFloat('threshold', _this._highlightsThreshold);
  46313. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  46314. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46315. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46316. };
  46317. };
  46318. // colors shifting and distortion
  46319. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  46320. var _this = this;
  46321. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  46322. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  46323. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  46324. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46325. this._depthOfFieldPostProcess.onApply = function (effect) {
  46326. effect.setTexture("depthSampler", _this._depthTexture);
  46327. effect.setTexture("grainSampler", _this._grainTexture);
  46328. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  46329. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  46330. effect.setFloat('grain_amount', _this._grainAmount);
  46331. effect.setBool('blur_noise', _this._blurNoise);
  46332. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46333. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46334. effect.setFloat('distortion', _this._distortion);
  46335. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  46336. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  46337. effect.setFloat('aperture', _this._dofAperture);
  46338. effect.setFloat('darken', _this._dofDarken);
  46339. effect.setFloat('edge_blur', _this._edgeBlur);
  46340. effect.setBool('highlights', (_this._highlightsGain !== -1));
  46341. effect.setFloat('near', _this._scene.activeCamera.minZ);
  46342. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  46343. };
  46344. };
  46345. // creates a black and white random noise texture, 512x512
  46346. LensRenderingPipeline.prototype._createGrainTexture = function () {
  46347. var size = 512;
  46348. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46349. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46350. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46351. var context = this._grainTexture.getContext();
  46352. var rand = function (min, max) {
  46353. return Math.random() * (max - min) + min;
  46354. };
  46355. var value;
  46356. for (var x = 0; x < size; x++) {
  46357. for (var y = 0; y < size; y++) {
  46358. value = Math.floor(rand(0.42, 0.58) * 255);
  46359. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  46360. context.fillRect(x, y, 1, 1);
  46361. }
  46362. }
  46363. this._grainTexture.update(false);
  46364. };
  46365. return LensRenderingPipeline;
  46366. }(BABYLON.PostProcessRenderPipeline));
  46367. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  46368. })(BABYLON || (BABYLON = {}));
  46369. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  46370. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  46371. var BABYLON;
  46372. (function (BABYLON) {
  46373. var HDRRenderingPipeline = (function (_super) {
  46374. __extends(HDRRenderingPipeline, _super);
  46375. /**
  46376. * @constructor
  46377. * @param {string} name - The rendering pipeline name
  46378. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46379. * @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)
  46380. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  46381. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46382. */
  46383. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  46384. if (originalPostProcess === void 0) { originalPostProcess = null; }
  46385. var _this = _super.call(this, scene.getEngine(), name) || this;
  46386. /**
  46387. * Public members
  46388. */
  46389. // Gaussian Blur
  46390. /**
  46391. * Gaussian blur coefficient
  46392. * @type {number}
  46393. */
  46394. _this.gaussCoeff = 0.3;
  46395. /**
  46396. * Gaussian blur mean
  46397. * @type {number}
  46398. */
  46399. _this.gaussMean = 1.0;
  46400. /**
  46401. * Gaussian blur standard deviation
  46402. * @type {number}
  46403. */
  46404. _this.gaussStandDev = 0.8;
  46405. /**
  46406. * Gaussian blur multiplier. Multiplies the blur effect
  46407. * @type {number}
  46408. */
  46409. _this.gaussMultiplier = 4.0;
  46410. // HDR
  46411. /**
  46412. * Exposure, controls the overall intensity of the pipeline
  46413. * @type {number}
  46414. */
  46415. _this.exposure = 1.0;
  46416. /**
  46417. * Minimum luminance that the post-process can output. Luminance is >= 0
  46418. * @type {number}
  46419. */
  46420. _this.minimumLuminance = 1.0;
  46421. /**
  46422. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  46423. * @type {number}
  46424. */
  46425. _this.maximumLuminance = 1e20;
  46426. /**
  46427. * Increase rate for luminance: eye adaptation speed to dark
  46428. * @type {number}
  46429. */
  46430. _this.luminanceIncreaserate = 0.5;
  46431. /**
  46432. * Decrease rate for luminance: eye adaptation speed to bright
  46433. * @type {number}
  46434. */
  46435. _this.luminanceDecreaseRate = 0.5;
  46436. // Bright pass
  46437. /**
  46438. * Minimum luminance needed to compute HDR
  46439. * @type {number}
  46440. */
  46441. _this.brightThreshold = 0.8;
  46442. _this._needUpdate = true;
  46443. _this._scene = scene;
  46444. // Bright pass
  46445. _this._createBrightPassPostProcess(scene, ratio);
  46446. // Down sample X4
  46447. _this._createDownSampleX4PostProcess(scene, ratio);
  46448. // Create gaussian blur post-processes
  46449. _this._createGaussianBlurPostProcess(scene, ratio);
  46450. // Texture adder
  46451. _this._createTextureAdderPostProcess(scene, ratio);
  46452. // Luminance generator
  46453. _this._createLuminanceGeneratorPostProcess(scene);
  46454. // HDR
  46455. _this._createHDRPostProcess(scene, ratio);
  46456. // Pass postprocess
  46457. if (originalPostProcess === null) {
  46458. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  46459. }
  46460. else {
  46461. _this._originalPostProcess = originalPostProcess;
  46462. }
  46463. // Configure pipeline
  46464. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  46465. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  46466. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  46467. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  46468. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  46469. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  46470. var addDownSamplerPostProcess = function (id) {
  46471. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  46472. };
  46473. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  46474. addDownSamplerPostProcess(i);
  46475. }
  46476. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  46477. // Finish
  46478. scene.postProcessRenderPipelineManager.addPipeline(_this);
  46479. if (cameras !== null) {
  46480. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46481. }
  46482. _this.update();
  46483. return _this;
  46484. }
  46485. /**
  46486. * Tells the pipeline to update its post-processes
  46487. */
  46488. HDRRenderingPipeline.prototype.update = function () {
  46489. this._needUpdate = true;
  46490. };
  46491. /**
  46492. * Returns the current calculated luminance
  46493. */
  46494. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  46495. return this._hdrCurrentLuminance;
  46496. };
  46497. /**
  46498. * Returns the currently drawn luminance
  46499. */
  46500. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  46501. return this._hdrOutputLuminance;
  46502. };
  46503. /**
  46504. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  46505. */
  46506. HDRRenderingPipeline.prototype.dispose = function () {
  46507. for (var i = 0; i < this._scene.cameras.length; i++) {
  46508. var camera = this._scene.cameras[i];
  46509. this._originalPostProcess.dispose(camera);
  46510. this._brightPassPostProcess.dispose(camera);
  46511. this._downSampleX4PostProcess.dispose(camera);
  46512. this._guassianBlurHPostProcess.dispose(camera);
  46513. this._guassianBlurVPostProcess.dispose(camera);
  46514. this._textureAdderPostProcess.dispose(camera);
  46515. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  46516. this._downSamplePostProcesses[j].dispose(camera);
  46517. }
  46518. this._hdrPostProcess.dispose(camera);
  46519. }
  46520. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46521. _super.prototype.dispose.call(this);
  46522. };
  46523. /**
  46524. * Creates the HDR post-process and computes the luminance adaptation
  46525. */
  46526. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  46527. var _this = this;
  46528. var hdrLastLuminance = 0.0;
  46529. this._hdrOutputLuminance = -1.0;
  46530. this._hdrCurrentLuminance = 1.0;
  46531. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  46532. this._hdrPostProcess.onApply = function (effect) {
  46533. if (_this._hdrOutputLuminance < 0.0) {
  46534. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46535. }
  46536. else {
  46537. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  46538. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  46539. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  46540. }
  46541. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  46542. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  46543. }
  46544. else {
  46545. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46546. }
  46547. }
  46548. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  46549. hdrLastLuminance += scene.getEngine().getDeltaTime();
  46550. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  46551. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46552. effect.setFloat("exposure", _this.exposure);
  46553. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  46554. _this._needUpdate = false;
  46555. };
  46556. };
  46557. /**
  46558. * Texture Adder post-process
  46559. */
  46560. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  46561. var _this = this;
  46562. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  46563. this._textureAdderPostProcess.onApply = function (effect) {
  46564. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46565. };
  46566. };
  46567. /**
  46568. * Down sample X4 post-process
  46569. */
  46570. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  46571. var _this = this;
  46572. var downSampleX4Offsets = new Array(32);
  46573. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  46574. this._downSampleX4PostProcess.onApply = function (effect) {
  46575. if (_this._needUpdate) {
  46576. var id = 0;
  46577. for (var i = -2; i < 2; i++) {
  46578. for (var j = -2; j < 2; j++) {
  46579. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  46580. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  46581. id += 2;
  46582. }
  46583. }
  46584. }
  46585. effect.setArray2("dsOffsets", downSampleX4Offsets);
  46586. };
  46587. };
  46588. /**
  46589. * Bright pass post-process
  46590. */
  46591. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  46592. var _this = this;
  46593. var brightOffsets = new Array(8);
  46594. var brightPassCallback = function (effect) {
  46595. if (_this._needUpdate) {
  46596. var sU = (1.0 / _this._brightPassPostProcess.width);
  46597. var sV = (1.0 / _this._brightPassPostProcess.height);
  46598. brightOffsets[0] = -0.5 * sU;
  46599. brightOffsets[1] = 0.5 * sV;
  46600. brightOffsets[2] = 0.5 * sU;
  46601. brightOffsets[3] = 0.5 * sV;
  46602. brightOffsets[4] = -0.5 * sU;
  46603. brightOffsets[5] = -0.5 * sV;
  46604. brightOffsets[6] = 0.5 * sU;
  46605. brightOffsets[7] = -0.5 * sV;
  46606. }
  46607. effect.setArray2("dsOffsets", brightOffsets);
  46608. effect.setFloat("brightThreshold", _this.brightThreshold);
  46609. };
  46610. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  46611. this._brightPassPostProcess.onApply = brightPassCallback;
  46612. };
  46613. /**
  46614. * Luminance generator. Creates the luminance post-process and down sample post-processes
  46615. */
  46616. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  46617. var _this = this;
  46618. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  46619. var luminanceOffsets = new Array(8);
  46620. var downSampleOffsets = new Array(18);
  46621. var halfDestPixelSize;
  46622. this._downSamplePostProcesses = new Array(lumSteps);
  46623. // Utils for luminance
  46624. var luminanceUpdateSourceOffsets = function (width, height) {
  46625. var sU = (1.0 / width);
  46626. var sV = (1.0 / height);
  46627. luminanceOffsets[0] = -0.5 * sU;
  46628. luminanceOffsets[1] = 0.5 * sV;
  46629. luminanceOffsets[2] = 0.5 * sU;
  46630. luminanceOffsets[3] = 0.5 * sV;
  46631. luminanceOffsets[4] = -0.5 * sU;
  46632. luminanceOffsets[5] = -0.5 * sV;
  46633. luminanceOffsets[6] = 0.5 * sU;
  46634. luminanceOffsets[7] = -0.5 * sV;
  46635. };
  46636. var luminanceUpdateDestOffsets = function (width, height) {
  46637. var id = 0;
  46638. for (var x = -1; x < 2; x++) {
  46639. for (var y = -1; y < 2; y++) {
  46640. downSampleOffsets[id] = (x) / width;
  46641. downSampleOffsets[id + 1] = (y) / height;
  46642. id += 2;
  46643. }
  46644. }
  46645. };
  46646. // Luminance callback
  46647. var luminanceCallback = function (effect) {
  46648. if (_this._needUpdate) {
  46649. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  46650. }
  46651. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  46652. effect.setArray2("lumOffsets", luminanceOffsets);
  46653. };
  46654. // Down sample callbacks
  46655. var downSampleCallback = function (indice) {
  46656. var i = indice;
  46657. return function (effect) {
  46658. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  46659. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  46660. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  46661. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  46662. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  46663. effect.setArray2("dsOffsets", downSampleOffsets);
  46664. };
  46665. };
  46666. var downSampleAfterRenderCallback = function (effect) {
  46667. // Unpack result
  46668. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  46669. 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);
  46670. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  46671. };
  46672. // Create luminance post-process
  46673. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  46674. this._downSamplePostProcesses[lumSteps - 1] = new BABYLON.PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", BABYLON.Engine.TEXTURETYPE_FLOAT);
  46675. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  46676. // Create down sample post-processes
  46677. for (var i = lumSteps - 2; i >= 0; i--) {
  46678. var length = Math.pow(3, i);
  46679. ratio = { width: length, height: length };
  46680. var defines = "#define DOWN_SAMPLE\n";
  46681. if (i === 0) {
  46682. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  46683. }
  46684. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  46685. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  46686. if (i === 0) {
  46687. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  46688. }
  46689. }
  46690. };
  46691. /**
  46692. * Gaussian blur post-processes. Horizontal and Vertical
  46693. */
  46694. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  46695. var _this = this;
  46696. var blurOffsetsW = new Array(9);
  46697. var blurOffsetsH = new Array(9);
  46698. var blurWeights = new Array(9);
  46699. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  46700. // Utils for gaussian blur
  46701. var calculateBlurOffsets = function (height) {
  46702. var lastOutputDimensions = {
  46703. width: scene.getEngine().getRenderWidth(),
  46704. height: scene.getEngine().getRenderHeight()
  46705. };
  46706. for (var i = 0; i < 9; i++) {
  46707. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  46708. if (height) {
  46709. blurOffsetsH[i] = value;
  46710. }
  46711. else {
  46712. blurOffsetsW[i] = value;
  46713. }
  46714. }
  46715. };
  46716. var calculateWeights = function () {
  46717. var x = 0.0;
  46718. for (var i = 0; i < 9; i++) {
  46719. x = (i - 4.0) / 4.0;
  46720. blurWeights[i] = _this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussStandDev)) * Math.exp((-((x - _this.gaussMean) * (x - _this.gaussMean))) / (2.0 * _this.gaussStandDev * _this.gaussStandDev));
  46721. }
  46722. };
  46723. // Callback
  46724. var gaussianBlurCallback = function (height) {
  46725. return function (effect) {
  46726. if (_this._needUpdate) {
  46727. calculateWeights();
  46728. calculateBlurOffsets(height);
  46729. }
  46730. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  46731. effect.setArray("blurWeights", blurWeights);
  46732. effect.setFloat("multiplier", _this.gaussMultiplier);
  46733. };
  46734. };
  46735. // Create horizontal gaussian blur post-processes
  46736. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  46737. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  46738. // Create vertical gaussian blur post-process
  46739. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  46740. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  46741. };
  46742. return HDRRenderingPipeline;
  46743. }(BABYLON.PostProcessRenderPipeline));
  46744. // Luminance generator
  46745. HDRRenderingPipeline.LUM_STEPS = 6;
  46746. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  46747. })(BABYLON || (BABYLON = {}));
  46748. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  46749. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  46750. var BABYLON;
  46751. (function (BABYLON) {
  46752. var StandardRenderingPipeline = (function (_super) {
  46753. __extends(StandardRenderingPipeline, _super);
  46754. /**
  46755. * @constructor
  46756. * @param {string} name - The rendering pipeline name
  46757. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46758. * @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)
  46759. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  46760. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46761. */
  46762. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  46763. if (originalPostProcess === void 0) { originalPostProcess = null; }
  46764. var _this = _super.call(this, scene.getEngine(), name) || this;
  46765. _this.downSampleX4PostProcess = null;
  46766. _this.brightPassPostProcess = null;
  46767. _this.gaussianBlurHPostProcesses = [];
  46768. _this.gaussianBlurVPostProcesses = [];
  46769. _this.textureAdderPostProcess = null;
  46770. _this.textureAdderFinalPostProcess = null;
  46771. _this.lensFlareFinalPostProcess = null;
  46772. _this.lensFlarePostProcess = null;
  46773. _this.lensFlareComposePostProcess = null;
  46774. _this.depthOfFieldPostProcess = null;
  46775. // Values
  46776. _this.brightThreshold = 1.0;
  46777. _this.blurWidth = 2.0;
  46778. _this.horizontalBlur = false;
  46779. _this.gaussianCoefficient = 0.25;
  46780. _this.gaussianMean = 1.0;
  46781. _this.gaussianStandardDeviation = 1.0;
  46782. _this.exposure = 1.0;
  46783. _this.lensTexture = null;
  46784. _this.lensColorTexture = null;
  46785. _this.lensFlareStrength = 20.0;
  46786. _this.lensFlareGhostDispersal = 1.4;
  46787. _this.lensFlareHaloWidth = 0.7;
  46788. _this.lensFlareDistortionStrength = 16.0;
  46789. _this.lensStarTexture = null;
  46790. _this.lensFlareDirtTexture = null;
  46791. _this.depthOfFieldDistance = 10.0;
  46792. _this.depthOfFieldBlurWidth = 2.0;
  46793. // IAnimatable
  46794. _this.animations = [];
  46795. _this._depthRenderer = null;
  46796. _this._currentDepthOfFieldSource = null;
  46797. // Getters and setters
  46798. _this._depthOfFieldEnabled = true;
  46799. _this._lensFlareEnabled = true;
  46800. _this._cameras = cameras || [];
  46801. // Initialize
  46802. _this._scene = scene;
  46803. // Create pass post-processe
  46804. if (!originalPostProcess) {
  46805. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  46806. }
  46807. else {
  46808. _this.originalPostProcess = originalPostProcess;
  46809. }
  46810. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  46811. // Create down sample X4 post-process
  46812. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  46813. // Create bright pass post-process
  46814. _this._createBrightPassPostProcess(scene, ratio / 2);
  46815. // Create gaussian blur post-processes (down sampling blurs)
  46816. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  46817. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  46818. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  46819. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  46820. // Create texture adder post-process
  46821. _this._createTextureAdderPostProcess(scene, ratio);
  46822. // Create depth-of-field source post-process
  46823. _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);
  46824. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  46825. // Create lens flare post-process
  46826. _this._createLensFlarePostProcess(scene, ratio);
  46827. // Create depth-of-field source post-process post lens-flare and disable it now
  46828. _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);
  46829. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  46830. // Create gaussian blur used by depth-of-field
  46831. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  46832. // Create depth-of-field post-process
  46833. _this._createDepthOfFieldPostProcess(scene, ratio);
  46834. // Finish
  46835. scene.postProcessRenderPipelineManager.addPipeline(_this);
  46836. if (cameras !== null) {
  46837. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46838. }
  46839. // Deactivate
  46840. _this.LensFlareEnabled = false;
  46841. _this.DepthOfFieldEnabled = false;
  46842. return _this;
  46843. }
  46844. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  46845. get: function () {
  46846. return this._depthOfFieldEnabled;
  46847. },
  46848. set: function (enabled) {
  46849. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  46850. if (enabled && !this._depthOfFieldEnabled) {
  46851. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  46852. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  46853. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  46854. this._depthRenderer = this._scene.enableDepthRenderer();
  46855. }
  46856. else if (!enabled && this._depthOfFieldEnabled) {
  46857. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  46858. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  46859. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  46860. }
  46861. this._depthOfFieldEnabled = enabled;
  46862. },
  46863. enumerable: true,
  46864. configurable: true
  46865. });
  46866. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  46867. get: function () {
  46868. return this._lensFlareEnabled;
  46869. },
  46870. set: function (enabled) {
  46871. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  46872. if (enabled && !this._lensFlareEnabled) {
  46873. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._cameras);
  46874. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._cameras);
  46875. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  46876. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  46877. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._cameras);
  46878. this._setDepthOfFieldSavePostProcess("HDRPostLensFlareDepthOfFieldSource");
  46879. }
  46880. else if (!enabled && this._lensFlareEnabled) {
  46881. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._cameras);
  46882. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._cameras);
  46883. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  46884. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  46885. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._cameras);
  46886. this._setDepthOfFieldSavePostProcess("HDRBaseDepthOfFieldSource");
  46887. }
  46888. this._lensFlareEnabled = enabled;
  46889. },
  46890. enumerable: true,
  46891. configurable: true
  46892. });
  46893. // Sets depth-of-field save post-process
  46894. StandardRenderingPipeline.prototype._setDepthOfFieldSavePostProcess = function (name) {
  46895. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._cameras);
  46896. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, name, this._cameras);
  46897. switch (name) {
  46898. case "HDRBaseDepthOfFieldSource":
  46899. this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;
  46900. break;
  46901. case "HDRPostLensFlareDepthOfFieldSource":
  46902. this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;
  46903. break;
  46904. default: break;
  46905. }
  46906. };
  46907. // Down Sample X4 Post-Processs
  46908. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  46909. var _this = this;
  46910. var downSampleX4Offsets = new Array(32);
  46911. 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);
  46912. this.downSampleX4PostProcess.onApply = function (effect) {
  46913. var id = 0;
  46914. for (var i = -2; i < 2; i++) {
  46915. for (var j = -2; j < 2; j++) {
  46916. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  46917. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  46918. id += 2;
  46919. }
  46920. }
  46921. effect.setArray2("dsOffsets", downSampleX4Offsets);
  46922. };
  46923. // Add to pipeline
  46924. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  46925. };
  46926. // Brightpass Post-Process
  46927. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  46928. var _this = this;
  46929. var brightOffsets = new Array(8);
  46930. 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);
  46931. this.brightPassPostProcess.onApply = function (effect) {
  46932. var sU = (1.0 / _this.brightPassPostProcess.width);
  46933. var sV = (1.0 / _this.brightPassPostProcess.height);
  46934. brightOffsets[0] = -0.5 * sU;
  46935. brightOffsets[1] = 0.5 * sV;
  46936. brightOffsets[2] = 0.5 * sU;
  46937. brightOffsets[3] = 0.5 * sV;
  46938. brightOffsets[4] = -0.5 * sU;
  46939. brightOffsets[5] = -0.5 * sV;
  46940. brightOffsets[6] = 0.5 * sU;
  46941. brightOffsets[7] = -0.5 * sV;
  46942. effect.setArray2("dsOffsets", brightOffsets);
  46943. effect.setFloat("brightThreshold", _this.brightThreshold);
  46944. };
  46945. // Add to pipeline
  46946. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  46947. };
  46948. // Create gaussian blur H&V post-processes
  46949. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  46950. var _this = this;
  46951. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  46952. var blurOffsets = new Array(9);
  46953. var blurWeights = new Array(9);
  46954. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  46955. var callback = function (height) {
  46956. return function (effect) {
  46957. // Weights
  46958. var x = 0.0;
  46959. for (var i = 0; i < 9; i++) {
  46960. x = (i - 4.0) / 4.0;
  46961. blurWeights[i] =
  46962. _this.gaussianCoefficient
  46963. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  46964. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  46965. }
  46966. var lastOutputDimensions = {
  46967. width: scene.getEngine().getRenderWidth(),
  46968. height: scene.getEngine().getRenderHeight()
  46969. };
  46970. for (var i = 0; i < 9; i++) {
  46971. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  46972. blurOffsets[i] = value;
  46973. }
  46974. effect.setArray("blurOffsets", blurOffsets);
  46975. effect.setArray("blurWeights", blurWeights);
  46976. if (height) {
  46977. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  46978. }
  46979. else {
  46980. effect.setFloat("blurWidth", _this[blurWidthKey]);
  46981. }
  46982. };
  46983. };
  46984. // Create horizontal gaussian blur post-processes
  46985. 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);
  46986. gaussianBlurHPostProcess.onApply = callback(false);
  46987. // Create vertical gaussian blur post-process
  46988. 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);
  46989. gaussianBlurVPostProcess.onApply = callback(true);
  46990. // Add to pipeline
  46991. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  46992. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  46993. // Finish
  46994. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  46995. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  46996. };
  46997. // Create texture adder post-process
  46998. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  46999. var _this = this;
  47000. 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);
  47001. this.textureAdderPostProcess.onApply = function (effect) {
  47002. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  47003. effect.setTexture("lensSampler", _this.lensTexture);
  47004. effect.setFloat("exposure", _this.exposure);
  47005. };
  47006. // Add to pipeline
  47007. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  47008. };
  47009. // Create lens flare post-process
  47010. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  47011. var _this = this;
  47012. 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);
  47013. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  47014. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  47015. 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);
  47016. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  47017. var resolution = new BABYLON.Vector2(0, 0);
  47018. // Lens flare
  47019. this.lensFlarePostProcess.onApply = function (effect) {
  47020. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  47021. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  47022. effect.setFloat("strength", _this.lensFlareStrength);
  47023. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  47024. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  47025. // Shift
  47026. resolution.x = _this.lensFlarePostProcess.width;
  47027. resolution.y = _this.lensFlarePostProcess.height;
  47028. effect.setVector2("resolution", resolution);
  47029. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  47030. };
  47031. // Compose
  47032. 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);
  47033. 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);
  47034. this.lensFlareComposePostProcess.onApply = function (effect) {
  47035. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  47036. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  47037. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  47038. // Lens start rotation matrix
  47039. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  47040. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  47041. 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));
  47042. camRot *= 4.0;
  47043. 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);
  47044. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  47045. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  47046. };
  47047. };
  47048. // Create depth-of-field post-process
  47049. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  47050. var _this = this;
  47051. 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);
  47052. this.depthOfFieldPostProcess.onApply = function (effect) {
  47053. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  47054. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  47055. effect.setFloat("distance", _this.depthOfFieldDistance);
  47056. };
  47057. // Add to pipeline
  47058. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  47059. };
  47060. // Dispose
  47061. StandardRenderingPipeline.prototype.dispose = function () {
  47062. for (var i = 0; i < this._cameras.length; i++) {
  47063. var camera = this._cameras[i];
  47064. this.originalPostProcess.dispose(camera);
  47065. this.downSampleX4PostProcess.dispose(camera);
  47066. this.brightPassPostProcess.dispose(camera);
  47067. this.textureAdderPostProcess.dispose(camera);
  47068. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  47069. this.gaussianBlurHPostProcesses[j].dispose(camera);
  47070. }
  47071. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  47072. this.gaussianBlurVPostProcesses[j].dispose(camera);
  47073. }
  47074. this.textureAdderFinalPostProcess.dispose(camera);
  47075. this.lensFlarePostProcess.dispose(camera);
  47076. this.lensFlareComposePostProcess.dispose(camera);
  47077. this.depthOfFieldPostProcess.dispose(camera);
  47078. }
  47079. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  47080. _super.prototype.dispose.call(this);
  47081. };
  47082. // Serialize rendering pipeline
  47083. StandardRenderingPipeline.prototype.serialize = function () {
  47084. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47085. serializationObject.customType = "StandardRenderingPipeline";
  47086. return serializationObject;
  47087. };
  47088. // Parse serialized pipeline
  47089. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  47090. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  47091. };
  47092. return StandardRenderingPipeline;
  47093. }(BABYLON.PostProcessRenderPipeline));
  47094. __decorate([
  47095. BABYLON.serialize()
  47096. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  47097. __decorate([
  47098. BABYLON.serialize()
  47099. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  47100. __decorate([
  47101. BABYLON.serialize()
  47102. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  47103. __decorate([
  47104. BABYLON.serialize()
  47105. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  47106. __decorate([
  47107. BABYLON.serialize()
  47108. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  47109. __decorate([
  47110. BABYLON.serialize()
  47111. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  47112. __decorate([
  47113. BABYLON.serialize()
  47114. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  47115. __decorate([
  47116. BABYLON.serializeAsTexture("lensTexture")
  47117. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  47118. __decorate([
  47119. BABYLON.serializeAsTexture("lensColorTexture")
  47120. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  47121. __decorate([
  47122. BABYLON.serialize()
  47123. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  47124. __decorate([
  47125. BABYLON.serialize()
  47126. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  47127. __decorate([
  47128. BABYLON.serialize()
  47129. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  47130. __decorate([
  47131. BABYLON.serialize()
  47132. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  47133. __decorate([
  47134. BABYLON.serializeAsTexture("lensStarTexture")
  47135. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  47136. __decorate([
  47137. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  47138. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  47139. __decorate([
  47140. BABYLON.serialize()
  47141. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  47142. __decorate([
  47143. BABYLON.serialize()
  47144. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  47145. __decorate([
  47146. BABYLON.serialize()
  47147. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  47148. __decorate([
  47149. BABYLON.serialize()
  47150. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  47151. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  47152. })(BABYLON || (BABYLON = {}));
  47153. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  47154. var BABYLON;
  47155. (function (BABYLON) {
  47156. var BlurPostProcess = (function (_super) {
  47157. __extends(BlurPostProcess, _super);
  47158. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  47159. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47160. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  47161. _this.direction = direction;
  47162. _this.blurWidth = blurWidth;
  47163. _this.onApplyObservable.add(function (effect) {
  47164. effect.setFloat2("screenSize", _this.width, _this.height);
  47165. effect.setVector2("direction", _this.direction);
  47166. effect.setFloat("blurWidth", _this.blurWidth);
  47167. });
  47168. return _this;
  47169. }
  47170. return BlurPostProcess;
  47171. }(BABYLON.PostProcess));
  47172. BABYLON.BlurPostProcess = BlurPostProcess;
  47173. })(BABYLON || (BABYLON = {}));
  47174. //# sourceMappingURL=babylon.blurPostProcess.js.map
  47175. var BABYLON;
  47176. (function (BABYLON) {
  47177. var RefractionPostProcess = (function (_super) {
  47178. __extends(RefractionPostProcess, _super);
  47179. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  47180. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  47181. _this.color = color;
  47182. _this.depth = depth;
  47183. _this.colorLevel = colorLevel;
  47184. _this.onActivateObservable.add(function (cam) {
  47185. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  47186. });
  47187. _this.onApplyObservable.add(function (effect) {
  47188. effect.setColor3("baseColor", _this.color);
  47189. effect.setFloat("depth", _this.depth);
  47190. effect.setFloat("colorLevel", _this.colorLevel);
  47191. effect.setTexture("refractionSampler", _this._refRexture);
  47192. });
  47193. return _this;
  47194. }
  47195. // Methods
  47196. RefractionPostProcess.prototype.dispose = function (camera) {
  47197. if (this._refRexture) {
  47198. this._refRexture.dispose();
  47199. }
  47200. _super.prototype.dispose.call(this, camera);
  47201. };
  47202. return RefractionPostProcess;
  47203. }(BABYLON.PostProcess));
  47204. BABYLON.RefractionPostProcess = RefractionPostProcess;
  47205. })(BABYLON || (BABYLON = {}));
  47206. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  47207. var BABYLON;
  47208. (function (BABYLON) {
  47209. var BlackAndWhitePostProcess = (function (_super) {
  47210. __extends(BlackAndWhitePostProcess, _super);
  47211. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  47212. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  47213. }
  47214. return BlackAndWhitePostProcess;
  47215. }(BABYLON.PostProcess));
  47216. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  47217. })(BABYLON || (BABYLON = {}));
  47218. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  47219. var BABYLON;
  47220. (function (BABYLON) {
  47221. var ConvolutionPostProcess = (function (_super) {
  47222. __extends(ConvolutionPostProcess, _super);
  47223. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  47224. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  47225. _this.kernel = kernel;
  47226. _this.onApply = function (effect) {
  47227. effect.setFloat2("screenSize", _this.width, _this.height);
  47228. effect.setArray("kernel", _this.kernel);
  47229. };
  47230. return _this;
  47231. }
  47232. return ConvolutionPostProcess;
  47233. }(BABYLON.PostProcess));
  47234. // Statics
  47235. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  47236. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  47237. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  47238. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  47239. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  47240. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  47241. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  47242. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  47243. })(BABYLON || (BABYLON = {}));
  47244. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  47245. var BABYLON;
  47246. (function (BABYLON) {
  47247. var FilterPostProcess = (function (_super) {
  47248. __extends(FilterPostProcess, _super);
  47249. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  47250. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  47251. _this.kernelMatrix = kernelMatrix;
  47252. _this.onApply = function (effect) {
  47253. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  47254. };
  47255. return _this;
  47256. }
  47257. return FilterPostProcess;
  47258. }(BABYLON.PostProcess));
  47259. BABYLON.FilterPostProcess = FilterPostProcess;
  47260. })(BABYLON || (BABYLON = {}));
  47261. //# sourceMappingURL=babylon.filterPostProcess.js.map
  47262. var BABYLON;
  47263. (function (BABYLON) {
  47264. var FxaaPostProcess = (function (_super) {
  47265. __extends(FxaaPostProcess, _super);
  47266. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  47267. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable) || this;
  47268. _this.onSizeChangedObservable.add(function () {
  47269. _this.texelWidth = 1.0 / _this.width;
  47270. _this.texelHeight = 1.0 / _this.height;
  47271. });
  47272. _this.onApplyObservable.add(function (effect) {
  47273. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  47274. });
  47275. return _this;
  47276. }
  47277. return FxaaPostProcess;
  47278. }(BABYLON.PostProcess));
  47279. BABYLON.FxaaPostProcess = FxaaPostProcess;
  47280. })(BABYLON || (BABYLON = {}));
  47281. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  47282. var BABYLON;
  47283. (function (BABYLON) {
  47284. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  47285. var VolumetricLightScatteringPostProcess = (function (_super) {
  47286. __extends(VolumetricLightScatteringPostProcess, _super);
  47287. /**
  47288. * @constructor
  47289. * @param {string} name - The post-process name
  47290. * @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)
  47291. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  47292. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  47293. * @param {number} samples - The post-process quality, default 100
  47294. * @param {number} samplingMode - The post-process filtering mode
  47295. * @param {BABYLON.Engine} engine - The babylon engine
  47296. * @param {boolean} reusable - If the post-process is reusable
  47297. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  47298. */
  47299. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  47300. if (samples === void 0) { samples = 100; }
  47301. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47302. 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;
  47303. _this._screenCoordinates = BABYLON.Vector2.Zero();
  47304. /**
  47305. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  47306. * @type {Vector3}
  47307. */
  47308. _this.customMeshPosition = BABYLON.Vector3.Zero();
  47309. /**
  47310. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  47311. * @type {boolean}
  47312. */
  47313. _this.useCustomMeshPosition = false;
  47314. /**
  47315. * If the post-process should inverse the light scattering direction
  47316. * @type {boolean}
  47317. */
  47318. _this.invert = true;
  47319. /**
  47320. * Array containing the excluded meshes not rendered in the internal pass
  47321. */
  47322. _this.excludedMeshes = new Array();
  47323. /**
  47324. * Controls the overall intensity of the post-process
  47325. * @type {number}
  47326. */
  47327. _this.exposure = 0.3;
  47328. /**
  47329. * Dissipates each sample's contribution in range [0, 1]
  47330. * @type {number}
  47331. */
  47332. _this.decay = 0.96815;
  47333. /**
  47334. * Controls the overall intensity of each sample
  47335. * @type {number}
  47336. */
  47337. _this.weight = 0.58767;
  47338. /**
  47339. * Controls the density of each sample
  47340. * @type {number}
  47341. */
  47342. _this.density = 0.926;
  47343. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  47344. var engine = scene.getEngine();
  47345. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47346. // Configure mesh
  47347. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  47348. // Configure
  47349. _this._createPass(scene, ratio.passRatio || ratio);
  47350. _this.onActivate = function (camera) {
  47351. if (!_this.isSupported) {
  47352. _this.dispose(camera);
  47353. }
  47354. _this.onActivate = null;
  47355. };
  47356. _this.onApplyObservable.add(function (effect) {
  47357. _this._updateMeshScreenCoordinates(scene);
  47358. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  47359. effect.setFloat("exposure", _this.exposure);
  47360. effect.setFloat("decay", _this.decay);
  47361. effect.setFloat("weight", _this.weight);
  47362. effect.setFloat("density", _this.density);
  47363. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  47364. });
  47365. return _this;
  47366. }
  47367. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  47368. get: function () {
  47369. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47370. return false;
  47371. },
  47372. set: function (useDiffuseColor) {
  47373. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47374. },
  47375. enumerable: true,
  47376. configurable: true
  47377. });
  47378. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  47379. var mesh = subMesh.getMesh();
  47380. // Render this.mesh as default
  47381. if (mesh === this.mesh) {
  47382. return mesh.material.isReady(mesh);
  47383. }
  47384. var defines = [];
  47385. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47386. var material = subMesh.getMaterial();
  47387. var needUV = false;
  47388. // Alpha test
  47389. if (material) {
  47390. if (material.needAlphaTesting()) {
  47391. defines.push("#define ALPHATEST");
  47392. }
  47393. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47394. attribs.push(BABYLON.VertexBuffer.UVKind);
  47395. defines.push("#define UV1");
  47396. }
  47397. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47398. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47399. defines.push("#define UV2");
  47400. }
  47401. }
  47402. // Bones
  47403. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47404. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47405. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47406. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47407. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47408. }
  47409. else {
  47410. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47411. }
  47412. // Instances
  47413. if (useInstances) {
  47414. defines.push("#define INSTANCES");
  47415. attribs.push("world0");
  47416. attribs.push("world1");
  47417. attribs.push("world2");
  47418. attribs.push("world3");
  47419. }
  47420. // Get correct effect
  47421. var join = defines.join("\n");
  47422. if (this._cachedDefines !== join) {
  47423. this._cachedDefines = join;
  47424. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  47425. }
  47426. return this._volumetricLightScatteringPass.isReady();
  47427. };
  47428. /**
  47429. * Sets the new light position for light scattering effect
  47430. * @param {BABYLON.Vector3} The new custom light position
  47431. */
  47432. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  47433. this.customMeshPosition = position;
  47434. };
  47435. /**
  47436. * Returns the light position for light scattering effect
  47437. * @return {BABYLON.Vector3} The custom light position
  47438. */
  47439. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  47440. return this.customMeshPosition;
  47441. };
  47442. /**
  47443. * Disposes the internal assets and detaches the post-process from the camera
  47444. */
  47445. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  47446. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  47447. if (rttIndex !== -1) {
  47448. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  47449. }
  47450. this._volumetricLightScatteringRTT.dispose();
  47451. _super.prototype.dispose.call(this, camera);
  47452. };
  47453. /**
  47454. * Returns the render target texture used by the post-process
  47455. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  47456. */
  47457. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  47458. return this._volumetricLightScatteringRTT;
  47459. };
  47460. // Private methods
  47461. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  47462. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  47463. return true;
  47464. }
  47465. return false;
  47466. };
  47467. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  47468. var _this = this;
  47469. var engine = scene.getEngine();
  47470. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47471. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47472. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47473. this._volumetricLightScatteringRTT.renderList = null;
  47474. this._volumetricLightScatteringRTT.renderParticles = false;
  47475. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  47476. // Custom render function for submeshes
  47477. var renderSubMesh = function (subMesh) {
  47478. var mesh = subMesh.getRenderingMesh();
  47479. if (_this._meshExcluded(mesh)) {
  47480. return;
  47481. }
  47482. var scene = mesh.getScene();
  47483. var engine = scene.getEngine();
  47484. // Culling
  47485. engine.setState(subMesh.getMaterial().backFaceCulling);
  47486. // Managing instances
  47487. var batch = mesh._getInstancesRenderList(subMesh._id);
  47488. if (batch.mustReturn) {
  47489. return;
  47490. }
  47491. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47492. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47493. var effect = _this._volumetricLightScatteringPass;
  47494. if (mesh === _this.mesh) {
  47495. if (subMesh.effect) {
  47496. effect = subMesh.effect;
  47497. }
  47498. else {
  47499. effect = subMesh.getMaterial().getEffect();
  47500. }
  47501. }
  47502. engine.enableEffect(effect);
  47503. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  47504. if (mesh === _this.mesh) {
  47505. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  47506. }
  47507. else {
  47508. var material = subMesh.getMaterial();
  47509. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  47510. // Alpha test
  47511. if (material && material.needAlphaTesting()) {
  47512. var alphaTexture = material.getAlphaTestTexture();
  47513. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  47514. if (alphaTexture) {
  47515. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47516. }
  47517. }
  47518. // Bones
  47519. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47520. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47521. }
  47522. }
  47523. // Draw
  47524. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  47525. }
  47526. };
  47527. // Render target texture callbacks
  47528. var savedSceneClearColor;
  47529. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  47530. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  47531. savedSceneClearColor = scene.clearColor;
  47532. scene.clearColor = sceneClearColor;
  47533. });
  47534. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  47535. scene.clearColor = savedSceneClearColor;
  47536. });
  47537. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  47538. var engine = scene.getEngine();
  47539. var index;
  47540. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47541. renderSubMesh(opaqueSubMeshes.data[index]);
  47542. }
  47543. engine.setAlphaTesting(true);
  47544. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47545. renderSubMesh(alphaTestSubMeshes.data[index]);
  47546. }
  47547. engine.setAlphaTesting(false);
  47548. if (transparentSubMeshes.length) {
  47549. // Sort sub meshes
  47550. for (index = 0; index < transparentSubMeshes.length; index++) {
  47551. var submesh = transparentSubMeshes.data[index];
  47552. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  47553. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  47554. }
  47555. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  47556. sortedArray.sort(function (a, b) {
  47557. // Alpha index first
  47558. if (a._alphaIndex > b._alphaIndex) {
  47559. return 1;
  47560. }
  47561. if (a._alphaIndex < b._alphaIndex) {
  47562. return -1;
  47563. }
  47564. // Then distance to camera
  47565. if (a._distanceToCamera < b._distanceToCamera) {
  47566. return 1;
  47567. }
  47568. if (a._distanceToCamera > b._distanceToCamera) {
  47569. return -1;
  47570. }
  47571. return 0;
  47572. });
  47573. // Render sub meshes
  47574. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47575. for (index = 0; index < sortedArray.length; index++) {
  47576. renderSubMesh(sortedArray[index]);
  47577. }
  47578. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47579. }
  47580. };
  47581. };
  47582. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  47583. var transform = scene.getTransformMatrix();
  47584. var meshPosition;
  47585. if (this.useCustomMeshPosition) {
  47586. meshPosition = this.customMeshPosition;
  47587. }
  47588. else if (this.attachedNode) {
  47589. meshPosition = this.attachedNode.position;
  47590. }
  47591. else {
  47592. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  47593. }
  47594. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  47595. this._screenCoordinates.x = pos.x / this._viewPort.width;
  47596. this._screenCoordinates.y = pos.y / this._viewPort.height;
  47597. if (this.invert)
  47598. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  47599. };
  47600. // Static methods
  47601. /**
  47602. * Creates a default mesh for the Volumeric Light Scattering post-process
  47603. * @param {string} The mesh name
  47604. * @param {BABYLON.Scene} The scene where to create the mesh
  47605. * @return {BABYLON.Mesh} the default mesh
  47606. */
  47607. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  47608. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  47609. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  47610. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  47611. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  47612. mesh.material = material;
  47613. return mesh;
  47614. };
  47615. return VolumetricLightScatteringPostProcess;
  47616. }(BABYLON.PostProcess));
  47617. __decorate([
  47618. BABYLON.serializeAsVector3()
  47619. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  47620. __decorate([
  47621. BABYLON.serialize()
  47622. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  47623. __decorate([
  47624. BABYLON.serialize()
  47625. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  47626. __decorate([
  47627. BABYLON.serializeAsMeshReference()
  47628. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  47629. __decorate([
  47630. BABYLON.serialize()
  47631. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  47632. __decorate([
  47633. BABYLON.serialize()
  47634. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  47635. __decorate([
  47636. BABYLON.serialize()
  47637. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  47638. __decorate([
  47639. BABYLON.serialize()
  47640. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  47641. __decorate([
  47642. BABYLON.serialize()
  47643. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  47644. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  47645. })(BABYLON || (BABYLON = {}));
  47646. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  47647. //
  47648. // This post-process allows the modification of rendered colors by using
  47649. // a 'look-up table' (LUT). This effect is also called Color Grading.
  47650. //
  47651. // The object needs to be provided an url to a texture containing the color
  47652. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  47653. // Use an image editing software to tweak the LUT to match your needs.
  47654. //
  47655. // For an example of a color LUT, see here:
  47656. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  47657. // For explanations on color grading, see here:
  47658. // http://udn.epicgames.com/Three/ColorGrading.html
  47659. //
  47660. var BABYLON;
  47661. (function (BABYLON) {
  47662. var ColorCorrectionPostProcess = (function (_super) {
  47663. __extends(ColorCorrectionPostProcess, _super);
  47664. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  47665. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  47666. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47667. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  47668. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47669. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47670. _this.onApply = function (effect) {
  47671. effect.setTexture("colorTable", _this._colorTableTexture);
  47672. };
  47673. return _this;
  47674. }
  47675. return ColorCorrectionPostProcess;
  47676. }(BABYLON.PostProcess));
  47677. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  47678. })(BABYLON || (BABYLON = {}));
  47679. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  47680. var BABYLON;
  47681. (function (BABYLON) {
  47682. var TonemappingOperator;
  47683. (function (TonemappingOperator) {
  47684. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  47685. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  47686. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  47687. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  47688. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  47689. ;
  47690. var TonemapPostProcess = (function (_super) {
  47691. __extends(TonemapPostProcess, _super);
  47692. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  47693. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47694. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47695. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  47696. _this._operator = _operator;
  47697. _this.exposureAdjustment = exposureAdjustment;
  47698. var defines = "#define ";
  47699. if (_this._operator === TonemappingOperator.Hable)
  47700. defines += "HABLE_TONEMAPPING";
  47701. else if (_this._operator === TonemappingOperator.Reinhard)
  47702. defines += "REINHARD_TONEMAPPING";
  47703. else if (_this._operator === TonemappingOperator.HejiDawson)
  47704. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  47705. else if (_this._operator === TonemappingOperator.Photographic)
  47706. defines += "PHOTOGRAPHIC_TONEMAPPING";
  47707. //sadly a second call to create the effect.
  47708. _this.updateEffect(defines);
  47709. _this.onApply = function (effect) {
  47710. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  47711. };
  47712. return _this;
  47713. }
  47714. return TonemapPostProcess;
  47715. }(BABYLON.PostProcess));
  47716. BABYLON.TonemapPostProcess = TonemapPostProcess;
  47717. })(BABYLON || (BABYLON = {}));
  47718. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  47719. var BABYLON;
  47720. (function (BABYLON) {
  47721. var DisplayPassPostProcess = (function (_super) {
  47722. __extends(DisplayPassPostProcess, _super);
  47723. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  47724. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  47725. }
  47726. return DisplayPassPostProcess;
  47727. }(BABYLON.PostProcess));
  47728. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  47729. })(BABYLON || (BABYLON = {}));
  47730. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  47731. /// <reference path="..\babylon.node.ts" />
  47732. var BABYLON;
  47733. (function (BABYLON) {
  47734. var Bone = (function (_super) {
  47735. __extends(Bone, _super);
  47736. function Bone(name, skeleton, parentBone, matrix, restPose) {
  47737. var _this = _super.call(this, name, skeleton.getScene()) || this;
  47738. _this.name = name;
  47739. _this.children = new Array();
  47740. _this.animations = new Array();
  47741. _this._worldTransform = new BABYLON.Matrix();
  47742. _this._absoluteTransform = new BABYLON.Matrix();
  47743. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  47744. _this._scaleMatrix = BABYLON.Matrix.Identity();
  47745. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  47746. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  47747. _this._scalingDeterminant = 1;
  47748. _this._skeleton = skeleton;
  47749. _this._localMatrix = matrix;
  47750. _this._baseMatrix = matrix.clone();
  47751. _this._restPose = restPose ? restPose : matrix.clone();
  47752. skeleton.bones.push(_this);
  47753. if (parentBone) {
  47754. _this._parent = parentBone;
  47755. parentBone.children.push(_this);
  47756. }
  47757. else {
  47758. _this._parent = null;
  47759. }
  47760. _this._updateDifferenceMatrix();
  47761. if (_this.getAbsoluteTransform().determinant() < 0) {
  47762. _this._scalingDeterminant *= -1;
  47763. }
  47764. return _this;
  47765. }
  47766. Object.defineProperty(Bone.prototype, "_matrix", {
  47767. get: function () {
  47768. return this._localMatrix;
  47769. },
  47770. set: function (val) {
  47771. if (this._localMatrix) {
  47772. this._localMatrix.copyFrom(val);
  47773. }
  47774. else {
  47775. this._localMatrix = val;
  47776. }
  47777. },
  47778. enumerable: true,
  47779. configurable: true
  47780. });
  47781. // Members
  47782. Bone.prototype.getParent = function () {
  47783. return this._parent;
  47784. };
  47785. Bone.prototype.getLocalMatrix = function () {
  47786. return this._localMatrix;
  47787. };
  47788. Bone.prototype.getBaseMatrix = function () {
  47789. return this._baseMatrix;
  47790. };
  47791. Bone.prototype.getRestPose = function () {
  47792. return this._restPose;
  47793. };
  47794. Bone.prototype.returnToRest = function () {
  47795. this.updateMatrix(this._restPose.clone());
  47796. };
  47797. Bone.prototype.getWorldMatrix = function () {
  47798. return this._worldTransform;
  47799. };
  47800. Bone.prototype.getInvertedAbsoluteTransform = function () {
  47801. return this._invertedAbsoluteTransform;
  47802. };
  47803. Bone.prototype.getAbsoluteTransform = function () {
  47804. return this._absoluteTransform;
  47805. };
  47806. // Methods
  47807. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  47808. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  47809. this._baseMatrix = matrix.clone();
  47810. this._localMatrix = matrix.clone();
  47811. this._skeleton._markAsDirty();
  47812. if (updateDifferenceMatrix) {
  47813. this._updateDifferenceMatrix();
  47814. }
  47815. };
  47816. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  47817. if (!rootMatrix) {
  47818. rootMatrix = this._baseMatrix;
  47819. }
  47820. if (this._parent) {
  47821. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  47822. }
  47823. else {
  47824. this._absoluteTransform.copyFrom(rootMatrix);
  47825. }
  47826. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  47827. for (var index = 0; index < this.children.length; index++) {
  47828. this.children[index]._updateDifferenceMatrix();
  47829. }
  47830. };
  47831. Bone.prototype.markAsDirty = function () {
  47832. this._currentRenderId++;
  47833. this._skeleton._markAsDirty();
  47834. };
  47835. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  47836. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  47837. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  47838. // all animation may be coming from a library skeleton, so may need to create animation
  47839. if (this.animations.length === 0) {
  47840. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  47841. this.animations[0].setKeys([]);
  47842. }
  47843. // get animation info / verify there is such a range from the source bone
  47844. var sourceRange = source.animations[0].getRange(rangeName);
  47845. if (!sourceRange) {
  47846. return false;
  47847. }
  47848. var from = sourceRange.from;
  47849. var to = sourceRange.to;
  47850. var sourceKeys = source.animations[0].getKeys();
  47851. // rescaling prep
  47852. var sourceBoneLength = source.length;
  47853. var sourceParent = source.getParent();
  47854. var parent = this.getParent();
  47855. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  47856. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  47857. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  47858. var destKeys = this.animations[0].getKeys();
  47859. // loop vars declaration
  47860. var orig;
  47861. var origTranslation;
  47862. var mat;
  47863. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  47864. orig = sourceKeys[key];
  47865. if (orig.frame >= from && orig.frame <= to) {
  47866. if (rescaleAsRequired) {
  47867. mat = orig.value.clone();
  47868. // scale based on parent ratio, when bone has parent
  47869. if (parentScalingReqd) {
  47870. origTranslation = mat.getTranslation();
  47871. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  47872. // scale based on skeleton dimension ratio when root bone, and value is passed
  47873. }
  47874. else if (dimensionsScalingReqd) {
  47875. origTranslation = mat.getTranslation();
  47876. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  47877. // use original when root bone, and no data for skelDimensionsRatio
  47878. }
  47879. else {
  47880. mat = orig.value;
  47881. }
  47882. }
  47883. else {
  47884. mat = orig.value;
  47885. }
  47886. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  47887. }
  47888. }
  47889. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  47890. return true;
  47891. };
  47892. /**
  47893. * Translate the bone in local or world space.
  47894. * @param vec The amount to translate the bone.
  47895. * @param space The space that the translation is in.
  47896. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  47897. */
  47898. Bone.prototype.translate = function (vec, space, mesh) {
  47899. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  47900. var lm = this.getLocalMatrix();
  47901. if (space == BABYLON.Space.LOCAL) {
  47902. lm.m[12] += vec.x;
  47903. lm.m[13] += vec.y;
  47904. lm.m[14] += vec.z;
  47905. }
  47906. else {
  47907. var wm;
  47908. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  47909. if (mesh) {
  47910. wm = mesh.getWorldMatrix();
  47911. }
  47912. this._skeleton.computeAbsoluteTransforms();
  47913. var tmat = Bone._tmpMats[0];
  47914. var tvec = Bone._tmpVecs[0];
  47915. if (mesh) {
  47916. tmat.copyFrom(this._parent.getAbsoluteTransform());
  47917. tmat.multiplyToRef(wm, tmat);
  47918. }
  47919. else {
  47920. tmat.copyFrom(this._parent.getAbsoluteTransform());
  47921. }
  47922. tmat.m[12] = 0;
  47923. tmat.m[13] = 0;
  47924. tmat.m[14] = 0;
  47925. tmat.invert();
  47926. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  47927. lm.m[12] += tvec.x;
  47928. lm.m[13] += tvec.y;
  47929. lm.m[14] += tvec.z;
  47930. }
  47931. this.markAsDirty();
  47932. };
  47933. /**
  47934. * Set the postion of the bone in local or world space.
  47935. * @param position The position to set the bone.
  47936. * @param space The space that the position is in.
  47937. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  47938. */
  47939. Bone.prototype.setPosition = function (position, space, mesh) {
  47940. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  47941. var lm = this.getLocalMatrix();
  47942. if (space == BABYLON.Space.LOCAL) {
  47943. lm.m[12] = position.x;
  47944. lm.m[13] = position.y;
  47945. lm.m[14] = position.z;
  47946. }
  47947. else {
  47948. var wm;
  47949. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  47950. if (mesh) {
  47951. wm = mesh.getWorldMatrix();
  47952. }
  47953. this._skeleton.computeAbsoluteTransforms();
  47954. var tmat = Bone._tmpMats[0];
  47955. var vec = Bone._tmpVecs[0];
  47956. if (mesh) {
  47957. tmat.copyFrom(this._parent.getAbsoluteTransform());
  47958. tmat.multiplyToRef(wm, tmat);
  47959. }
  47960. else {
  47961. tmat.copyFrom(this._parent.getAbsoluteTransform());
  47962. }
  47963. tmat.invert();
  47964. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  47965. lm.m[12] = vec.x;
  47966. lm.m[13] = vec.y;
  47967. lm.m[14] = vec.z;
  47968. }
  47969. this.markAsDirty();
  47970. };
  47971. /**
  47972. * Set the absolute postion of the bone (world space).
  47973. * @param position The position to set the bone.
  47974. * @param mesh The mesh that this bone is attached to.
  47975. */
  47976. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  47977. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  47978. };
  47979. /**
  47980. * Set the scale of the bone on the x, y and z axes.
  47981. * @param x The scale of the bone on the x axis.
  47982. * @param x The scale of the bone on the y axis.
  47983. * @param z The scale of the bone on the z axis.
  47984. * @param scaleChildren Set this to true if children of the bone should be scaled.
  47985. */
  47986. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  47987. if (scaleChildren === void 0) { scaleChildren = false; }
  47988. if (this.animations[0] && !this.animations[0].isStopped()) {
  47989. if (!scaleChildren) {
  47990. this._negateScaleChildren.x = 1 / x;
  47991. this._negateScaleChildren.y = 1 / y;
  47992. this._negateScaleChildren.z = 1 / z;
  47993. }
  47994. this._syncScaleVector();
  47995. }
  47996. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  47997. };
  47998. /**
  47999. * Scale the bone on the x, y and z axes.
  48000. * @param x The amount to scale the bone on the x axis.
  48001. * @param x The amount to scale the bone on the y axis.
  48002. * @param z The amount to scale the bone on the z axis.
  48003. * @param scaleChildren Set this to true if children of the bone should be scaled.
  48004. */
  48005. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  48006. if (scaleChildren === void 0) { scaleChildren = false; }
  48007. var locMat = this.getLocalMatrix();
  48008. var origLocMat = Bone._tmpMats[0];
  48009. origLocMat.copyFrom(locMat);
  48010. var origLocMatInv = Bone._tmpMats[1];
  48011. origLocMatInv.copyFrom(origLocMat);
  48012. origLocMatInv.invert();
  48013. var scaleMat = Bone._tmpMats[2];
  48014. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  48015. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  48016. this._scaleVector.x *= x;
  48017. this._scaleVector.y *= y;
  48018. this._scaleVector.z *= z;
  48019. locMat.multiplyToRef(origLocMatInv, locMat);
  48020. locMat.multiplyToRef(scaleMat, locMat);
  48021. locMat.multiplyToRef(origLocMat, locMat);
  48022. var parent = this.getParent();
  48023. if (parent) {
  48024. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  48025. }
  48026. else {
  48027. this.getAbsoluteTransform().copyFrom(locMat);
  48028. }
  48029. var len = this.children.length;
  48030. scaleMat.invert();
  48031. for (var i = 0; i < len; i++) {
  48032. var child = this.children[i];
  48033. var cm = child.getLocalMatrix();
  48034. cm.multiplyToRef(scaleMat, cm);
  48035. var lm = child.getLocalMatrix();
  48036. lm.m[12] *= x;
  48037. lm.m[13] *= y;
  48038. lm.m[14] *= z;
  48039. }
  48040. this.computeAbsoluteTransforms();
  48041. if (scaleChildren) {
  48042. for (var i = 0; i < len; i++) {
  48043. this.children[i].scale(x, y, z, scaleChildren);
  48044. }
  48045. }
  48046. this.markAsDirty();
  48047. };
  48048. /**
  48049. * Set the yaw, pitch, and roll of the bone in local or world space.
  48050. * @param yaw The rotation of the bone on the y axis.
  48051. * @param pitch The rotation of the bone on the x axis.
  48052. * @param roll The rotation of the bone on the z axis.
  48053. * @param space The space that the axes of rotation are in.
  48054. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48055. */
  48056. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  48057. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48058. var rotMat = Bone._tmpMats[0];
  48059. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  48060. var rotMatInv = Bone._tmpMats[1];
  48061. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  48062. rotMatInv.multiplyToRef(rotMat, rotMat);
  48063. this._rotateWithMatrix(rotMat, space, mesh);
  48064. };
  48065. /**
  48066. * Rotate the bone on an axis in local or world space.
  48067. * @param axis The axis to rotate the bone on.
  48068. * @param amount The amount to rotate the bone.
  48069. * @param space The space that the axis is in.
  48070. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48071. */
  48072. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  48073. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48074. var rmat = Bone._tmpMats[0];
  48075. rmat.m[12] = 0;
  48076. rmat.m[13] = 0;
  48077. rmat.m[14] = 0;
  48078. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  48079. this._rotateWithMatrix(rmat, space, mesh);
  48080. };
  48081. /**
  48082. * Set the rotation of the bone to a particular axis angle in local or world space.
  48083. * @param axis The axis to rotate the bone on.
  48084. * @param angle The angle that the bone should be rotated to.
  48085. * @param space The space that the axis is in.
  48086. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48087. */
  48088. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  48089. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48090. var rotMat = Bone._tmpMats[0];
  48091. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  48092. var rotMatInv = Bone._tmpMats[1];
  48093. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  48094. rotMatInv.multiplyToRef(rotMat, rotMat);
  48095. this._rotateWithMatrix(rotMat, space, mesh);
  48096. };
  48097. /**
  48098. * Set the euler rotation of the bone in local of world space.
  48099. * @param rotation The euler rotation that the bone should be set to.
  48100. * @param space The space that the rotation is in.
  48101. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48102. */
  48103. Bone.prototype.setRotation = function (rotation, space, mesh) {
  48104. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48105. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  48106. };
  48107. /**
  48108. * Set the quaternion rotation of the bone in local of world space.
  48109. * @param quat The quaternion rotation that the bone should be set to.
  48110. * @param space The space that the rotation is in.
  48111. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48112. */
  48113. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  48114. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48115. var rotMatInv = Bone._tmpMats[0];
  48116. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  48117. var rotMat = Bone._tmpMats[1];
  48118. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  48119. rotMatInv.multiplyToRef(rotMat, rotMat);
  48120. this._rotateWithMatrix(rotMat, space, mesh);
  48121. };
  48122. /**
  48123. * Set the rotation matrix of the bone in local of world space.
  48124. * @param rotMat The rotation matrix that the bone should be set to.
  48125. * @param space The space that the rotation is in.
  48126. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48127. */
  48128. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  48129. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48130. var rotMatInv = Bone._tmpMats[0];
  48131. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  48132. var rotMat2 = Bone._tmpMats[1];
  48133. rotMat2.copyFrom(rotMat);
  48134. rotMatInv.multiplyToRef(rotMat, rotMat2);
  48135. this._rotateWithMatrix(rotMat2, space, mesh);
  48136. };
  48137. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  48138. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48139. var lmat = this.getLocalMatrix();
  48140. var lx = lmat.m[12];
  48141. var ly = lmat.m[13];
  48142. var lz = lmat.m[14];
  48143. var parent = this.getParent();
  48144. var parentScale = Bone._tmpMats[3];
  48145. var parentScaleInv = Bone._tmpMats[4];
  48146. if (parent) {
  48147. if (space == BABYLON.Space.WORLD) {
  48148. if (mesh) {
  48149. parentScale.copyFrom(mesh.getWorldMatrix());
  48150. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  48151. }
  48152. else {
  48153. parentScale.copyFrom(parent.getAbsoluteTransform());
  48154. }
  48155. }
  48156. else {
  48157. parentScale = parent._scaleMatrix;
  48158. }
  48159. parentScaleInv.copyFrom(parentScale);
  48160. parentScaleInv.invert();
  48161. lmat.multiplyToRef(parentScale, lmat);
  48162. lmat.multiplyToRef(rmat, lmat);
  48163. lmat.multiplyToRef(parentScaleInv, lmat);
  48164. }
  48165. else {
  48166. if (space == BABYLON.Space.WORLD && mesh) {
  48167. parentScale.copyFrom(mesh.getWorldMatrix());
  48168. parentScaleInv.copyFrom(parentScale);
  48169. parentScaleInv.invert();
  48170. lmat.multiplyToRef(parentScale, lmat);
  48171. lmat.multiplyToRef(rmat, lmat);
  48172. lmat.multiplyToRef(parentScaleInv, lmat);
  48173. }
  48174. else {
  48175. lmat.multiplyToRef(rmat, lmat);
  48176. }
  48177. }
  48178. lmat.m[12] = lx;
  48179. lmat.m[13] = ly;
  48180. lmat.m[14] = lz;
  48181. this.computeAbsoluteTransforms();
  48182. this.markAsDirty();
  48183. };
  48184. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  48185. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48186. if (space == BABYLON.Space.WORLD) {
  48187. var scaleMatrix = Bone._tmpMats[2];
  48188. scaleMatrix.copyFrom(this._scaleMatrix);
  48189. rotMatInv.copyFrom(this.getAbsoluteTransform());
  48190. if (mesh) {
  48191. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  48192. var meshScale = Bone._tmpMats[3];
  48193. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  48194. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  48195. }
  48196. rotMatInv.invert();
  48197. scaleMatrix.m[0] *= this._scalingDeterminant;
  48198. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  48199. }
  48200. else {
  48201. rotMatInv.copyFrom(this.getLocalMatrix());
  48202. rotMatInv.invert();
  48203. var scaleMatrix = Bone._tmpMats[2];
  48204. scaleMatrix.copyFrom(this._scaleMatrix);
  48205. if (this._parent) {
  48206. var pscaleMatrix = Bone._tmpMats[3];
  48207. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  48208. pscaleMatrix.invert();
  48209. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  48210. }
  48211. else {
  48212. scaleMatrix.m[0] *= this._scalingDeterminant;
  48213. }
  48214. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  48215. }
  48216. };
  48217. /**
  48218. * Get the scale of the bone
  48219. * @returns the scale of the bone
  48220. */
  48221. Bone.prototype.getScale = function () {
  48222. return this._scaleVector.clone();
  48223. };
  48224. /**
  48225. * Copy the scale of the bone to a vector3.
  48226. * @param result The vector3 to copy the scale to
  48227. */
  48228. Bone.prototype.getScaleToRef = function (result) {
  48229. result.copyFrom(this._scaleVector);
  48230. };
  48231. /**
  48232. * Get the position of the bone in local or world space.
  48233. * @param space The space that the returned position is in.
  48234. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48235. * @returns The position of the bone
  48236. */
  48237. Bone.prototype.getPosition = function (space, mesh) {
  48238. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48239. var pos = BABYLON.Vector3.Zero();
  48240. this.getPositionToRef(space, mesh, pos);
  48241. return pos;
  48242. };
  48243. /**
  48244. * Copy the position of the bone to a vector3 in local or world space.
  48245. * @param space The space that the returned position is in.
  48246. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48247. * @param result The vector3 to copy the position to.
  48248. */
  48249. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  48250. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48251. if (space == BABYLON.Space.LOCAL) {
  48252. var lm = this.getLocalMatrix();
  48253. result.x = lm.m[12];
  48254. result.y = lm.m[13];
  48255. result.z = lm.m[14];
  48256. }
  48257. else {
  48258. var wm;
  48259. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  48260. if (mesh) {
  48261. wm = mesh.getWorldMatrix();
  48262. }
  48263. this._skeleton.computeAbsoluteTransforms();
  48264. var tmat = Bone._tmpMats[0];
  48265. if (mesh) {
  48266. tmat.copyFrom(this.getAbsoluteTransform());
  48267. tmat.multiplyToRef(wm, tmat);
  48268. }
  48269. else {
  48270. tmat = this.getAbsoluteTransform();
  48271. }
  48272. result.x = tmat.m[12];
  48273. result.y = tmat.m[13];
  48274. result.z = tmat.m[14];
  48275. }
  48276. };
  48277. /**
  48278. * Get the absolute position of the bone (world space).
  48279. * @param mesh The mesh that this bone is attached to.
  48280. * @returns The absolute position of the bone
  48281. */
  48282. Bone.prototype.getAbsolutePosition = function (mesh) {
  48283. var pos = BABYLON.Vector3.Zero();
  48284. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  48285. return pos;
  48286. };
  48287. /**
  48288. * Copy the absolute position of the bone (world space) to the result param.
  48289. * @param mesh The mesh that this bone is attached to.
  48290. * @param result The vector3 to copy the absolute position to.
  48291. */
  48292. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  48293. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  48294. };
  48295. /**
  48296. * Compute the absolute transforms of this bone and its children.
  48297. */
  48298. Bone.prototype.computeAbsoluteTransforms = function () {
  48299. if (this._parent) {
  48300. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  48301. }
  48302. else {
  48303. this._absoluteTransform.copyFrom(this._localMatrix);
  48304. var poseMatrix = this._skeleton.getPoseMatrix();
  48305. if (poseMatrix) {
  48306. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  48307. }
  48308. }
  48309. var children = this.children;
  48310. var len = children.length;
  48311. for (var i = 0; i < len; i++) {
  48312. children[i].computeAbsoluteTransforms();
  48313. }
  48314. };
  48315. Bone.prototype._syncScaleVector = function () {
  48316. var lm = this.getLocalMatrix();
  48317. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  48318. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  48319. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  48320. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  48321. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  48322. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  48323. this._scaleVector.x = xs * Math.sqrt(xsq);
  48324. this._scaleVector.y = ys * Math.sqrt(ysq);
  48325. this._scaleVector.z = zs * Math.sqrt(zsq);
  48326. if (this._parent) {
  48327. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  48328. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  48329. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  48330. }
  48331. 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);
  48332. };
  48333. /**
  48334. * Get the world direction from an axis that is in the local space of the bone.
  48335. * @param localAxis The local direction that is used to compute the world direction.
  48336. * @param mesh The mesh that this bone is attached to.
  48337. * @returns The world direction
  48338. */
  48339. Bone.prototype.getDirection = function (localAxis, mesh) {
  48340. var result = BABYLON.Vector3.Zero();
  48341. this.getDirectionToRef(localAxis, mesh, result);
  48342. return result;
  48343. };
  48344. /**
  48345. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  48346. * @param localAxis The local direction that is used to compute the world direction.
  48347. * @param mesh The mesh that this bone is attached to.
  48348. * @param result The vector3 that the world direction will be copied to.
  48349. */
  48350. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  48351. var wm;
  48352. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  48353. if (mesh) {
  48354. wm = mesh.getWorldMatrix();
  48355. }
  48356. this._skeleton.computeAbsoluteTransforms();
  48357. var mat = Bone._tmpMats[0];
  48358. mat.copyFrom(this.getAbsoluteTransform());
  48359. if (mesh) {
  48360. mat.multiplyToRef(wm, mat);
  48361. }
  48362. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  48363. result.normalize();
  48364. };
  48365. /**
  48366. * Get the euler rotation of the bone in local or world space.
  48367. * @param space The space that the rotation should be in.
  48368. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48369. * @returns The euler rotation
  48370. */
  48371. Bone.prototype.getRotation = function (space, mesh) {
  48372. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48373. var result = BABYLON.Vector3.Zero();
  48374. this.getRotationToRef(space, mesh, result);
  48375. return result;
  48376. };
  48377. /**
  48378. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  48379. * @param space The space that the rotation should be in.
  48380. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48381. * @param result The vector3 that the rotation should be copied to.
  48382. */
  48383. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  48384. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48385. var quat = Bone._tmpQuat;
  48386. this.getRotationQuaternionToRef(space, mesh, quat);
  48387. quat.toEulerAnglesToRef(result);
  48388. };
  48389. /**
  48390. * Get the quaternion rotation of the bone in either local or world space.
  48391. * @param space The space that the rotation should be in.
  48392. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48393. * @returns The quaternion rotation
  48394. */
  48395. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  48396. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48397. var result = BABYLON.Quaternion.Identity();
  48398. this.getRotationQuaternionToRef(space, mesh, result);
  48399. return result;
  48400. };
  48401. /**
  48402. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  48403. * @param space The space that the rotation should be in.
  48404. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48405. * @param result The quaternion that the rotation should be copied to.
  48406. */
  48407. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  48408. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48409. if (space == BABYLON.Space.LOCAL) {
  48410. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  48411. }
  48412. else {
  48413. var mat = Bone._tmpMats[0];
  48414. var amat = this.getAbsoluteTransform();
  48415. if (mesh) {
  48416. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  48417. }
  48418. else {
  48419. mat.copyFrom(amat);
  48420. }
  48421. mat.m[0] *= this._scalingDeterminant;
  48422. mat.m[1] *= this._scalingDeterminant;
  48423. mat.m[2] *= this._scalingDeterminant;
  48424. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  48425. }
  48426. };
  48427. /**
  48428. * Get the rotation matrix of the bone in local or world space.
  48429. * @param space The space that the rotation should be in.
  48430. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48431. * @returns The rotation matrix
  48432. */
  48433. Bone.prototype.getRotationMatrix = function (space, mesh) {
  48434. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48435. var result = BABYLON.Matrix.Identity();
  48436. this.getRotationMatrixToRef(space, mesh, result);
  48437. return result;
  48438. };
  48439. /**
  48440. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  48441. * @param space The space that the rotation should be in.
  48442. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48443. * @param result The quaternion that the rotation should be copied to.
  48444. */
  48445. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  48446. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48447. if (space == BABYLON.Space.LOCAL) {
  48448. this.getLocalMatrix().getRotationMatrixToRef(result);
  48449. }
  48450. else {
  48451. var mat = Bone._tmpMats[0];
  48452. var amat = this.getAbsoluteTransform();
  48453. if (mesh) {
  48454. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  48455. }
  48456. else {
  48457. mat.copyFrom(amat);
  48458. }
  48459. mat.m[0] *= this._scalingDeterminant;
  48460. mat.m[1] *= this._scalingDeterminant;
  48461. mat.m[2] *= this._scalingDeterminant;
  48462. mat.getRotationMatrixToRef(result);
  48463. }
  48464. };
  48465. /**
  48466. * Get the world position of a point that is in the local space of the bone.
  48467. * @param position The local position
  48468. * @param mesh The mesh that this bone is attached to.
  48469. * @returns The world position
  48470. */
  48471. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  48472. var result = BABYLON.Vector3.Zero();
  48473. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  48474. return result;
  48475. };
  48476. /**
  48477. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  48478. * @param position The local position
  48479. * @param mesh The mesh that this bone is attached to.
  48480. * @param result The vector3 that the world position should be copied to.
  48481. */
  48482. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  48483. var wm;
  48484. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  48485. if (mesh) {
  48486. wm = mesh.getWorldMatrix();
  48487. }
  48488. this._skeleton.computeAbsoluteTransforms();
  48489. var tmat = Bone._tmpMats[0];
  48490. if (mesh) {
  48491. tmat.copyFrom(this.getAbsoluteTransform());
  48492. tmat.multiplyToRef(wm, tmat);
  48493. }
  48494. else {
  48495. tmat = this.getAbsoluteTransform();
  48496. }
  48497. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  48498. };
  48499. /**
  48500. * Get the local position of a point that is in world space.
  48501. * @param position The world position
  48502. * @param mesh The mesh that this bone is attached to.
  48503. * @returns The local position
  48504. */
  48505. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  48506. var result = BABYLON.Vector3.Zero();
  48507. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  48508. return result;
  48509. };
  48510. /**
  48511. * Get the local position of a point that is in world space and copy it to the result param.
  48512. * @param position The world position
  48513. * @param mesh The mesh that this bone is attached to.
  48514. * @param result The vector3 that the local position should be copied to.
  48515. */
  48516. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  48517. var wm;
  48518. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  48519. if (mesh) {
  48520. wm = mesh.getWorldMatrix();
  48521. }
  48522. this._skeleton.computeAbsoluteTransforms();
  48523. var tmat = Bone._tmpMats[0];
  48524. tmat.copyFrom(this.getAbsoluteTransform());
  48525. if (mesh) {
  48526. tmat.multiplyToRef(wm, tmat);
  48527. }
  48528. tmat.invert();
  48529. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  48530. };
  48531. return Bone;
  48532. }(BABYLON.Node));
  48533. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  48534. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  48535. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  48536. BABYLON.Bone = Bone;
  48537. })(BABYLON || (BABYLON = {}));
  48538. //# sourceMappingURL=babylon.bone.js.map
  48539. var BABYLON;
  48540. (function (BABYLON) {
  48541. var BoneIKController = (function () {
  48542. function BoneIKController(mesh, bone, options) {
  48543. this.targetPosition = BABYLON.Vector3.Zero();
  48544. this.poleTargetPosition = BABYLON.Vector3.Zero();
  48545. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  48546. this.poleAngle = 0;
  48547. this.slerpAmount = 1;
  48548. this._bone1Quat = BABYLON.Quaternion.Identity();
  48549. this._bone1Mat = BABYLON.Matrix.Identity();
  48550. this._bone2Ang = Math.PI;
  48551. this._maxAngle = Math.PI;
  48552. this._rightHandedSystem = false;
  48553. this._bendAxis = BABYLON.Vector3.Right();
  48554. this._slerping = false;
  48555. this._adjustRoll = 0;
  48556. this._bone2 = bone;
  48557. this._bone1 = bone.getParent();
  48558. this.mesh = mesh;
  48559. var bonePos = bone.getPosition();
  48560. if (bone.getAbsoluteTransform().determinant() > 0) {
  48561. this._rightHandedSystem = true;
  48562. this._bendAxis.x = 0;
  48563. this._bendAxis.y = 0;
  48564. this._bendAxis.z = -1;
  48565. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  48566. this._adjustRoll = Math.PI * .5;
  48567. this._bendAxis.z = 1;
  48568. }
  48569. }
  48570. if (this._bone1.length) {
  48571. var boneScale1 = this._bone1.getScale();
  48572. var boneScale2 = this._bone2.getScale();
  48573. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  48574. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  48575. }
  48576. else if (this._bone1.children[0]) {
  48577. mesh.computeWorldMatrix(true);
  48578. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  48579. var pos2 = this._bone2.getAbsolutePosition(mesh);
  48580. var pos3 = this._bone1.getAbsolutePosition(mesh);
  48581. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  48582. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  48583. }
  48584. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  48585. this.maxAngle = Math.PI;
  48586. if (options) {
  48587. if (options.targetMesh) {
  48588. this.targetMesh = options.targetMesh;
  48589. this.targetMesh.computeWorldMatrix(true);
  48590. }
  48591. if (options.poleTargetMesh) {
  48592. this.poleTargetMesh = options.poleTargetMesh;
  48593. this.poleTargetMesh.computeWorldMatrix(true);
  48594. }
  48595. else if (options.poleTargetBone) {
  48596. this.poleTargetBone = options.poleTargetBone;
  48597. }
  48598. else if (this._bone1.getParent()) {
  48599. this.poleTargetBone = this._bone1.getParent();
  48600. }
  48601. if (options.poleTargetLocalOffset) {
  48602. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  48603. }
  48604. if (options.poleAngle) {
  48605. this.poleAngle = options.poleAngle;
  48606. }
  48607. if (options.bendAxis) {
  48608. this._bendAxis.copyFrom(options.bendAxis);
  48609. }
  48610. if (options.maxAngle) {
  48611. this.maxAngle = options.maxAngle;
  48612. }
  48613. if (options.slerpAmount) {
  48614. this.slerpAmount = options.slerpAmount;
  48615. }
  48616. }
  48617. }
  48618. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  48619. get: function () {
  48620. return this._maxAngle;
  48621. },
  48622. set: function (value) {
  48623. this._setMaxAngle(value);
  48624. },
  48625. enumerable: true,
  48626. configurable: true
  48627. });
  48628. BoneIKController.prototype._setMaxAngle = function (ang) {
  48629. if (ang < 0) {
  48630. ang = 0;
  48631. }
  48632. if (ang > Math.PI || ang == undefined) {
  48633. ang = Math.PI;
  48634. }
  48635. this._maxAngle = ang;
  48636. var a = this._bone1Length;
  48637. var b = this._bone2Length;
  48638. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  48639. };
  48640. BoneIKController.prototype.update = function () {
  48641. var bone1 = this._bone1;
  48642. var target = this.targetPosition;
  48643. var poleTarget = this.poleTargetPosition;
  48644. var mat1 = BoneIKController._tmpMats[0];
  48645. var mat2 = BoneIKController._tmpMats[1];
  48646. if (this.targetMesh) {
  48647. target.copyFrom(this.targetMesh.getAbsolutePosition());
  48648. }
  48649. if (this.poleTargetBone) {
  48650. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  48651. }
  48652. else if (this.poleTargetMesh) {
  48653. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  48654. }
  48655. var bonePos = BoneIKController._tmpVecs[0];
  48656. var zaxis = BoneIKController._tmpVecs[1];
  48657. var xaxis = BoneIKController._tmpVecs[2];
  48658. var yaxis = BoneIKController._tmpVecs[3];
  48659. var upAxis = BoneIKController._tmpVecs[4];
  48660. var _tmpQuat = BoneIKController._tmpQuat;
  48661. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  48662. poleTarget.subtractToRef(bonePos, upAxis);
  48663. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  48664. upAxis.y = 1;
  48665. }
  48666. else {
  48667. upAxis.normalize();
  48668. }
  48669. target.subtractToRef(bonePos, yaxis);
  48670. yaxis.normalize();
  48671. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  48672. zaxis.normalize();
  48673. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  48674. xaxis.normalize();
  48675. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  48676. var a = this._bone1Length;
  48677. var b = this._bone2Length;
  48678. var c = BABYLON.Vector3.Distance(bonePos, target);
  48679. if (this._maxReach > 0) {
  48680. c = Math.min(this._maxReach, c);
  48681. }
  48682. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  48683. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  48684. if (acosa > 1) {
  48685. acosa = 1;
  48686. }
  48687. if (acosb > 1) {
  48688. acosb = 1;
  48689. }
  48690. if (acosa < -1) {
  48691. acosa = -1;
  48692. }
  48693. if (acosb < -1) {
  48694. acosb = -1;
  48695. }
  48696. var angA = Math.acos(acosa);
  48697. var angB = Math.acos(acosb);
  48698. var angC = -angA - angB;
  48699. if (this._rightHandedSystem) {
  48700. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  48701. mat2.multiplyToRef(mat1, mat1);
  48702. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  48703. mat2.multiplyToRef(mat1, mat1);
  48704. }
  48705. else {
  48706. var _tmpVec = BoneIKController._tmpVecs[5];
  48707. _tmpVec.copyFrom(this._bendAxis);
  48708. _tmpVec.x *= -1;
  48709. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  48710. mat2.multiplyToRef(mat1, mat1);
  48711. }
  48712. if (this.poleAngle) {
  48713. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  48714. mat1.multiplyToRef(mat2, mat1);
  48715. }
  48716. if (this.slerpAmount < 1) {
  48717. if (!this._slerping) {
  48718. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  48719. }
  48720. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  48721. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  48722. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  48723. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  48724. this._slerping = true;
  48725. }
  48726. else {
  48727. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  48728. this._bone1Mat.copyFrom(mat1);
  48729. this._slerping = false;
  48730. }
  48731. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  48732. this._bone2Ang = angC;
  48733. };
  48734. return BoneIKController;
  48735. }());
  48736. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  48737. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  48738. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  48739. BABYLON.BoneIKController = BoneIKController;
  48740. })(BABYLON || (BABYLON = {}));
  48741. //# sourceMappingURL=babylon.boneIKController.js.map
  48742. var BABYLON;
  48743. (function (BABYLON) {
  48744. var BoneLookController = (function () {
  48745. /**
  48746. * Create a BoneLookController
  48747. * @param mesh the mesh that the bone belongs to
  48748. * @param bone the bone that will be looking to the target
  48749. * @param target the target Vector3 to look at
  48750. * @param settings optional settings:
  48751. * - maxYaw: the maximum angle the bone will yaw to
  48752. * - minYaw: the minimum angle the bone will yaw to
  48753. * - maxPitch: the maximum angle the bone will pitch to
  48754. * - minPitch: the minimum angle the bone will yaw to
  48755. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  48756. * - upAxis: the up axis of the coordinate system
  48757. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  48758. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  48759. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  48760. * - adjustYaw: used to make an adjustment to the yaw of the bone
  48761. * - adjustPitch: used to make an adjustment to the pitch of the bone
  48762. * - adjustRoll: used to make an adjustment to the roll of the bone
  48763. **/
  48764. function BoneLookController(mesh, bone, target, options) {
  48765. /**
  48766. * The up axis of the coordinate system that is used when the bone is rotated.
  48767. */
  48768. this.upAxis = BABYLON.Vector3.Up();
  48769. /**
  48770. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  48771. */
  48772. this.upAxisSpace = BABYLON.Space.LOCAL;
  48773. /**
  48774. * Used to make an adjustment to the yaw of the bone.
  48775. */
  48776. this.adjustYaw = 0;
  48777. /**
  48778. * Used to make an adjustment to the pitch of the bone.
  48779. */
  48780. this.adjustPitch = 0;
  48781. /**
  48782. * Used to make an adjustment to the roll of the bone.
  48783. */
  48784. this.adjustRoll = 0;
  48785. /**
  48786. * 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).
  48787. */
  48788. this.slerpAmount = 1;
  48789. this._boneQuat = BABYLON.Quaternion.Identity();
  48790. this._slerping = false;
  48791. this._firstFrameSkipped = false;
  48792. this._fowardAxis = BABYLON.Vector3.Forward();
  48793. this.mesh = mesh;
  48794. this.bone = bone;
  48795. this.target = target;
  48796. if (options) {
  48797. if (options.adjustYaw) {
  48798. this.adjustYaw = options.adjustYaw;
  48799. }
  48800. if (options.adjustPitch) {
  48801. this.adjustPitch = options.adjustPitch;
  48802. }
  48803. if (options.adjustRoll) {
  48804. this.adjustRoll = options.adjustRoll;
  48805. }
  48806. if (options.maxYaw != null) {
  48807. this.maxYaw = options.maxYaw;
  48808. }
  48809. else {
  48810. this.maxYaw = Math.PI;
  48811. }
  48812. if (options.minYaw != null) {
  48813. this.minYaw = options.minYaw;
  48814. }
  48815. else {
  48816. this.minYaw = -Math.PI;
  48817. }
  48818. if (options.maxPitch != null) {
  48819. this.maxPitch = options.maxPitch;
  48820. }
  48821. else {
  48822. this.maxPitch = Math.PI;
  48823. }
  48824. if (options.minPitch != null) {
  48825. this.minPitch = options.minPitch;
  48826. }
  48827. else {
  48828. this.minPitch = -Math.PI;
  48829. }
  48830. if (options.slerpAmount != null) {
  48831. this.slerpAmount = options.slerpAmount;
  48832. }
  48833. if (options.upAxis != null) {
  48834. this.upAxis = options.upAxis;
  48835. }
  48836. if (options.upAxisSpace != null) {
  48837. this.upAxisSpace = options.upAxisSpace;
  48838. }
  48839. if (options.yawAxis != null || options.pitchAxis != null) {
  48840. var newYawAxis = BABYLON.Axis.Y;
  48841. var newPitchAxis = BABYLON.Axis.X;
  48842. if (options.yawAxis != null) {
  48843. newYawAxis = options.yawAxis.clone();
  48844. newYawAxis.normalize();
  48845. }
  48846. if (options.pitchAxis != null) {
  48847. newPitchAxis = options.pitchAxis.clone();
  48848. newPitchAxis.normalize();
  48849. }
  48850. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  48851. this._transformYawPitch = BABYLON.Matrix.Identity();
  48852. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  48853. this._transformYawPitchInv = this._transformYawPitch.clone();
  48854. this._transformYawPitch.invert();
  48855. }
  48856. }
  48857. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  48858. this.upAxisSpace = BABYLON.Space.LOCAL;
  48859. }
  48860. }
  48861. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  48862. /**
  48863. * Get/set the minimum yaw angle that the bone can look to.
  48864. */
  48865. get: function () {
  48866. return this._minYaw;
  48867. },
  48868. set: function (value) {
  48869. this._minYaw = value;
  48870. this._minYawSin = Math.sin(value);
  48871. this._minYawCos = Math.cos(value);
  48872. if (this._maxYaw != null) {
  48873. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  48874. this._yawRange = this._maxYaw - this._minYaw;
  48875. }
  48876. },
  48877. enumerable: true,
  48878. configurable: true
  48879. });
  48880. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  48881. /**
  48882. * Get/set the maximum yaw angle that the bone can look to.
  48883. */
  48884. get: function () {
  48885. return this._maxYaw;
  48886. },
  48887. set: function (value) {
  48888. this._maxYaw = value;
  48889. this._maxYawSin = Math.sin(value);
  48890. this._maxYawCos = Math.cos(value);
  48891. if (this._minYaw != null) {
  48892. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  48893. this._yawRange = this._maxYaw - this._minYaw;
  48894. }
  48895. },
  48896. enumerable: true,
  48897. configurable: true
  48898. });
  48899. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  48900. /**
  48901. * Get/set the minimum pitch angle that the bone can look to.
  48902. */
  48903. get: function () {
  48904. return this._minPitch;
  48905. },
  48906. set: function (value) {
  48907. this._minPitch = value;
  48908. this._minPitchTan = Math.tan(value);
  48909. },
  48910. enumerable: true,
  48911. configurable: true
  48912. });
  48913. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  48914. /**
  48915. * Get/set the maximum pitch angle that the bone can look to.
  48916. */
  48917. get: function () {
  48918. return this._maxPitch;
  48919. },
  48920. set: function (value) {
  48921. this._maxPitch = value;
  48922. this._maxPitchTan = Math.tan(value);
  48923. },
  48924. enumerable: true,
  48925. configurable: true
  48926. });
  48927. /**
  48928. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  48929. */
  48930. BoneLookController.prototype.update = function () {
  48931. //skip the first frame when slerping so that the mesh rotation is correct
  48932. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  48933. this._firstFrameSkipped = true;
  48934. return;
  48935. }
  48936. var bone = this.bone;
  48937. var bonePos = BoneLookController._tmpVecs[0];
  48938. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  48939. var target = this.target;
  48940. var _tmpMat1 = BoneLookController._tmpMats[0];
  48941. var _tmpMat2 = BoneLookController._tmpMats[1];
  48942. var mesh = this.mesh;
  48943. var parentBone = bone.getParent();
  48944. var upAxis = BoneLookController._tmpVecs[1];
  48945. upAxis.copyFrom(this.upAxis);
  48946. if (this.upAxisSpace == BABYLON.Space.BONE) {
  48947. if (this._transformYawPitch) {
  48948. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  48949. }
  48950. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  48951. }
  48952. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  48953. mesh.getDirectionToRef(upAxis, upAxis);
  48954. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  48955. upAxis.normalize();
  48956. }
  48957. }
  48958. var checkYaw = false;
  48959. var checkPitch = false;
  48960. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  48961. checkYaw = true;
  48962. }
  48963. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  48964. checkPitch = true;
  48965. }
  48966. if (checkYaw || checkPitch) {
  48967. var spaceMat = BoneLookController._tmpMats[2];
  48968. var spaceMatInv = BoneLookController._tmpMats[3];
  48969. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  48970. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  48971. }
  48972. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  48973. spaceMat.copyFrom(mesh.getWorldMatrix());
  48974. }
  48975. else {
  48976. var forwardAxis = BoneLookController._tmpVecs[2];
  48977. forwardAxis.copyFrom(this._fowardAxis);
  48978. if (this._transformYawPitch) {
  48979. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  48980. }
  48981. if (parentBone) {
  48982. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  48983. }
  48984. else {
  48985. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  48986. }
  48987. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  48988. rightAxis.normalize();
  48989. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  48990. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  48991. }
  48992. spaceMat.invertToRef(spaceMatInv);
  48993. var xzlen;
  48994. if (checkPitch) {
  48995. var localTarget = BoneLookController._tmpVecs[3];
  48996. target.subtractToRef(bonePos, localTarget);
  48997. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  48998. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  48999. var pitch = Math.atan2(localTarget.y, xzlen);
  49000. var newPitch = pitch;
  49001. if (pitch > this._maxPitch) {
  49002. localTarget.y = this._maxPitchTan * xzlen;
  49003. newPitch = this._maxPitch;
  49004. }
  49005. else if (pitch < this._minPitch) {
  49006. localTarget.y = this._minPitchTan * xzlen;
  49007. newPitch = this._minPitch;
  49008. }
  49009. if (pitch != newPitch) {
  49010. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  49011. localTarget.addInPlace(bonePos);
  49012. target = localTarget;
  49013. }
  49014. }
  49015. if (checkYaw) {
  49016. var localTarget = BoneLookController._tmpVecs[4];
  49017. target.subtractToRef(bonePos, localTarget);
  49018. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  49019. var yaw = Math.atan2(localTarget.x, localTarget.z);
  49020. var newYaw = yaw;
  49021. if (yaw > this._maxYaw || yaw < this._minYaw) {
  49022. if (xzlen == null) {
  49023. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  49024. }
  49025. if (this._yawRange > Math.PI) {
  49026. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  49027. localTarget.z = this._maxYawCos * xzlen;
  49028. localTarget.x = this._maxYawSin * xzlen;
  49029. newYaw = this._maxYaw;
  49030. }
  49031. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  49032. localTarget.z = this._minYawCos * xzlen;
  49033. localTarget.x = this._minYawSin * xzlen;
  49034. newYaw = this._minYaw;
  49035. }
  49036. }
  49037. else {
  49038. if (yaw > this._maxYaw) {
  49039. localTarget.z = this._maxYawCos * xzlen;
  49040. localTarget.x = this._maxYawSin * xzlen;
  49041. newYaw = this._maxYaw;
  49042. }
  49043. else if (yaw < this._minYaw) {
  49044. localTarget.z = this._minYawCos * xzlen;
  49045. localTarget.x = this._minYawSin * xzlen;
  49046. newYaw = this._minYaw;
  49047. }
  49048. }
  49049. }
  49050. if (this._slerping && this._yawRange > Math.PI) {
  49051. //are we going to be crossing into the min/max region?
  49052. var boneFwd = BoneLookController._tmpVecs[8];
  49053. boneFwd.copyFrom(BABYLON.Axis.Z);
  49054. if (this._transformYawPitch) {
  49055. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  49056. }
  49057. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  49058. this._boneQuat.toRotationMatrix(boneRotMat);
  49059. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  49060. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  49061. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  49062. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  49063. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  49064. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  49065. if (angBtwTar > angBtwMidYaw) {
  49066. if (xzlen == null) {
  49067. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  49068. }
  49069. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  49070. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  49071. if (angBtwMin < angBtwMax) {
  49072. newYaw = boneYaw + Math.PI * .75;
  49073. localTarget.z = Math.cos(newYaw) * xzlen;
  49074. localTarget.x = Math.sin(newYaw) * xzlen;
  49075. }
  49076. else {
  49077. newYaw = boneYaw - Math.PI * .75;
  49078. localTarget.z = Math.cos(newYaw) * xzlen;
  49079. localTarget.x = Math.sin(newYaw) * xzlen;
  49080. }
  49081. }
  49082. }
  49083. if (yaw != newYaw) {
  49084. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  49085. localTarget.addInPlace(bonePos);
  49086. target = localTarget;
  49087. }
  49088. }
  49089. }
  49090. var zaxis = BoneLookController._tmpVecs[5];
  49091. var xaxis = BoneLookController._tmpVecs[6];
  49092. var yaxis = BoneLookController._tmpVecs[7];
  49093. var _tmpQuat = BoneLookController._tmpQuat;
  49094. target.subtractToRef(bonePos, zaxis);
  49095. zaxis.normalize();
  49096. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  49097. xaxis.normalize();
  49098. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  49099. yaxis.normalize();
  49100. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  49101. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  49102. return;
  49103. }
  49104. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  49105. return;
  49106. }
  49107. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  49108. return;
  49109. }
  49110. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  49111. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  49112. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  49113. }
  49114. if (this.slerpAmount < 1) {
  49115. if (!this._slerping) {
  49116. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  49117. }
  49118. if (this._transformYawPitch) {
  49119. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  49120. }
  49121. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  49122. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  49123. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  49124. this._slerping = true;
  49125. }
  49126. else {
  49127. if (this._transformYawPitch) {
  49128. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  49129. }
  49130. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  49131. this._slerping = false;
  49132. }
  49133. };
  49134. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  49135. var angDiff = ang2 - ang1;
  49136. angDiff %= Math.PI * 2;
  49137. if (angDiff > Math.PI) {
  49138. angDiff -= Math.PI * 2;
  49139. }
  49140. else if (angDiff < -Math.PI) {
  49141. angDiff += Math.PI * 2;
  49142. }
  49143. return angDiff;
  49144. };
  49145. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  49146. ang1 %= (2 * Math.PI);
  49147. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  49148. ang2 %= (2 * Math.PI);
  49149. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  49150. var ab = 0;
  49151. if (ang1 < ang2) {
  49152. ab = ang2 - ang1;
  49153. }
  49154. else {
  49155. ab = ang1 - ang2;
  49156. }
  49157. if (ab > Math.PI) {
  49158. ab = Math.PI * 2 - ab;
  49159. }
  49160. return ab;
  49161. };
  49162. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  49163. ang %= (2 * Math.PI);
  49164. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  49165. ang1 %= (2 * Math.PI);
  49166. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  49167. ang2 %= (2 * Math.PI);
  49168. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  49169. if (ang1 < ang2) {
  49170. if (ang > ang1 && ang < ang2) {
  49171. return true;
  49172. }
  49173. }
  49174. else {
  49175. if (ang > ang2 && ang < ang1) {
  49176. return true;
  49177. }
  49178. }
  49179. return false;
  49180. };
  49181. return BoneLookController;
  49182. }());
  49183. 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()];
  49184. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  49185. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  49186. BABYLON.BoneLookController = BoneLookController;
  49187. })(BABYLON || (BABYLON = {}));
  49188. //# sourceMappingURL=babylon.boneLookController.js.map
  49189. var BABYLON;
  49190. (function (BABYLON) {
  49191. var Skeleton = (function () {
  49192. function Skeleton(name, id, scene) {
  49193. this.name = name;
  49194. this.id = id;
  49195. this.bones = new Array();
  49196. this.needInitialSkinMatrix = false;
  49197. this._isDirty = true;
  49198. this._meshesWithPoseMatrix = new Array();
  49199. this._identity = BABYLON.Matrix.Identity();
  49200. this._ranges = {};
  49201. this._lastAbsoluteTransformsUpdateId = -1;
  49202. // Events
  49203. /**
  49204. * An event triggered before computing the skeleton's matrices
  49205. * @type {BABYLON.Observable}
  49206. */
  49207. this.onBeforeComputeObservable = new BABYLON.Observable();
  49208. this.bones = [];
  49209. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49210. scene.skeletons.push(this);
  49211. //make sure it will recalculate the matrix next time prepare is called.
  49212. this._isDirty = true;
  49213. }
  49214. // Members
  49215. Skeleton.prototype.getTransformMatrices = function (mesh) {
  49216. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  49217. return mesh._bonesTransformMatrices;
  49218. }
  49219. if (!this._transformMatrices) {
  49220. this.prepare();
  49221. }
  49222. return this._transformMatrices;
  49223. };
  49224. Skeleton.prototype.getScene = function () {
  49225. return this._scene;
  49226. };
  49227. // Methods
  49228. /**
  49229. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  49230. */
  49231. Skeleton.prototype.toString = function (fullDetails) {
  49232. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  49233. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49234. if (fullDetails) {
  49235. ret += ", Ranges: {";
  49236. var first = true;
  49237. for (var name_1 in this._ranges) {
  49238. if (first) {
  49239. ret += ", ";
  49240. first = false;
  49241. }
  49242. ret += name_1;
  49243. }
  49244. ret += "}";
  49245. }
  49246. return ret;
  49247. };
  49248. /**
  49249. * Get bone's index searching by name
  49250. * @param {string} name is bone's name to search for
  49251. * @return {number} Indice of the bone. Returns -1 if not found
  49252. */
  49253. Skeleton.prototype.getBoneIndexByName = function (name) {
  49254. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  49255. if (this.bones[boneIndex].name === name) {
  49256. return boneIndex;
  49257. }
  49258. }
  49259. return -1;
  49260. };
  49261. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  49262. // check name not already in use
  49263. if (!this._ranges[name]) {
  49264. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  49265. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  49266. if (this.bones[i].animations[0]) {
  49267. this.bones[i].animations[0].createRange(name, from, to);
  49268. }
  49269. }
  49270. }
  49271. };
  49272. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  49273. if (deleteFrames === void 0) { deleteFrames = true; }
  49274. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  49275. if (this.bones[i].animations[0]) {
  49276. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  49277. }
  49278. }
  49279. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  49280. };
  49281. Skeleton.prototype.getAnimationRange = function (name) {
  49282. return this._ranges[name];
  49283. };
  49284. /**
  49285. * Returns as an Array, all AnimationRanges defined on this skeleton
  49286. */
  49287. Skeleton.prototype.getAnimationRanges = function () {
  49288. var animationRanges = [];
  49289. var name;
  49290. var i = 0;
  49291. for (name in this._ranges) {
  49292. animationRanges[i] = this._ranges[name];
  49293. i++;
  49294. }
  49295. return animationRanges;
  49296. };
  49297. /**
  49298. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  49299. */
  49300. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  49301. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  49302. if (this._ranges[name] || !source.getAnimationRange(name)) {
  49303. return false;
  49304. }
  49305. var ret = true;
  49306. var frameOffset = this._getHighestAnimationFrame() + 1;
  49307. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  49308. var boneDict = {};
  49309. var sourceBones = source.bones;
  49310. var nBones;
  49311. var i;
  49312. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  49313. boneDict[sourceBones[i].name] = sourceBones[i];
  49314. }
  49315. if (this.bones.length !== sourceBones.length) {
  49316. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  49317. ret = false;
  49318. }
  49319. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  49320. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  49321. var boneName = this.bones[i].name;
  49322. var sourceBone = boneDict[boneName];
  49323. if (sourceBone) {
  49324. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  49325. }
  49326. else {
  49327. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  49328. ret = false;
  49329. }
  49330. }
  49331. // do not call createAnimationRange(), since it also is done to bones, which was already done
  49332. var range = source.getAnimationRange(name);
  49333. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  49334. return ret;
  49335. };
  49336. Skeleton.prototype.returnToRest = function () {
  49337. for (var index = 0; index < this.bones.length; index++) {
  49338. this.bones[index].returnToRest();
  49339. }
  49340. };
  49341. Skeleton.prototype._getHighestAnimationFrame = function () {
  49342. var ret = 0;
  49343. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  49344. if (this.bones[i].animations[0]) {
  49345. var highest = this.bones[i].animations[0].getHighestFrame();
  49346. if (ret < highest) {
  49347. ret = highest;
  49348. }
  49349. }
  49350. }
  49351. return ret;
  49352. };
  49353. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  49354. var range = this.getAnimationRange(name);
  49355. if (!range) {
  49356. return null;
  49357. }
  49358. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  49359. };
  49360. Skeleton.prototype._markAsDirty = function () {
  49361. this._isDirty = true;
  49362. };
  49363. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  49364. this._meshesWithPoseMatrix.push(mesh);
  49365. };
  49366. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  49367. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  49368. if (index > -1) {
  49369. this._meshesWithPoseMatrix.splice(index, 1);
  49370. }
  49371. };
  49372. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  49373. this.onBeforeComputeObservable.notifyObservers(this);
  49374. for (var index = 0; index < this.bones.length; index++) {
  49375. var bone = this.bones[index];
  49376. var parentBone = bone.getParent();
  49377. if (parentBone) {
  49378. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  49379. }
  49380. else {
  49381. if (initialSkinMatrix) {
  49382. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  49383. }
  49384. else {
  49385. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  49386. }
  49387. }
  49388. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  49389. }
  49390. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  49391. };
  49392. Skeleton.prototype.prepare = function () {
  49393. if (!this._isDirty) {
  49394. return;
  49395. }
  49396. if (this.needInitialSkinMatrix) {
  49397. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  49398. var mesh = this._meshesWithPoseMatrix[index];
  49399. var poseMatrix = mesh.getPoseMatrix();
  49400. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  49401. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  49402. }
  49403. if (this._synchronizedWithMesh !== mesh) {
  49404. this._synchronizedWithMesh = mesh;
  49405. // Prepare bones
  49406. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  49407. var bone = this.bones[boneIndex];
  49408. if (!bone.getParent()) {
  49409. var matrix = bone.getBaseMatrix();
  49410. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  49411. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  49412. }
  49413. }
  49414. }
  49415. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  49416. }
  49417. }
  49418. else {
  49419. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  49420. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  49421. }
  49422. this._computeTransformMatrices(this._transformMatrices, null);
  49423. }
  49424. this._isDirty = false;
  49425. this._scene._activeBones.addCount(this.bones.length, false);
  49426. };
  49427. Skeleton.prototype.getAnimatables = function () {
  49428. if (!this._animatables || this._animatables.length !== this.bones.length) {
  49429. this._animatables = [];
  49430. for (var index = 0; index < this.bones.length; index++) {
  49431. this._animatables.push(this.bones[index]);
  49432. }
  49433. }
  49434. return this._animatables;
  49435. };
  49436. Skeleton.prototype.clone = function (name, id) {
  49437. var result = new Skeleton(name, id || name, this._scene);
  49438. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  49439. for (var index = 0; index < this.bones.length; index++) {
  49440. var source = this.bones[index];
  49441. var parentBone = null;
  49442. if (source.getParent()) {
  49443. var parentIndex = this.bones.indexOf(source.getParent());
  49444. parentBone = result.bones[parentIndex];
  49445. }
  49446. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  49447. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  49448. }
  49449. if (this._ranges) {
  49450. result._ranges = {};
  49451. for (var rangeName in this._ranges) {
  49452. result._ranges[rangeName] = this._ranges[rangeName].clone();
  49453. }
  49454. }
  49455. this._isDirty = true;
  49456. return result;
  49457. };
  49458. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  49459. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  49460. this.bones.forEach(function (bone) {
  49461. bone.animations.forEach(function (animation) {
  49462. animation.enableBlending = true;
  49463. animation.blendingSpeed = blendingSpeed;
  49464. });
  49465. });
  49466. };
  49467. Skeleton.prototype.dispose = function () {
  49468. this._meshesWithPoseMatrix = [];
  49469. // Animations
  49470. this.getScene().stopAnimation(this);
  49471. // Remove from scene
  49472. this.getScene().removeSkeleton(this);
  49473. };
  49474. Skeleton.prototype.serialize = function () {
  49475. var serializationObject = {};
  49476. serializationObject.name = this.name;
  49477. serializationObject.id = this.id;
  49478. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  49479. serializationObject.bones = [];
  49480. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  49481. for (var index = 0; index < this.bones.length; index++) {
  49482. var bone = this.bones[index];
  49483. var serializedBone = {
  49484. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  49485. name: bone.name,
  49486. matrix: bone.getBaseMatrix().toArray(),
  49487. rest: bone.getRestPose().toArray()
  49488. };
  49489. serializationObject.bones.push(serializedBone);
  49490. if (bone.length) {
  49491. serializedBone.length = bone.length;
  49492. }
  49493. if (bone.animations && bone.animations.length > 0) {
  49494. serializedBone.animation = bone.animations[0].serialize();
  49495. }
  49496. serializationObject.ranges = [];
  49497. for (var name in this._ranges) {
  49498. var range = {};
  49499. range.name = name;
  49500. range.from = this._ranges[name].from;
  49501. range.to = this._ranges[name].to;
  49502. serializationObject.ranges.push(range);
  49503. }
  49504. }
  49505. return serializationObject;
  49506. };
  49507. Skeleton.Parse = function (parsedSkeleton, scene) {
  49508. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  49509. if (parsedSkeleton.dimensionsAtRest) {
  49510. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  49511. }
  49512. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  49513. var index;
  49514. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  49515. var parsedBone = parsedSkeleton.bones[index];
  49516. var parentBone = null;
  49517. if (parsedBone.parentBoneIndex > -1) {
  49518. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  49519. }
  49520. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  49521. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  49522. if (parsedBone.length) {
  49523. bone.length = parsedBone.length;
  49524. }
  49525. if (parsedBone.animation) {
  49526. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  49527. }
  49528. }
  49529. // placed after bones, so createAnimationRange can cascade down
  49530. if (parsedSkeleton.ranges) {
  49531. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  49532. var data = parsedSkeleton.ranges[index];
  49533. skeleton.createAnimationRange(data.name, data.from, data.to);
  49534. }
  49535. }
  49536. return skeleton;
  49537. };
  49538. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  49539. if (forceUpdate === void 0) { forceUpdate = false; }
  49540. var renderId = this._scene.getRenderId();
  49541. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  49542. this.bones[0].computeAbsoluteTransforms();
  49543. this._lastAbsoluteTransformsUpdateId = renderId;
  49544. }
  49545. };
  49546. Skeleton.prototype.getPoseMatrix = function () {
  49547. var poseMatrix;
  49548. if (this._meshesWithPoseMatrix.length > 0) {
  49549. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  49550. }
  49551. return poseMatrix;
  49552. };
  49553. return Skeleton;
  49554. }());
  49555. BABYLON.Skeleton = Skeleton;
  49556. })(BABYLON || (BABYLON = {}));
  49557. //# sourceMappingURL=babylon.skeleton.js.map
  49558. var BABYLON;
  49559. (function (BABYLON) {
  49560. var Internals;
  49561. (function (Internals) {
  49562. var FileFaceOrientation = (function () {
  49563. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  49564. this.name = name;
  49565. this.worldAxisForNormal = worldAxisForNormal;
  49566. this.worldAxisForFileX = worldAxisForFileX;
  49567. this.worldAxisForFileY = worldAxisForFileY;
  49568. }
  49569. return FileFaceOrientation;
  49570. }());
  49571. ;
  49572. /**
  49573. * Helper class dealing with the extraction of spherical polynomial dataArray
  49574. * from a cube map.
  49575. */
  49576. var CubeMapToSphericalPolynomialTools = (function () {
  49577. function CubeMapToSphericalPolynomialTools() {
  49578. }
  49579. /**
  49580. * Converts a cubemap to the according Spherical Polynomial data.
  49581. * This extracts the first 3 orders only as they are the only one used in the lighting.
  49582. *
  49583. * @param cubeInfo The Cube map to extract the information from.
  49584. * @return The Spherical Polynomial data.
  49585. */
  49586. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  49587. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  49588. var totalSolidAngle = 0.0;
  49589. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  49590. var du = 2.0 / cubeInfo.size;
  49591. var dv = du;
  49592. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  49593. var minUV = du * 0.5 - 1.0;
  49594. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  49595. var fileFace = this.FileFaces[faceIndex];
  49596. var dataArray = cubeInfo[fileFace.name];
  49597. var v = minUV;
  49598. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  49599. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  49600. // Because SP is still linear, so summation is fine in that basis.
  49601. for (var y = 0; y < cubeInfo.size; y++) {
  49602. var u = minUV;
  49603. for (var x = 0; x < cubeInfo.size; x++) {
  49604. // World direction (not normalised)
  49605. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  49606. worldDirection.normalize();
  49607. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  49608. if (1) {
  49609. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  49610. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  49611. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  49612. var color = new BABYLON.Color3(r, g, b);
  49613. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  49614. }
  49615. else {
  49616. if (faceIndex == 0) {
  49617. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49618. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49619. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49620. }
  49621. else if (faceIndex == 1) {
  49622. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49623. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49624. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49625. }
  49626. else if (faceIndex == 2) {
  49627. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49628. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49629. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49630. }
  49631. else if (faceIndex == 3) {
  49632. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49633. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49634. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49635. }
  49636. else if (faceIndex == 4) {
  49637. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49638. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49639. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49640. }
  49641. else if (faceIndex == 5) {
  49642. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49643. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49644. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49645. }
  49646. 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]);
  49647. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  49648. }
  49649. totalSolidAngle += deltaSolidAngle;
  49650. u += du;
  49651. }
  49652. v += dv;
  49653. }
  49654. }
  49655. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  49656. var correction = correctSolidAngle / totalSolidAngle;
  49657. sphericalHarmonics.scale(correction);
  49658. // Additionally scale by pi -- audit needed
  49659. sphericalHarmonics.scale(1.0 / Math.PI);
  49660. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  49661. };
  49662. return CubeMapToSphericalPolynomialTools;
  49663. }());
  49664. CubeMapToSphericalPolynomialTools.FileFaces = [
  49665. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  49666. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  49667. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  49668. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  49669. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  49670. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  49671. ];
  49672. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  49673. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49674. })(BABYLON || (BABYLON = {}));
  49675. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  49676. var BABYLON;
  49677. (function (BABYLON) {
  49678. var Internals;
  49679. (function (Internals) {
  49680. /**
  49681. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  49682. */
  49683. var PanoramaToCubeMapTools = (function () {
  49684. function PanoramaToCubeMapTools() {
  49685. }
  49686. /**
  49687. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  49688. *
  49689. * @param float32Array The source data.
  49690. * @param inputWidth The width of the input panorama.
  49691. * @param inputhHeight The height of the input panorama.
  49692. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  49693. * @return The cubemap data
  49694. */
  49695. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  49696. if (!float32Array) {
  49697. throw "ConvertPanoramaToCubemap: input cannot be null";
  49698. }
  49699. if (float32Array.length != inputWidth * inputHeight * 3) {
  49700. throw "ConvertPanoramaToCubemap: input size is wrong";
  49701. }
  49702. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  49703. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  49704. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  49705. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  49706. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  49707. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  49708. return {
  49709. front: textureFront,
  49710. back: textureBack,
  49711. left: textureLeft,
  49712. right: textureRight,
  49713. up: textureUp,
  49714. down: textureDown,
  49715. size: size
  49716. };
  49717. };
  49718. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  49719. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  49720. var textureArray = new Float32Array(buffer);
  49721. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  49722. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  49723. var dy = 1 / texSize;
  49724. var fy = 0;
  49725. for (var y = 0; y < texSize; y++) {
  49726. var xv1 = faceData[0];
  49727. var xv2 = faceData[2];
  49728. for (var x = 0; x < texSize; x++) {
  49729. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  49730. v.normalize();
  49731. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  49732. // 3 channels per pixels
  49733. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  49734. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  49735. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  49736. xv1 = xv1.add(rotDX1);
  49737. xv2 = xv2.add(rotDX2);
  49738. }
  49739. fy += dy;
  49740. }
  49741. return textureArray;
  49742. };
  49743. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  49744. var theta = Math.atan2(vDir.z, vDir.x);
  49745. var phi = Math.acos(vDir.y);
  49746. while (theta < -Math.PI)
  49747. theta += 2 * Math.PI;
  49748. while (theta > Math.PI)
  49749. theta -= 2 * Math.PI;
  49750. var dx = theta / Math.PI;
  49751. var dy = phi / Math.PI;
  49752. // recenter.
  49753. dx = dx * 0.5 + 0.5;
  49754. var px = Math.round(dx * inputWidth);
  49755. if (px < 0)
  49756. px = 0;
  49757. else if (px >= inputWidth)
  49758. px = inputWidth - 1;
  49759. var py = Math.round(dy * inputHeight);
  49760. if (py < 0)
  49761. py = 0;
  49762. else if (py >= inputHeight)
  49763. py = inputHeight - 1;
  49764. var inputY = (inputHeight - py - 1);
  49765. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  49766. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  49767. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  49768. return {
  49769. r: r,
  49770. g: g,
  49771. b: b
  49772. };
  49773. };
  49774. return PanoramaToCubeMapTools;
  49775. }());
  49776. PanoramaToCubeMapTools.FACE_FRONT = [
  49777. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  49778. new BABYLON.Vector3(1.0, -1.0, -1.0),
  49779. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  49780. new BABYLON.Vector3(1.0, 1.0, -1.0)
  49781. ];
  49782. PanoramaToCubeMapTools.FACE_BACK = [
  49783. new BABYLON.Vector3(1.0, -1.0, 1.0),
  49784. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  49785. new BABYLON.Vector3(1.0, 1.0, 1.0),
  49786. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  49787. ];
  49788. PanoramaToCubeMapTools.FACE_RIGHT = [
  49789. new BABYLON.Vector3(1.0, -1.0, -1.0),
  49790. new BABYLON.Vector3(1.0, -1.0, 1.0),
  49791. new BABYLON.Vector3(1.0, 1.0, -1.0),
  49792. new BABYLON.Vector3(1.0, 1.0, 1.0)
  49793. ];
  49794. PanoramaToCubeMapTools.FACE_LEFT = [
  49795. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  49796. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  49797. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  49798. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  49799. ];
  49800. PanoramaToCubeMapTools.FACE_DOWN = [
  49801. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  49802. new BABYLON.Vector3(1.0, 1.0, -1.0),
  49803. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  49804. new BABYLON.Vector3(1.0, 1.0, 1.0)
  49805. ];
  49806. PanoramaToCubeMapTools.FACE_UP = [
  49807. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  49808. new BABYLON.Vector3(1.0, -1.0, 1.0),
  49809. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  49810. new BABYLON.Vector3(1.0, -1.0, -1.0)
  49811. ];
  49812. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  49813. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49814. })(BABYLON || (BABYLON = {}));
  49815. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  49816. var BABYLON;
  49817. (function (BABYLON) {
  49818. var Internals;
  49819. (function (Internals) {
  49820. ;
  49821. /**
  49822. * This groups tools to convert HDR texture to native colors array.
  49823. */
  49824. var HDRTools = (function () {
  49825. function HDRTools() {
  49826. }
  49827. HDRTools.Ldexp = function (mantissa, exponent) {
  49828. if (exponent > 1023) {
  49829. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  49830. }
  49831. if (exponent < -1074) {
  49832. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  49833. }
  49834. return mantissa * Math.pow(2, exponent);
  49835. };
  49836. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  49837. if (exponent > 0) {
  49838. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  49839. float32array[index + 0] = red * exponent;
  49840. float32array[index + 1] = green * exponent;
  49841. float32array[index + 2] = blue * exponent;
  49842. }
  49843. else {
  49844. float32array[index + 0] = 0;
  49845. float32array[index + 1] = 0;
  49846. float32array[index + 2] = 0;
  49847. }
  49848. };
  49849. HDRTools.readStringLine = function (uint8array, startIndex) {
  49850. var line = "";
  49851. var character = "";
  49852. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  49853. character = String.fromCharCode(uint8array[i]);
  49854. if (character == "\n") {
  49855. break;
  49856. }
  49857. line += character;
  49858. }
  49859. return line;
  49860. };
  49861. /**
  49862. * Reads header information from an RGBE texture stored in a native array.
  49863. * More information on this format are available here:
  49864. * https://en.wikipedia.org/wiki/RGBE_image_format
  49865. *
  49866. * @param uint8array The binary file stored in native array.
  49867. * @return The header information.
  49868. */
  49869. HDRTools.RGBE_ReadHeader = function (uint8array) {
  49870. var height = 0;
  49871. var width = 0;
  49872. var line = this.readStringLine(uint8array, 0);
  49873. if (line[0] != '#' || line[1] != '?') {
  49874. throw "Bad HDR Format.";
  49875. }
  49876. var endOfHeader = false;
  49877. var findFormat = false;
  49878. var lineIndex = 0;
  49879. do {
  49880. lineIndex += (line.length + 1);
  49881. line = this.readStringLine(uint8array, lineIndex);
  49882. if (line == "FORMAT=32-bit_rle_rgbe") {
  49883. findFormat = true;
  49884. }
  49885. else if (line.length == 0) {
  49886. endOfHeader = true;
  49887. }
  49888. } while (!endOfHeader);
  49889. if (!findFormat) {
  49890. throw "HDR Bad header format, unsupported FORMAT";
  49891. }
  49892. lineIndex += (line.length + 1);
  49893. line = this.readStringLine(uint8array, lineIndex);
  49894. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  49895. var match = sizeRegexp.exec(line);
  49896. // TODO. Support +Y and -X if needed.
  49897. if (match.length < 3) {
  49898. throw "HDR Bad header format, no size";
  49899. }
  49900. width = parseInt(match[2]);
  49901. height = parseInt(match[1]);
  49902. if (width < 8 || width > 0x7fff) {
  49903. throw "HDR Bad header format, unsupported size";
  49904. }
  49905. lineIndex += (line.length + 1);
  49906. return {
  49907. height: height,
  49908. width: width,
  49909. dataPosition: lineIndex
  49910. };
  49911. };
  49912. /**
  49913. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  49914. * This RGBE texture needs to store the information as a panorama.
  49915. *
  49916. * More information on this format are available here:
  49917. * https://en.wikipedia.org/wiki/RGBE_image_format
  49918. *
  49919. * @param buffer The binary file stored in an array buffer.
  49920. * @param size The expected size of the extracted cubemap.
  49921. * @return The Cube Map information.
  49922. */
  49923. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  49924. var uint8array = new Uint8Array(buffer);
  49925. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  49926. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  49927. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  49928. return cubeMapData;
  49929. };
  49930. /**
  49931. * Returns the pixels data extracted from an RGBE texture.
  49932. * This pixels will be stored left to right up to down in the R G B order in one array.
  49933. *
  49934. * More information on this format are available here:
  49935. * https://en.wikipedia.org/wiki/RGBE_image_format
  49936. *
  49937. * @param uint8array The binary file stored in an array buffer.
  49938. * @param hdrInfo The header information of the file.
  49939. * @return The pixels data in RGB right to left up to down order.
  49940. */
  49941. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  49942. // Keep for multi format supports.
  49943. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  49944. };
  49945. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  49946. var num_scanlines = hdrInfo.height;
  49947. var scanline_width = hdrInfo.width;
  49948. var a, b, c, d, count;
  49949. var dataIndex = hdrInfo.dataPosition;
  49950. var index = 0, endIndex = 0, i = 0;
  49951. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  49952. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  49953. // 3 channels of 4 bytes per pixel in float.
  49954. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  49955. var resultArray = new Float32Array(resultBuffer);
  49956. // read in each successive scanline
  49957. while (num_scanlines > 0) {
  49958. a = uint8array[dataIndex++];
  49959. b = uint8array[dataIndex++];
  49960. c = uint8array[dataIndex++];
  49961. d = uint8array[dataIndex++];
  49962. if (a != 2 || b != 2 || (c & 0x80)) {
  49963. // this file is not run length encoded
  49964. throw "HDR Bad header format, not RLE";
  49965. }
  49966. if (((c << 8) | d) != scanline_width) {
  49967. throw "HDR Bad header format, wrong scan line width";
  49968. }
  49969. index = 0;
  49970. // read each of the four channels for the scanline into the buffer
  49971. for (i = 0; i < 4; i++) {
  49972. endIndex = (i + 1) * scanline_width;
  49973. while (index < endIndex) {
  49974. a = uint8array[dataIndex++];
  49975. b = uint8array[dataIndex++];
  49976. if (a > 128) {
  49977. // a run of the same value
  49978. count = a - 128;
  49979. if ((count == 0) || (count > endIndex - index)) {
  49980. throw "HDR Bad Format, bad scanline data (run)";
  49981. }
  49982. while (count-- > 0) {
  49983. scanLineArray[index++] = b;
  49984. }
  49985. }
  49986. else {
  49987. // a non-run
  49988. count = a;
  49989. if ((count == 0) || (count > endIndex - index)) {
  49990. throw "HDR Bad Format, bad scanline data (non-run)";
  49991. }
  49992. scanLineArray[index++] = b;
  49993. if (--count > 0) {
  49994. for (var j = 0; j < count; j++) {
  49995. scanLineArray[index++] = uint8array[dataIndex++];
  49996. }
  49997. }
  49998. }
  49999. }
  50000. }
  50001. // now convert data from buffer into floats
  50002. for (i = 0; i < scanline_width; i++) {
  50003. a = scanLineArray[i];
  50004. b = scanLineArray[i + scanline_width];
  50005. c = scanLineArray[i + 2 * scanline_width];
  50006. d = scanLineArray[i + 3 * scanline_width];
  50007. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  50008. }
  50009. num_scanlines--;
  50010. }
  50011. return resultArray;
  50012. };
  50013. return HDRTools;
  50014. }());
  50015. Internals.HDRTools = HDRTools;
  50016. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50017. })(BABYLON || (BABYLON = {}));
  50018. //# sourceMappingURL=babylon.hdr.js.map
  50019. //_______________________________________________________________
  50020. // Extracted from CubeMapGen:
  50021. // https://code.google.com/archive/p/cubemapgen/
  50022. //
  50023. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50024. //_______________________________________________________________
  50025. var BABYLON;
  50026. (function (BABYLON) {
  50027. var Internals;
  50028. (function (Internals) {
  50029. /**
  50030. * The bounding box information used during the conversion process.
  50031. */
  50032. var CMGBoundinBox = (function () {
  50033. function CMGBoundinBox() {
  50034. this.min = new BABYLON.Vector3(0, 0, 0);
  50035. this.max = new BABYLON.Vector3(0, 0, 0);
  50036. this.clear();
  50037. }
  50038. CMGBoundinBox.prototype.clear = function () {
  50039. this.min.x = CMGBoundinBox.MAX;
  50040. this.min.y = CMGBoundinBox.MAX;
  50041. this.min.z = CMGBoundinBox.MAX;
  50042. this.max.x = CMGBoundinBox.MIN;
  50043. this.max.y = CMGBoundinBox.MIN;
  50044. this.max.z = CMGBoundinBox.MIN;
  50045. };
  50046. CMGBoundinBox.prototype.augment = function (x, y, z) {
  50047. this.min.x = Math.min(this.min.x, x);
  50048. this.min.y = Math.min(this.min.y, y);
  50049. this.min.z = Math.min(this.min.z, z);
  50050. this.max.x = Math.max(this.max.x, x);
  50051. this.max.y = Math.max(this.max.y, y);
  50052. this.max.z = Math.max(this.max.z, z);
  50053. };
  50054. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  50055. this.min.x = Math.max(this.min.x, x);
  50056. this.min.y = Math.max(this.min.y, y);
  50057. this.min.z = Math.max(this.min.z, z);
  50058. };
  50059. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  50060. this.max.x = Math.min(this.max.x, x);
  50061. this.max.y = Math.min(this.max.y, y);
  50062. this.max.z = Math.min(this.max.z, z);
  50063. };
  50064. CMGBoundinBox.prototype.empty = function () {
  50065. if ((this.min.x > this.max.y) ||
  50066. (this.min.y > this.max.y) ||
  50067. (this.min.z > this.max.y)) {
  50068. return true;
  50069. }
  50070. else {
  50071. return false;
  50072. }
  50073. };
  50074. return CMGBoundinBox;
  50075. }());
  50076. CMGBoundinBox.MAX = Number.MAX_VALUE;
  50077. CMGBoundinBox.MIN = Number.MIN_VALUE;
  50078. /**
  50079. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  50080. * required by the glossinees of a material.
  50081. *
  50082. * This only supports the cosine drop power as well as Warp fixup generation method.
  50083. *
  50084. * This is using the process from CubeMapGen described here:
  50085. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50086. */
  50087. var PMREMGenerator = (function () {
  50088. /**
  50089. * Constructor of the generator.
  50090. *
  50091. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  50092. * @param inputSize The size of the cubemap faces
  50093. * @param outputSize The size of the output cubemap faces
  50094. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  50095. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  50096. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  50097. * @param specularPower The max specular level of the desired cubemap
  50098. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  50099. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  50100. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  50101. */
  50102. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  50103. this.input = input;
  50104. this.inputSize = inputSize;
  50105. this.outputSize = outputSize;
  50106. this.maxNumMipLevels = maxNumMipLevels;
  50107. this.numChannels = numChannels;
  50108. this.isFloat = isFloat;
  50109. this.specularPower = specularPower;
  50110. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  50111. this.excludeBase = excludeBase;
  50112. this.fixup = fixup;
  50113. this._outputSurface = [];
  50114. this._numMipLevels = 0;
  50115. }
  50116. /**
  50117. * Launches the filter process and return the result.
  50118. *
  50119. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  50120. */
  50121. PMREMGenerator.prototype.filterCubeMap = function () {
  50122. // Init cubemap processor
  50123. this.init();
  50124. // Filters the cubemap
  50125. this.filterCubeMapMipChain();
  50126. // Returns the filtered mips.
  50127. return this._outputSurface;
  50128. };
  50129. PMREMGenerator.prototype.init = function () {
  50130. var i;
  50131. var j;
  50132. var mipLevelSize;
  50133. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  50134. if (this.maxNumMipLevels == 0) {
  50135. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  50136. }
  50137. //first miplevel size
  50138. mipLevelSize = this.outputSize;
  50139. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  50140. for (j = 0; j < this.maxNumMipLevels; j++) {
  50141. this._outputSurface.length++;
  50142. this._outputSurface[j] = [];
  50143. //Iterate over faces for output images
  50144. for (i = 0; i < 6; i++) {
  50145. this._outputSurface[j].length++;
  50146. // Initializes a new array for the output.
  50147. if (this.isFloat) {
  50148. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50149. }
  50150. else {
  50151. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50152. }
  50153. }
  50154. //next mip level is half size
  50155. mipLevelSize >>= 1;
  50156. this._numMipLevels++;
  50157. //terminate if mip chain becomes too small
  50158. if (mipLevelSize == 0) {
  50159. this.maxNumMipLevels = j;
  50160. return;
  50161. }
  50162. }
  50163. };
  50164. //--------------------------------------------------------------------------------------
  50165. //Cube map filtering and mip chain generation.
  50166. // the cube map filtereing is specified using a number of parameters:
  50167. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  50168. // indicates the region of the hemisphere to filter over for each tap.
  50169. //
  50170. // Note that the top mip level is also a filtered version of the original input images
  50171. // as well in order to create mip chains for diffuse environment illumination.
  50172. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  50173. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  50174. //
  50175. // Then the mip angle used to genreate the next level of the mip chain from the first level
  50176. // is a_InitialMipAngle
  50177. //
  50178. // The angle for the subsequent levels of the mip chain are specified by their parents
  50179. // filtering angle and a per-level scale and bias
  50180. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  50181. //
  50182. //--------------------------------------------------------------------------------------
  50183. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  50184. // First, take count of the lighting model to modify SpecularPower
  50185. // 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;
  50186. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  50187. //Cone angle start (for generating subsequent mip levels)
  50188. var currentSpecularPower = this.specularPower;
  50189. //Build filter lookup tables based on the source miplevel size
  50190. this.precomputeFilterLookupTables(this.inputSize);
  50191. // Note that we need to filter the first level before generating mipmap
  50192. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  50193. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  50194. // TODO : Write a function to copy and scale the base mipmap in output
  50195. // I am just lazy here and just put a high specular power value, and do some if.
  50196. if (this.excludeBase && (levelIndex == 0)) {
  50197. // 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).
  50198. currentSpecularPower = 100000.0;
  50199. }
  50200. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  50201. var srcCubeImage = this.input;
  50202. var dstCubeImage = this._outputSurface[levelIndex];
  50203. var dstSize = this.outputSize >> levelIndex;
  50204. // Compute required angle.
  50205. var angle = this.getBaseFilterAngle(currentSpecularPower);
  50206. // filter cube surfaces
  50207. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  50208. // fix seams
  50209. if (this.fixup) {
  50210. this.fixupCubeEdges(dstCubeImage, dstSize);
  50211. }
  50212. // Decrease the specular power to generate the mipmap chain
  50213. // TODO : Use another method for Exclude (see first comment at start of the function
  50214. if (this.excludeBase && (levelIndex == 0)) {
  50215. currentSpecularPower = this.specularPower;
  50216. }
  50217. currentSpecularPower *= this.cosinePowerDropPerMip;
  50218. }
  50219. };
  50220. //--------------------------------------------------------------------------------------
  50221. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  50222. // It allow to optimize the texel to access base on the specular power.
  50223. //--------------------------------------------------------------------------------------
  50224. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  50225. // We want to find the alpha such that:
  50226. // cos(alpha)^cosinePower = epsilon
  50227. // That's: acos(epsilon^(1/cosinePower))
  50228. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  50229. var angle = 180.0;
  50230. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  50231. angle *= 180.0 / Math.PI; // Convert to degree
  50232. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  50233. return angle;
  50234. };
  50235. //--------------------------------------------------------------------------------------
  50236. //Builds the following lookup tables prior to filtering:
  50237. // -normalizer cube map
  50238. // -tap weight lookup table
  50239. //
  50240. //--------------------------------------------------------------------------------------
  50241. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  50242. var srcTexelAngle;
  50243. var iCubeFace;
  50244. //clear pre-existing normalizer cube map
  50245. this._normCubeMap = [];
  50246. //Normalized vectors per cubeface and per-texel solid angle
  50247. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  50248. };
  50249. //--------------------------------------------------------------------------------------
  50250. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  50251. //
  50252. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  50253. //
  50254. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  50255. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  50256. // below
  50257. //--------------------------------------------------------------------------------------
  50258. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  50259. var iCubeFace;
  50260. var u;
  50261. var v;
  50262. //iterate over cube faces
  50263. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50264. //First three channels for norm cube, and last channel for solid angle
  50265. this._normCubeMap.push(new Float32Array(size * size * 4));
  50266. //fast texture walk, build normalizer cube map
  50267. var facesData = this.input[iCubeFace];
  50268. for (v = 0; v < size; v++) {
  50269. for (u = 0; u < size; u++) {
  50270. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  50271. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  50272. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  50273. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  50274. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  50275. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  50276. }
  50277. }
  50278. }
  50279. };
  50280. //--------------------------------------------------------------------------------------
  50281. // Convert cubemap face texel coordinates and face idx to 3D vector
  50282. // note the U and V coords are integer coords and range from 0 to size-1
  50283. // this routine can be used to generate a normalizer cube map
  50284. //--------------------------------------------------------------------------------------
  50285. // SL BEGIN
  50286. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  50287. var nvcU;
  50288. var nvcV;
  50289. var tempVec;
  50290. // Change from original AMD code
  50291. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50292. // + 0.5f is for texel center addressing
  50293. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  50294. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  50295. // warp fixup
  50296. if (fixup && size > 1) {
  50297. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  50298. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  50299. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  50300. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  50301. }
  50302. // Get current vector
  50303. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  50304. // U contribution
  50305. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50306. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  50307. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  50308. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  50309. // V contribution and Sum
  50310. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50311. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  50312. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  50313. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  50314. //add face axis
  50315. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  50316. PMREMGenerator._vectorTemp.x += faceAxis[0];
  50317. PMREMGenerator._vectorTemp.y += faceAxis[1];
  50318. PMREMGenerator._vectorTemp.z += faceAxis[2];
  50319. //normalize vector
  50320. PMREMGenerator._vectorTemp.normalize();
  50321. return PMREMGenerator._vectorTemp;
  50322. };
  50323. //--------------------------------------------------------------------------------------
  50324. // Convert 3D vector to cubemap face texel coordinates and face idx
  50325. // note the U and V coords are integer coords and range from 0 to size-1
  50326. // this routine can be used to generate a normalizer cube map
  50327. //
  50328. // returns face IDX and texel coords
  50329. //--------------------------------------------------------------------------------------
  50330. // SL BEGIN
  50331. /*
  50332. Mapping Texture Coordinates to Cube Map Faces
  50333. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  50334. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  50335. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  50336. map arrangement in Pixar's RenderMan package.
  50337. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  50338. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  50339. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  50340. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  50341. the major axis direction). The target column in the table below explains how the major axis direction
  50342. maps to the 2D image of a particular cube map target.
  50343. major axis
  50344. direction target sc tc ma
  50345. ---------- --------------------------------- --- --- ---
  50346. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  50347. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  50348. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  50349. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  50350. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  50351. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  50352. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  50353. an updated (s,t) is calculated as follows
  50354. s = ( sc/|ma| + 1 ) / 2
  50355. t = ( tc/|ma| + 1 ) / 2
  50356. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  50357. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  50358. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  50359. */
  50360. // Note this method return U and V in range from 0 to size-1
  50361. // SL END
  50362. // Store the information in vector3 for convenience (faceindex, u, v)
  50363. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  50364. var maxCoord;
  50365. var faceIdx;
  50366. //absolute value 3
  50367. var absX = Math.abs(x);
  50368. var absY = Math.abs(y);
  50369. var absZ = Math.abs(z);
  50370. if (absX >= absY && absX >= absZ) {
  50371. maxCoord = absX;
  50372. if (x >= 0) {
  50373. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  50374. }
  50375. else {
  50376. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50377. }
  50378. }
  50379. else if (absY >= absX && absY >= absZ) {
  50380. maxCoord = absY;
  50381. if (y >= 0) {
  50382. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50383. }
  50384. else {
  50385. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50386. }
  50387. }
  50388. else {
  50389. maxCoord = absZ;
  50390. if (z >= 0) {
  50391. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50392. }
  50393. else {
  50394. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50395. }
  50396. }
  50397. //divide through by max coord so face vector lies on cube face
  50398. var scale = 1 / maxCoord;
  50399. x *= scale;
  50400. y *= scale;
  50401. z *= scale;
  50402. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50403. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  50404. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50405. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  50406. // Modify original AMD code to return value from 0 to Size - 1
  50407. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  50408. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  50409. PMREMGenerator._vectorTemp.x = faceIdx;
  50410. PMREMGenerator._vectorTemp.y = u;
  50411. PMREMGenerator._vectorTemp.z = v;
  50412. return PMREMGenerator._vectorTemp;
  50413. };
  50414. //--------------------------------------------------------------------------------------
  50415. //Original code from Ignacio CastaÒo
  50416. // This formula is from Manne ÷hrstrˆm's thesis.
  50417. // Take two coordiantes in the range [-1, 1] that define a portion of a
  50418. // cube face and return the area of the projection of that portion on the
  50419. // surface of the sphere.
  50420. //--------------------------------------------------------------------------------------
  50421. PMREMGenerator.prototype.areaElement = function (x, y) {
  50422. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  50423. };
  50424. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  50425. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50426. // (+ 0.5f is for texel center addressing)
  50427. u = (2.0 * (u + 0.5) / size) - 1.0;
  50428. v = (2.0 * (v + 0.5) / size) - 1.0;
  50429. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  50430. var invResolution = 1.0 / size;
  50431. // U and V are the -1..1 texture coordinate on the current face.
  50432. // Get projected area for this texel
  50433. var x0 = u - invResolution;
  50434. var y0 = v - invResolution;
  50435. var x1 = u + invResolution;
  50436. var y1 = v + invResolution;
  50437. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  50438. return solidAngle;
  50439. };
  50440. //--------------------------------------------------------------------------------------
  50441. //The key to the speed of these filtering routines is to quickly define a per-face
  50442. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  50443. // Later these pixels are selectively processed based on their dot products to see if
  50444. // they reside within the filtering cone.
  50445. //
  50446. //This is done by computing the smallest per-texel angle to get a conservative estimate
  50447. // of the number of texels needed to be covered in width and height order to filter the
  50448. // region. the bounding box for the center taps face is defined first, and if the
  50449. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  50450. // defined next
  50451. //--------------------------------------------------------------------------------------
  50452. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  50453. // note that pixels within these regions may be rejected
  50454. // based on the anlge
  50455. var iCubeFace;
  50456. var u;
  50457. var v;
  50458. // bounding box per face to specify region to process
  50459. var filterExtents = [];
  50460. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50461. filterExtents.push(new CMGBoundinBox());
  50462. }
  50463. // min angle a src texel can cover (in degrees)
  50464. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  50465. // angle about center tap to define filter cone
  50466. // filter angle is 1/2 the cone angle
  50467. var filterAngle = filterConeAngle / 2.0;
  50468. //ensure filter angle is larger than a texel
  50469. if (filterAngle < srcTexelAngle) {
  50470. filterAngle = srcTexelAngle;
  50471. }
  50472. //ensure filter cone is always smaller than the hemisphere
  50473. if (filterAngle > 90.0) {
  50474. filterAngle = 90.0;
  50475. }
  50476. // the maximum number of texels in 1D the filter cone angle will cover
  50477. // used to determine bounding box size for filter extents
  50478. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  50479. // ensure conservative region always covers at least one texel
  50480. if (filterSize < 1) {
  50481. filterSize = 1;
  50482. }
  50483. // dotProdThresh threshold based on cone angle to determine whether or not taps
  50484. // reside within the cone angle
  50485. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  50486. // process required faces
  50487. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50488. //iterate over dst cube map face texel
  50489. for (v = 0; v < dstSize; v++) {
  50490. for (u = 0; u < dstSize; u++) {
  50491. //get center tap direction
  50492. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  50493. //clear old per-face filter extents
  50494. this.clearFilterExtents(filterExtents);
  50495. //define per-face filter extents
  50496. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  50497. //perform filtering of src faces using filter extents
  50498. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  50499. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  50500. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  50501. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  50502. }
  50503. }
  50504. }
  50505. };
  50506. //--------------------------------------------------------------------------------------
  50507. //Clear filter extents for the 6 cube map faces
  50508. //--------------------------------------------------------------------------------------
  50509. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  50510. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  50511. filterExtents[iCubeFaces].clear();
  50512. }
  50513. };
  50514. //--------------------------------------------------------------------------------------
  50515. //Define per-face bounding box filter extents
  50516. //
  50517. // These define conservative texel regions in each of the faces the filter can possibly
  50518. // process. When the pixels in the regions are actually processed, the dot product
  50519. // between the tap vector and the center tap vector is used to determine the weight of
  50520. // the tap and whether or not the tap is within the cone.
  50521. //
  50522. //--------------------------------------------------------------------------------------
  50523. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  50524. //neighboring face and bleed over amount, and width of BBOX for
  50525. // left, right, top, and bottom edges of this face
  50526. var bleedOverAmount = [0, 0, 0, 0];
  50527. var bleedOverBBoxMin = [0, 0, 0, 0];
  50528. var bleedOverBBoxMax = [0, 0, 0, 0];
  50529. var neighborFace;
  50530. var neighborEdge;
  50531. var oppositeFaceIdx;
  50532. //get face idx, and u, v info from center tap dir
  50533. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  50534. var faceIdx = result.x;
  50535. var u = result.y;
  50536. var v = result.z;
  50537. //define bbox size within face
  50538. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  50539. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  50540. filterExtents[faceIdx].clampMin(0, 0, 0);
  50541. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  50542. //u and v extent in face corresponding to center tap
  50543. var minU = filterExtents[faceIdx].min.x;
  50544. var minV = filterExtents[faceIdx].min.y;
  50545. var maxU = filterExtents[faceIdx].max.x;
  50546. var maxV = filterExtents[faceIdx].max.y;
  50547. //bleed over amounts for face across u=0 edge (left)
  50548. bleedOverAmount[0] = (bboxSize - u);
  50549. bleedOverBBoxMin[0] = minV;
  50550. bleedOverBBoxMax[0] = maxV;
  50551. //bleed over amounts for face across u=1 edge (right)
  50552. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  50553. bleedOverBBoxMin[1] = minV;
  50554. bleedOverBBoxMax[1] = maxV;
  50555. //bleed over to face across v=0 edge (up)
  50556. bleedOverAmount[2] = (bboxSize - v);
  50557. bleedOverBBoxMin[2] = minU;
  50558. bleedOverBBoxMax[2] = maxU;
  50559. //bleed over to face across v=1 edge (down)
  50560. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  50561. bleedOverBBoxMin[3] = minU;
  50562. bleedOverBBoxMax[3] = maxU;
  50563. //compute bleed over regions in neighboring faces
  50564. for (var i = 0; i < 4; i++) {
  50565. if (bleedOverAmount[i] > 0) {
  50566. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  50567. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  50568. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  50569. // be flipped: the cases are
  50570. // if a left edge mates with a left or bottom edge on the neighbor
  50571. // if a top edge mates with a top or right edge on the neighbor
  50572. // if a right edge mates with a right or top edge on the neighbor
  50573. // if a bottom edge mates with a bottom or left edge on the neighbor
  50574. //Seeing as the edges are enumerated as follows
  50575. // left =0
  50576. // right =1
  50577. // top =2
  50578. // bottom =3
  50579. //
  50580. // so if the edge enums are the same, or the sum of the enums == 3,
  50581. // the bbox needs to be flipped
  50582. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  50583. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  50584. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  50585. }
  50586. //The way the bounding box is extended onto the neighboring face
  50587. // depends on which edge of neighboring face abuts with this one
  50588. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  50589. case PMREMGenerator.CP_EDGE_LEFT:
  50590. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  50591. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  50592. break;
  50593. case PMREMGenerator.CP_EDGE_RIGHT:
  50594. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  50595. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  50596. break;
  50597. case PMREMGenerator.CP_EDGE_TOP:
  50598. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  50599. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  50600. break;
  50601. case PMREMGenerator.CP_EDGE_BOTTOM:
  50602. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  50603. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  50604. break;
  50605. }
  50606. //clamp filter extents in non-center tap faces to remain within surface
  50607. filterExtents[neighborFace].clampMin(0, 0, 0);
  50608. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  50609. }
  50610. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  50611. // from the center tap face, then process the opposite face entirely for now.
  50612. //Note that the cases in which this happens, what usually happens is that
  50613. // more than one edge bleeds onto the opposite face, and the bounding box
  50614. // encompasses the entire cube map face.
  50615. if (bleedOverAmount[i] > srcSize) {
  50616. //determine opposite face
  50617. switch (faceIdx) {
  50618. case PMREMGenerator.CP_FACE_X_POS:
  50619. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50620. break;
  50621. case PMREMGenerator.CP_FACE_X_NEG:
  50622. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  50623. break;
  50624. case PMREMGenerator.CP_FACE_Y_POS:
  50625. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50626. break;
  50627. case PMREMGenerator.CP_FACE_Y_NEG:
  50628. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50629. break;
  50630. case PMREMGenerator.CP_FACE_Z_POS:
  50631. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50632. break;
  50633. case PMREMGenerator.CP_FACE_Z_NEG:
  50634. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50635. break;
  50636. default:
  50637. break;
  50638. }
  50639. //just encompass entire face for now
  50640. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  50641. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  50642. }
  50643. }
  50644. };
  50645. //--------------------------------------------------------------------------------------
  50646. //ProcessFilterExtents
  50647. // Process bounding box in each cube face
  50648. //
  50649. //--------------------------------------------------------------------------------------
  50650. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  50651. //accumulators are 64-bit floats in order to have the precision needed
  50652. // over a summation of a large number of pixels
  50653. var dstAccum = [0, 0, 0, 0];
  50654. var weightAccum = 0;
  50655. var k = 0;
  50656. var nSrcChannels = this.numChannels;
  50657. // norm cube map and srcCubeMap have same face width
  50658. var faceWidth = srcSize;
  50659. //amount to add to pointer to move to next scanline in images
  50660. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  50661. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  50662. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  50663. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  50664. // iterate over cubefaces
  50665. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  50666. //if bbox is non empty
  50667. if (!filterExtents[iFaceIdx].empty()) {
  50668. var uStart = filterExtents[iFaceIdx].min.x;
  50669. var vStart = filterExtents[iFaceIdx].min.y;
  50670. var uEnd = filterExtents[iFaceIdx].max.x;
  50671. var vEnd = filterExtents[iFaceIdx].max.y;
  50672. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  50673. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  50674. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  50675. for (var v = vStart; v <= vEnd; v++) {
  50676. var normCubeRowWalk = 0;
  50677. var srcCubeRowWalk = 0;
  50678. for (var u = uStart; u <= uEnd; u++) {
  50679. //pointer to direction in cube map associated with texel
  50680. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  50681. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  50682. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  50683. //check dot product to see if texel is within cone
  50684. var tapDotProd = texelVectX * centerTapDir.x +
  50685. texelVectY * centerTapDir.y +
  50686. texelVectZ * centerTapDir.z;
  50687. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  50688. //solid angle stored in 4th channel of normalizer/solid angle cube map
  50689. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  50690. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  50691. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  50692. // so just adding one to specularpower do the trick.
  50693. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  50694. //iterate over channels
  50695. for (k = 0; k < nSrcChannels; k++) {
  50696. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  50697. srcCubeRowWalk++;
  50698. }
  50699. weightAccum += weight; //accumulate weight
  50700. }
  50701. else {
  50702. //step across source pixel
  50703. srcCubeRowWalk += nSrcChannels;
  50704. }
  50705. normCubeRowWalk += 4; // 4 channels per norm cube map.
  50706. }
  50707. startIndexNormCubeMap += normCubePitch;
  50708. startIndexSrcCubeMap += srcCubePitch;
  50709. }
  50710. }
  50711. }
  50712. //divide through by weights if weight is non zero
  50713. if (weightAccum != 0.0) {
  50714. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  50715. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  50716. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  50717. if (this.numChannels > 3) {
  50718. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  50719. }
  50720. }
  50721. else {
  50722. // otherwise sample nearest
  50723. // get face idx and u, v texel coordinate in face
  50724. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  50725. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  50726. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  50727. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  50728. if (this.numChannels > 3) {
  50729. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  50730. }
  50731. }
  50732. return PMREMGenerator._vectorTemp;
  50733. };
  50734. //--------------------------------------------------------------------------------------
  50735. // Fixup cube edges
  50736. //
  50737. // average texels on cube map faces across the edges
  50738. // WARP/BENT Method Only.
  50739. //--------------------------------------------------------------------------------------
  50740. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  50741. var k;
  50742. var j;
  50743. var i;
  50744. var iFace;
  50745. var iCorner = 0;
  50746. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  50747. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  50748. // note that if functionality to filter across the three texels for each corner, then
  50749. //indexed by corner and face idx. the array contains the face the start points belongs to.
  50750. var cornerPtr = [
  50751. [[], [], []],
  50752. [[], [], []],
  50753. [[], [], []],
  50754. [[], [], []],
  50755. [[], [], []],
  50756. [[], [], []],
  50757. [[], [], []],
  50758. [[], [], []]
  50759. ];
  50760. //if there is no fixup, or fixup width = 0, do nothing
  50761. if (cubeMapSize < 1) {
  50762. return;
  50763. }
  50764. //special case 1x1 cubemap, average face colors
  50765. if (cubeMapSize == 1) {
  50766. //iterate over channels
  50767. for (k = 0; k < this.numChannels; k++) {
  50768. var accum = 0.0;
  50769. //iterate over faces to accumulate face colors
  50770. for (iFace = 0; iFace < 6; iFace++) {
  50771. accum += cubeMap[iFace][k];
  50772. }
  50773. //compute average over 6 face colors
  50774. accum /= 6.0;
  50775. //iterate over faces to distribute face colors
  50776. for (iFace = 0; iFace < 6; iFace++) {
  50777. cubeMap[iFace][k] = accum;
  50778. }
  50779. }
  50780. return;
  50781. }
  50782. //iterate over faces to collect list of corner texel pointers
  50783. for (iFace = 0; iFace < 6; iFace++) {
  50784. //the 4 corner pointers for this face
  50785. faceCornerStartIndicies[0] = [iFace, 0];
  50786. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  50787. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  50788. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  50789. //iterate over face corners to collect cube corner pointers
  50790. for (iCorner = 0; iCorner < 4; iCorner++) {
  50791. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  50792. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  50793. cornerNumPtrs[corner]++;
  50794. }
  50795. }
  50796. //iterate over corners to average across corner tap values
  50797. for (iCorner = 0; iCorner < 8; iCorner++) {
  50798. for (k = 0; k < this.numChannels; k++) {
  50799. var cornerTapAccum = 0.0;
  50800. //iterate over corner texels and average results
  50801. for (i = 0; i < 3; i++) {
  50802. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  50803. }
  50804. //divide by 3 to compute average of corner tap values
  50805. cornerTapAccum *= (1.0 / 3.0);
  50806. //iterate over corner texels and average results
  50807. for (i = 0; i < 3; i++) {
  50808. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  50809. }
  50810. }
  50811. }
  50812. //iterate over the twelve edges of the cube to average across edges
  50813. for (i = 0; i < 12; i++) {
  50814. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  50815. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  50816. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  50817. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  50818. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  50819. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  50820. var edgeWalk = 0;
  50821. var neighborEdgeWalk = 0;
  50822. //Determine walking pointers based on edge type
  50823. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  50824. switch (edge) {
  50825. case PMREMGenerator.CP_EDGE_LEFT:
  50826. // no change to faceEdgeStartPtr
  50827. edgeWalk = this.numChannels * cubeMapSize;
  50828. break;
  50829. case PMREMGenerator.CP_EDGE_RIGHT:
  50830. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  50831. edgeWalk = this.numChannels * cubeMapSize;
  50832. break;
  50833. case PMREMGenerator.CP_EDGE_TOP:
  50834. // no change to faceEdgeStartPtr
  50835. edgeWalk = this.numChannels;
  50836. break;
  50837. case PMREMGenerator.CP_EDGE_BOTTOM:
  50838. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  50839. edgeWalk = this.numChannels;
  50840. break;
  50841. }
  50842. //For certain types of edge abutments, the neighbor edge walk needs to
  50843. // be flipped: the cases are
  50844. // if a left edge mates with a left or bottom edge on the neighbor
  50845. // if a top edge mates with a top or right edge on the neighbor
  50846. // if a right edge mates with a right or top edge on the neighbor
  50847. // if a bottom edge mates with a bottom or left edge on the neighbor
  50848. //Seeing as the edges are enumerated as follows
  50849. // left =0
  50850. // right =1
  50851. // top =2
  50852. // bottom =3
  50853. //
  50854. //If the edge enums are the same, or the sum of the enums == 3,
  50855. // the neighbor edge walk needs to be flipped
  50856. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  50857. switch (neighborEdge) {
  50858. case PMREMGenerator.CP_EDGE_LEFT:
  50859. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  50860. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  50861. break;
  50862. case PMREMGenerator.CP_EDGE_RIGHT:
  50863. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  50864. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  50865. break;
  50866. case PMREMGenerator.CP_EDGE_TOP:
  50867. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  50868. neighborEdgeWalk = -this.numChannels;
  50869. break;
  50870. case PMREMGenerator.CP_EDGE_BOTTOM:
  50871. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  50872. neighborEdgeWalk = -this.numChannels;
  50873. break;
  50874. }
  50875. }
  50876. else {
  50877. //swapped direction neighbor edge walk
  50878. switch (neighborEdge) {
  50879. case PMREMGenerator.CP_EDGE_LEFT:
  50880. //no change to neighborEdgeStartPtr for this case since it points
  50881. // to the upper left corner already
  50882. neighborEdgeWalk = this.numChannels * cubeMapSize;
  50883. break;
  50884. case PMREMGenerator.CP_EDGE_RIGHT:
  50885. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  50886. neighborEdgeWalk = this.numChannels * cubeMapSize;
  50887. break;
  50888. case PMREMGenerator.CP_EDGE_TOP:
  50889. //no change to neighborEdgeStartPtr for this case since it points
  50890. // to the upper left corner already
  50891. neighborEdgeWalk = this.numChannels;
  50892. break;
  50893. case PMREMGenerator.CP_EDGE_BOTTOM:
  50894. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  50895. neighborEdgeWalk = this.numChannels;
  50896. break;
  50897. }
  50898. }
  50899. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  50900. //nearby neighborhood
  50901. //step ahead one texel on edge
  50902. edgeStartIndex += edgeWalk;
  50903. neighborEdgeStartIndex += neighborEdgeWalk;
  50904. // note that this loop does not process the corner texels, since they have already been
  50905. // averaged across faces across earlier
  50906. for (j = 1; j < (cubeMapSize - 1); j++) {
  50907. //for each set of taps along edge, average them
  50908. // and rewrite the results into the edges
  50909. for (k = 0; k < this.numChannels; k++) {
  50910. var edgeTap = cubeMap[face][edgeStartIndex + k];
  50911. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  50912. //compute average of tap intensity values
  50913. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  50914. //propagate average of taps to edge taps
  50915. cubeMap[face][edgeStartIndex + k] = avgTap;
  50916. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  50917. }
  50918. edgeStartIndex += edgeWalk;
  50919. neighborEdgeStartIndex += neighborEdgeWalk;
  50920. }
  50921. }
  50922. };
  50923. return PMREMGenerator;
  50924. }());
  50925. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  50926. PMREMGenerator.CP_UDIR = 0;
  50927. PMREMGenerator.CP_VDIR = 1;
  50928. PMREMGenerator.CP_FACEAXIS = 2;
  50929. //used to index cube faces
  50930. PMREMGenerator.CP_FACE_X_POS = 0;
  50931. PMREMGenerator.CP_FACE_X_NEG = 1;
  50932. PMREMGenerator.CP_FACE_Y_POS = 2;
  50933. PMREMGenerator.CP_FACE_Y_NEG = 3;
  50934. PMREMGenerator.CP_FACE_Z_POS = 4;
  50935. PMREMGenerator.CP_FACE_Z_NEG = 5;
  50936. //used to index image edges
  50937. // NOTE.. the actual number corresponding to the edge is important
  50938. // do not change these, or the code will break
  50939. //
  50940. // CP_EDGE_LEFT is u = 0
  50941. // CP_EDGE_RIGHT is u = width-1
  50942. // CP_EDGE_TOP is v = 0
  50943. // CP_EDGE_BOTTOM is v = height-1
  50944. PMREMGenerator.CP_EDGE_LEFT = 0;
  50945. PMREMGenerator.CP_EDGE_RIGHT = 1;
  50946. PMREMGenerator.CP_EDGE_TOP = 2;
  50947. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  50948. //corners of CUBE map (P or N specifys if it corresponds to the
  50949. // positive or negative direction each of X, Y, and Z
  50950. PMREMGenerator.CP_CORNER_NNN = 0;
  50951. PMREMGenerator.CP_CORNER_NNP = 1;
  50952. PMREMGenerator.CP_CORNER_NPN = 2;
  50953. PMREMGenerator.CP_CORNER_NPP = 3;
  50954. PMREMGenerator.CP_CORNER_PNN = 4;
  50955. PMREMGenerator.CP_CORNER_PNP = 5;
  50956. PMREMGenerator.CP_CORNER_PPN = 6;
  50957. PMREMGenerator.CP_CORNER_PPP = 7;
  50958. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  50959. //3x2 matrices that map cube map indexing vectors in 3d
  50960. // (after face selection and divide through by the
  50961. // _ABSOLUTE VALUE_ of the max coord)
  50962. // into NVC space
  50963. //Note this currently assumes the D3D cube face ordering and orientation
  50964. PMREMGenerator._sgFace2DMapping = [
  50965. //XPOS face
  50966. [[0, 0, -1],
  50967. [0, -1, 0],
  50968. [1, 0, 0]],
  50969. //XNEG face
  50970. [[0, 0, 1],
  50971. [0, -1, 0],
  50972. [-1, 0, 0]],
  50973. //YPOS face
  50974. [[1, 0, 0],
  50975. [0, 0, 1],
  50976. [0, 1, 0]],
  50977. //YNEG face
  50978. [[1, 0, 0],
  50979. [0, 0, -1],
  50980. [0, -1, 0]],
  50981. //ZPOS face
  50982. [[1, 0, 0],
  50983. [0, -1, 0],
  50984. [0, 0, 1]],
  50985. //ZNEG face
  50986. [[-1, 0, 0],
  50987. [0, -1, 0],
  50988. [0, 0, -1]],
  50989. ];
  50990. //------------------------------------------------------------------------------
  50991. // D3D cube map face specification
  50992. // mapping from 3D x,y,z cube map lookup coordinates
  50993. // to 2D within face u,v coordinates
  50994. //
  50995. // --------------------> U direction
  50996. // | (within-face texture space)
  50997. // | _____
  50998. // | | |
  50999. // | | +Y |
  51000. // | _____|_____|_____ _____
  51001. // | | | | | |
  51002. // | | -X | +Z | +X | -Z |
  51003. // | |_____|_____|_____|_____|
  51004. // | | |
  51005. // | | -Y |
  51006. // | |_____|
  51007. // |
  51008. // v V direction
  51009. // (within-face texture space)
  51010. //------------------------------------------------------------------------------
  51011. //Information about neighbors and how texture coorrdinates change across faces
  51012. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  51013. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  51014. //Note this currently assumes the D3D cube face ordering and orientation
  51015. PMREMGenerator._sgCubeNgh = [
  51016. //XPOS face
  51017. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51018. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51019. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51020. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  51021. //XNEG face
  51022. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51023. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  51024. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  51025. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  51026. //YPOS face
  51027. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51028. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51029. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51030. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  51031. //YNEG face
  51032. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51033. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51034. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51035. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  51036. //ZPOS face
  51037. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51038. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51039. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51040. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  51041. //ZNEG face
  51042. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51043. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51044. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  51045. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  51046. ];
  51047. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  51048. // this table is used to average over the edges.
  51049. PMREMGenerator._sgCubeEdgeList = [
  51050. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51051. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51052. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51053. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51054. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51055. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51056. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51057. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51058. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  51059. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51060. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51061. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  51062. ];
  51063. //Information about which of the 8 cube corners are correspond to the
  51064. // the 4 corners in each cube face
  51065. // the order is upper left, upper right, lower left, lower right
  51066. PMREMGenerator._sgCubeCornerList = [
  51067. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  51068. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  51069. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  51070. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  51071. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  51072. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  51073. ];
  51074. Internals.PMREMGenerator = PMREMGenerator;
  51075. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51076. })(BABYLON || (BABYLON = {}));
  51077. //# sourceMappingURL=babylon.pmremgenerator.js.map
  51078. var BABYLON;
  51079. (function (BABYLON) {
  51080. /**
  51081. * This represents a texture coming from an HDR input.
  51082. *
  51083. * The only supported format is currently panorama picture stored in RGBE format.
  51084. * Example of such files can be found on HDRLib: http://hdrlib.com/
  51085. */
  51086. var HDRCubeTexture = (function (_super) {
  51087. __extends(HDRCubeTexture, _super);
  51088. /**
  51089. * Instantiates an HDRTexture from the following parameters.
  51090. *
  51091. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  51092. * @param scene The scene the texture will be used in
  51093. * @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.
  51094. * @param noMipmap Forces to not generate the mipmap if true
  51095. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  51096. * @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)
  51097. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  51098. */
  51099. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  51100. if (noMipmap === void 0) { noMipmap = false; }
  51101. if (generateHarmonics === void 0) { generateHarmonics = true; }
  51102. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  51103. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  51104. if (onLoad === void 0) { onLoad = null; }
  51105. if (onError === void 0) { onError = null; }
  51106. var _this = _super.call(this, scene) || this;
  51107. _this._useInGammaSpace = false;
  51108. _this._generateHarmonics = true;
  51109. _this._isBABYLONPreprocessed = false;
  51110. _this._onLoad = null;
  51111. _this._onError = null;
  51112. /**
  51113. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  51114. */
  51115. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51116. /**
  51117. * The spherical polynomial data extracted from the texture.
  51118. */
  51119. _this.sphericalPolynomial = null;
  51120. /**
  51121. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  51122. * This is usefull at run time to apply the good shader.
  51123. */
  51124. _this.isPMREM = false;
  51125. if (!url) {
  51126. return _this;
  51127. }
  51128. _this.name = url;
  51129. _this.url = url;
  51130. _this.hasAlpha = false;
  51131. _this.isCube = true;
  51132. _this._textureMatrix = BABYLON.Matrix.Identity();
  51133. _this._onLoad = onLoad;
  51134. _this._onError = onError;
  51135. if (size) {
  51136. _this._isBABYLONPreprocessed = false;
  51137. _this._noMipmap = noMipmap;
  51138. _this._size = size;
  51139. _this._useInGammaSpace = useInGammaSpace;
  51140. _this._usePMREMGenerator = usePMREMGenerator &&
  51141. scene.getEngine().getCaps().textureLOD &&
  51142. _this.getScene().getEngine().getCaps().textureFloat &&
  51143. !_this._useInGammaSpace;
  51144. }
  51145. else {
  51146. _this._isBABYLONPreprocessed = true;
  51147. _this._noMipmap = false;
  51148. _this._useInGammaSpace = false;
  51149. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  51150. _this.getScene().getEngine().getCaps().textureFloat &&
  51151. !_this._useInGammaSpace;
  51152. }
  51153. _this.isPMREM = _this._usePMREMGenerator;
  51154. _this._texture = _this._getFromCache(url, _this._noMipmap);
  51155. if (!_this._texture) {
  51156. if (!scene.useDelayedTextureLoading) {
  51157. _this.loadTexture();
  51158. }
  51159. else {
  51160. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51161. }
  51162. }
  51163. return _this;
  51164. }
  51165. /**
  51166. * Occurs when the file is a preprocessed .babylon.hdr file.
  51167. */
  51168. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  51169. var _this = this;
  51170. var mipLevels = 0;
  51171. var floatArrayView = null;
  51172. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  51173. var mips = [];
  51174. var startIndex = 30;
  51175. for (var level = 0; level < mipLevels; level++) {
  51176. mips.push([]);
  51177. // Fill each pixel of the mip level.
  51178. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  51179. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51180. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  51181. mips[level].push(faceData);
  51182. startIndex += faceSize;
  51183. }
  51184. }
  51185. return mips;
  51186. } : null;
  51187. var callback = function (buffer) {
  51188. // Create Native Array Views
  51189. var intArrayView = new Int32Array(buffer);
  51190. floatArrayView = new Float32Array(buffer);
  51191. // Fill header.
  51192. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  51193. _this._size = intArrayView[1]; // CubeMap max mip face size.
  51194. // Update Texture Information.
  51195. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  51196. // Fill polynomial information.
  51197. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  51198. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  51199. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  51200. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  51201. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  51202. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  51203. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  51204. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  51205. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  51206. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  51207. // Fill pixel data.
  51208. mipLevels = intArrayView[29]; // Number of mip levels.
  51209. var startIndex = 30;
  51210. var data = [];
  51211. var faceSize = Math.pow(_this._size, 2) * 3;
  51212. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51213. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  51214. startIndex += faceSize;
  51215. }
  51216. var results = [];
  51217. var byteArray = null;
  51218. // Push each faces.
  51219. for (var k = 0; k < 6; k++) {
  51220. var dataFace = null;
  51221. // If special cases.
  51222. if (!mipmapGenerator) {
  51223. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  51224. dataFace = data[j];
  51225. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51226. // 3 channels of 1 bytes per pixel in bytes.
  51227. var byteBuffer = new ArrayBuffer(faceSize);
  51228. byteArray = new Uint8Array(byteBuffer);
  51229. }
  51230. for (var i = 0; i < _this._size * _this._size; i++) {
  51231. // Put in gamma space if requested.
  51232. if (_this._useInGammaSpace) {
  51233. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51234. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51235. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51236. }
  51237. // Convert to int texture for fallback.
  51238. if (byteArray) {
  51239. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51240. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51241. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51242. // May use luminance instead if the result is not accurate.
  51243. var max = Math.max(Math.max(r, g), b);
  51244. if (max > 255) {
  51245. var scale = 255 / max;
  51246. r *= scale;
  51247. g *= scale;
  51248. b *= scale;
  51249. }
  51250. byteArray[(i * 3) + 0] = r;
  51251. byteArray[(i * 3) + 1] = g;
  51252. byteArray[(i * 3) + 2] = b;
  51253. }
  51254. }
  51255. }
  51256. else {
  51257. dataFace = data[k];
  51258. }
  51259. // Fill the array accordingly.
  51260. if (byteArray) {
  51261. results.push(byteArray);
  51262. }
  51263. else {
  51264. results.push(dataFace);
  51265. }
  51266. }
  51267. return results;
  51268. };
  51269. this._texture = this.getScene().getEngine().createRawCubeTexture(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);
  51270. };
  51271. /**
  51272. * Occurs when the file is raw .hdr file.
  51273. */
  51274. HDRCubeTexture.prototype.loadHDRTexture = function () {
  51275. var _this = this;
  51276. var callback = function (buffer) {
  51277. // Extract the raw linear data.
  51278. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  51279. // Generate harmonics if needed.
  51280. if (_this._generateHarmonics) {
  51281. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  51282. }
  51283. var results = [];
  51284. var byteArray = null;
  51285. // Push each faces.
  51286. for (var j = 0; j < 6; j++) {
  51287. // Create uintarray fallback.
  51288. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51289. // 3 channels of 1 bytes per pixel in bytes.
  51290. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  51291. byteArray = new Uint8Array(byteBuffer);
  51292. }
  51293. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  51294. // If special cases.
  51295. if (_this._useInGammaSpace || byteArray) {
  51296. for (var i = 0; i < _this._size * _this._size; i++) {
  51297. // Put in gamma space if requested.
  51298. if (_this._useInGammaSpace) {
  51299. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51300. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51301. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51302. }
  51303. // Convert to int texture for fallback.
  51304. if (byteArray) {
  51305. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51306. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51307. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51308. // May use luminance instead if the result is not accurate.
  51309. var max = Math.max(Math.max(r, g), b);
  51310. if (max > 255) {
  51311. var scale = 255 / max;
  51312. r *= scale;
  51313. g *= scale;
  51314. b *= scale;
  51315. }
  51316. byteArray[(i * 3) + 0] = r;
  51317. byteArray[(i * 3) + 1] = g;
  51318. byteArray[(i * 3) + 2] = b;
  51319. }
  51320. }
  51321. }
  51322. if (byteArray) {
  51323. results.push(byteArray);
  51324. }
  51325. else {
  51326. results.push(dataFace);
  51327. }
  51328. }
  51329. return results;
  51330. };
  51331. var mipmapGenerator = null;
  51332. if (!this._noMipmap &&
  51333. this._usePMREMGenerator) {
  51334. mipmapGenerator = function (data) {
  51335. // Custom setup of the generator matching with the PBR shader values.
  51336. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  51337. return generator.filterCubeMap();
  51338. };
  51339. }
  51340. this._texture = this.getScene().getEngine().createRawCubeTexture(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);
  51341. };
  51342. /**
  51343. * Starts the loading process of the texture.
  51344. */
  51345. HDRCubeTexture.prototype.loadTexture = function () {
  51346. if (this._isBABYLONPreprocessed) {
  51347. this.loadBabylonTexture();
  51348. }
  51349. else {
  51350. this.loadHDRTexture();
  51351. }
  51352. };
  51353. HDRCubeTexture.prototype.clone = function () {
  51354. var size = this._isBABYLONPreprocessed ? null : this._size;
  51355. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  51356. // Base texture
  51357. newTexture.level = this.level;
  51358. newTexture.wrapU = this.wrapU;
  51359. newTexture.wrapV = this.wrapV;
  51360. newTexture.coordinatesIndex = this.coordinatesIndex;
  51361. newTexture.coordinatesMode = this.coordinatesMode;
  51362. return newTexture;
  51363. };
  51364. // Methods
  51365. HDRCubeTexture.prototype.delayLoad = function () {
  51366. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51367. return;
  51368. }
  51369. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51370. this._texture = this._getFromCache(this.url, this._noMipmap);
  51371. if (!this._texture) {
  51372. this.loadTexture();
  51373. }
  51374. };
  51375. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  51376. return this._textureMatrix;
  51377. };
  51378. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51379. var texture = null;
  51380. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  51381. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  51382. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  51383. texture.name = parsedTexture.name;
  51384. texture.hasAlpha = parsedTexture.hasAlpha;
  51385. texture.level = parsedTexture.level;
  51386. texture.coordinatesMode = parsedTexture.coordinatesMode;
  51387. }
  51388. return texture;
  51389. };
  51390. HDRCubeTexture.prototype.serialize = function () {
  51391. if (!this.name) {
  51392. return null;
  51393. }
  51394. var serializationObject = {};
  51395. serializationObject.name = this.name;
  51396. serializationObject.hasAlpha = this.hasAlpha;
  51397. serializationObject.isCube = true;
  51398. serializationObject.level = this.level;
  51399. serializationObject.size = this._size;
  51400. serializationObject.coordinatesMode = this.coordinatesMode;
  51401. serializationObject.useInGammaSpace = this._useInGammaSpace;
  51402. serializationObject.generateHarmonics = this._generateHarmonics;
  51403. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  51404. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  51405. serializationObject.customType = "BABYLON.HDRCubeTexture";
  51406. serializationObject.noMipmap = this._noMipmap;
  51407. return serializationObject;
  51408. };
  51409. /**
  51410. * Saves as a file the data contained in the texture in a binary format.
  51411. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51412. * as the spherical used in the lighting.
  51413. * @param url The HDR file url.
  51414. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51415. * @param onError Method called if any error happens during download.
  51416. * @return The packed binary data.
  51417. */
  51418. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  51419. if (onError === void 0) { onError = null; }
  51420. var callback = function (buffer) {
  51421. var data = new Blob([buffer], { type: 'application/octet-stream' });
  51422. // Returns a URL you can use as a href.
  51423. var objUrl = window.URL.createObjectURL(data);
  51424. // Simulates a link to it and click to dowload.
  51425. var a = document.createElement("a");
  51426. document.body.appendChild(a);
  51427. a.style.display = "none";
  51428. a.href = objUrl;
  51429. a.download = "envmap.babylon.hdr";
  51430. a.click();
  51431. };
  51432. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  51433. };
  51434. /**
  51435. * Serializes the data contained in the texture in a binary format.
  51436. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51437. * as the spherical used in the lighting.
  51438. * @param url The HDR file url.
  51439. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51440. * @param onError Method called if any error happens during download.
  51441. * @return The packed binary data.
  51442. */
  51443. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  51444. if (onError === void 0) { onError = null; }
  51445. // Needs the url tho create the texture.
  51446. if (!url) {
  51447. return null;
  51448. }
  51449. // Check Power of two size.
  51450. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  51451. return null;
  51452. }
  51453. var getDataCallback = function (dataBuffer) {
  51454. // Extract the raw linear data.
  51455. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  51456. // Generate harmonics if needed.
  51457. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  51458. // Generate seamless faces
  51459. var mipGeneratorArray = [];
  51460. // Data are known to be in +X +Y +Z -X -Y -Z
  51461. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  51462. mipGeneratorArray.push(cubeData.right); // +X
  51463. mipGeneratorArray.push(cubeData.left); // -X
  51464. mipGeneratorArray.push(cubeData.up); // +Y
  51465. mipGeneratorArray.push(cubeData.down); // -Y
  51466. mipGeneratorArray.push(cubeData.front); // +Z
  51467. mipGeneratorArray.push(cubeData.back); // -Z
  51468. // Custom setup of the generator matching with the PBR shader values.
  51469. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  51470. var mippedData = generator.filterCubeMap();
  51471. // Compute required byte length.
  51472. var byteLength = 1 * 4; // Raw Data Version int32.
  51473. byteLength += 4; // CubeMap max mip face size int32.
  51474. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  51475. // Add data size.
  51476. byteLength += 4; // Number of mip levels int32.
  51477. for (var level = 0; level < mippedData.length; level++) {
  51478. var mipSize = size >> level;
  51479. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  51480. }
  51481. // Prepare binary structure.
  51482. var buffer = new ArrayBuffer(byteLength);
  51483. var intArrayView = new Int32Array(buffer);
  51484. var floatArrayView = new Float32Array(buffer);
  51485. // Fill header.
  51486. intArrayView[0] = 1; // Version 1.
  51487. intArrayView[1] = size; // CubeMap max mip face size.
  51488. // Fill polynomial information.
  51489. sphericalPolynomial.x.toArray(floatArrayView, 2);
  51490. sphericalPolynomial.y.toArray(floatArrayView, 5);
  51491. sphericalPolynomial.z.toArray(floatArrayView, 8);
  51492. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  51493. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  51494. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  51495. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  51496. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  51497. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  51498. // Fill pixel data.
  51499. intArrayView[29] = mippedData.length; // Number of mip levels.
  51500. var startIndex = 30;
  51501. for (var level = 0; level < mippedData.length; level++) {
  51502. // Fill each pixel of the mip level.
  51503. var faceSize = Math.pow(size >> level, 2) * 3;
  51504. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51505. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  51506. startIndex += faceSize;
  51507. }
  51508. }
  51509. // Callback.
  51510. callback(buffer);
  51511. };
  51512. // Download and process.
  51513. BABYLON.Tools.LoadFile(url, function (data) {
  51514. getDataCallback(data);
  51515. }, null, null, true, onError);
  51516. };
  51517. return HDRCubeTexture;
  51518. }(BABYLON.BaseTexture));
  51519. HDRCubeTexture._facesMapping = [
  51520. "right",
  51521. "up",
  51522. "front",
  51523. "left",
  51524. "down",
  51525. "back"
  51526. ];
  51527. BABYLON.HDRCubeTexture = HDRCubeTexture;
  51528. })(BABYLON || (BABYLON = {}));
  51529. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  51530. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  51531. // Huge respect for a such great lib.
  51532. // Earcut license:
  51533. // Copyright (c) 2016, Mapbox
  51534. //
  51535. // Permission to use, copy, modify, and/or distribute this software for any purpose
  51536. // with or without fee is hereby granted, provided that the above copyright notice
  51537. // and this permission notice appear in all copies.
  51538. //
  51539. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  51540. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  51541. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  51542. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  51543. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  51544. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  51545. // THIS SOFTWARE.
  51546. var Earcut;
  51547. (function (Earcut) {
  51548. /**
  51549. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  51550. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  51551. * @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).
  51552. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  51553. */
  51554. function earcut(data, holeIndices, dim) {
  51555. dim = dim || 2;
  51556. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  51557. if (!outerNode)
  51558. return triangles;
  51559. var minX, minY, maxX, maxY, x, y, size;
  51560. if (hasHoles)
  51561. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  51562. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  51563. if (data.length > 80 * dim) {
  51564. minX = maxX = data[0];
  51565. minY = maxY = data[1];
  51566. for (var i = dim; i < outerLen; i += dim) {
  51567. x = data[i];
  51568. y = data[i + 1];
  51569. if (x < minX)
  51570. minX = x;
  51571. if (y < minY)
  51572. minY = y;
  51573. if (x > maxX)
  51574. maxX = x;
  51575. if (y > maxY)
  51576. maxY = y;
  51577. }
  51578. // minX, minY and size are later used to transform coords into integers for z-order calculation
  51579. size = Math.max(maxX - minX, maxY - minY);
  51580. }
  51581. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  51582. return triangles;
  51583. }
  51584. Earcut.earcut = earcut;
  51585. // create a circular doubly linked list from polygon points in the specified winding order
  51586. function linkedList(data, start, end, dim, clockwise) {
  51587. var i, last;
  51588. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  51589. for (i = start; i < end; i += dim)
  51590. last = insertNode(i, data[i], data[i + 1], last);
  51591. }
  51592. else {
  51593. for (i = end - dim; i >= start; i -= dim)
  51594. last = insertNode(i, data[i], data[i + 1], last);
  51595. }
  51596. if (last && equals(last, last.next)) {
  51597. removeNode(last);
  51598. last = last.next;
  51599. }
  51600. return last;
  51601. }
  51602. // eliminate colinear or duplicate points
  51603. function filterPoints(start, end) {
  51604. if (!start)
  51605. return start;
  51606. if (!end)
  51607. end = start;
  51608. var p = start, again;
  51609. do {
  51610. again = false;
  51611. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  51612. removeNode(p);
  51613. p = end = p.prev;
  51614. if (p === p.next)
  51615. return null;
  51616. again = true;
  51617. }
  51618. else {
  51619. p = p.next;
  51620. }
  51621. } while (again || p !== end);
  51622. return end;
  51623. }
  51624. // main ear slicing loop which triangulates a polygon (given as a linked list)
  51625. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  51626. if (!ear)
  51627. return;
  51628. // interlink polygon nodes in z-order
  51629. if (!pass && size)
  51630. indexCurve(ear, minX, minY, size);
  51631. var stop = ear, prev, next;
  51632. // iterate through ears, slicing them one by one
  51633. while (ear.prev !== ear.next) {
  51634. prev = ear.prev;
  51635. next = ear.next;
  51636. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  51637. // cut off the triangle
  51638. triangles.push(prev.i / dim);
  51639. triangles.push(ear.i / dim);
  51640. triangles.push(next.i / dim);
  51641. removeNode(ear);
  51642. // skipping the next vertice leads to less sliver triangles
  51643. ear = next.next;
  51644. stop = next.next;
  51645. continue;
  51646. }
  51647. ear = next;
  51648. // if we looped through the whole remaining polygon and can't find any more ears
  51649. if (ear === stop) {
  51650. // try filtering points and slicing again
  51651. if (!pass) {
  51652. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  51653. // if this didn't work, try curing all small self-intersections locally
  51654. }
  51655. else if (pass === 1) {
  51656. ear = cureLocalIntersections(ear, triangles, dim);
  51657. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  51658. // as a last resort, try splitting the remaining polygon into two
  51659. }
  51660. else if (pass === 2) {
  51661. splitEarcut(ear, triangles, dim, minX, minY, size);
  51662. }
  51663. break;
  51664. }
  51665. }
  51666. }
  51667. // check whether a polygon node forms a valid ear with adjacent nodes
  51668. function isEar(ear) {
  51669. var a = ear.prev, b = ear, c = ear.next;
  51670. if (area(a, b, c) >= 0)
  51671. return false; // reflex, can't be an ear
  51672. // now make sure we don't have other points inside the potential ear
  51673. var p = ear.next.next;
  51674. while (p !== ear.prev) {
  51675. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51676. area(p.prev, p, p.next) >= 0)
  51677. return false;
  51678. p = p.next;
  51679. }
  51680. return true;
  51681. }
  51682. function isEarHashed(ear, minX, minY, size) {
  51683. var a = ear.prev, b = ear, c = ear.next;
  51684. if (area(a, b, c) >= 0)
  51685. return false; // reflex, can't be an ear
  51686. // triangle bbox; min & max are calculated like this for speed
  51687. 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);
  51688. // z-order range for the current triangle bbox;
  51689. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  51690. // first look for points inside the triangle in increasing z-order
  51691. var p = ear.nextZ;
  51692. while (p && p.z <= maxZ) {
  51693. if (p !== ear.prev &&
  51694. p !== ear.next &&
  51695. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51696. area(p.prev, p, p.next) >= 0)
  51697. return false;
  51698. p = p.nextZ;
  51699. }
  51700. // then look for points in decreasing z-order
  51701. p = ear.prevZ;
  51702. while (p && p.z >= minZ) {
  51703. if (p !== ear.prev &&
  51704. p !== ear.next &&
  51705. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51706. area(p.prev, p, p.next) >= 0)
  51707. return false;
  51708. p = p.prevZ;
  51709. }
  51710. return true;
  51711. }
  51712. // go through all polygon nodes and cure small local self-intersections
  51713. function cureLocalIntersections(start, triangles, dim) {
  51714. var p = start;
  51715. do {
  51716. var a = p.prev, b = p.next.next;
  51717. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  51718. triangles.push(a.i / dim);
  51719. triangles.push(p.i / dim);
  51720. triangles.push(b.i / dim);
  51721. // remove two nodes involved
  51722. removeNode(p);
  51723. removeNode(p.next);
  51724. p = start = b;
  51725. }
  51726. p = p.next;
  51727. } while (p !== start);
  51728. return p;
  51729. }
  51730. // try splitting polygon into two and triangulate them independently
  51731. function splitEarcut(start, triangles, dim, minX, minY, size) {
  51732. // look for a valid diagonal that divides the polygon into two
  51733. var a = start;
  51734. do {
  51735. var b = a.next.next;
  51736. while (b !== a.prev) {
  51737. if (a.i !== b.i && isValidDiagonal(a, b)) {
  51738. // split the polygon in two by the diagonal
  51739. var c = splitPolygon(a, b);
  51740. // filter colinear points around the cuts
  51741. a = filterPoints(a, a.next);
  51742. c = filterPoints(c, c.next);
  51743. // run earcut on each half
  51744. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  51745. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  51746. return;
  51747. }
  51748. b = b.next;
  51749. }
  51750. a = a.next;
  51751. } while (a !== start);
  51752. }
  51753. // link every hole into the outer loop, producing a single-ring polygon without holes
  51754. function eliminateHoles(data, holeIndices, outerNode, dim) {
  51755. var queue = [], i, len, start, end, list;
  51756. for (i = 0, len = holeIndices.length; i < len; i++) {
  51757. start = holeIndices[i] * dim;
  51758. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  51759. list = linkedList(data, start, end, dim, false);
  51760. if (list === list.next)
  51761. list.steiner = true;
  51762. queue.push(getLeftmost(list));
  51763. }
  51764. queue.sort(compareX);
  51765. // process holes from left to right
  51766. for (i = 0; i < queue.length; i++) {
  51767. eliminateHole(queue[i], outerNode);
  51768. outerNode = filterPoints(outerNode, outerNode.next);
  51769. }
  51770. return outerNode;
  51771. }
  51772. function compareX(a, b) {
  51773. return a.x - b.x;
  51774. }
  51775. // find a bridge between vertices that connects hole with an outer ring and and link it
  51776. function eliminateHole(hole, outerNode) {
  51777. outerNode = findHoleBridge(hole, outerNode);
  51778. if (outerNode) {
  51779. var b = splitPolygon(outerNode, hole);
  51780. filterPoints(b, b.next);
  51781. }
  51782. }
  51783. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  51784. function findHoleBridge(hole, outerNode) {
  51785. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  51786. // find a segment intersected by a ray from the hole's leftmost point to the left;
  51787. // segment's endpoint with lesser x will be potential connection point
  51788. do {
  51789. if (hy <= p.y && hy >= p.next.y) {
  51790. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  51791. if (x <= hx && x > qx) {
  51792. qx = x;
  51793. if (x === hx) {
  51794. if (hy === p.y)
  51795. return p;
  51796. if (hy === p.next.y)
  51797. return p.next;
  51798. }
  51799. m = p.x < p.next.x ? p : p.next;
  51800. }
  51801. }
  51802. p = p.next;
  51803. } while (p !== outerNode);
  51804. if (!m)
  51805. return null;
  51806. if (hx === qx)
  51807. return m.prev; // hole touches outer segment; pick lower endpoint
  51808. // look for points inside the triangle of hole point, segment intersection and endpoint;
  51809. // if there are no points found, we have a valid connection;
  51810. // otherwise choose the point of the minimum angle with the ray as connection point
  51811. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  51812. p = m.next;
  51813. while (p !== stop) {
  51814. if (hx >= p.x &&
  51815. p.x >= mx &&
  51816. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  51817. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  51818. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  51819. m = p;
  51820. tanMin = tan;
  51821. }
  51822. }
  51823. p = p.next;
  51824. }
  51825. return m;
  51826. }
  51827. // interlink polygon nodes in z-order
  51828. function indexCurve(start, minX, minY, size) {
  51829. var p = start;
  51830. do {
  51831. if (p.z === null)
  51832. p.z = zOrder(p.x, p.y, minX, minY, size);
  51833. p.prevZ = p.prev;
  51834. p.nextZ = p.next;
  51835. p = p.next;
  51836. } while (p !== start);
  51837. p.prevZ.nextZ = null;
  51838. p.prevZ = null;
  51839. sortLinked(p);
  51840. }
  51841. // Simon Tatham's linked list merge sort algorithm
  51842. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  51843. function sortLinked(list) {
  51844. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  51845. do {
  51846. p = list;
  51847. list = null;
  51848. tail = null;
  51849. numMerges = 0;
  51850. while (p) {
  51851. numMerges++;
  51852. q = p;
  51853. pSize = 0;
  51854. for (i = 0; i < inSize; i++) {
  51855. pSize++;
  51856. q = q.nextZ;
  51857. if (!q)
  51858. break;
  51859. }
  51860. qSize = inSize;
  51861. while (pSize > 0 || (qSize > 0 && q)) {
  51862. if (pSize === 0) {
  51863. e = q;
  51864. q = q.nextZ;
  51865. qSize--;
  51866. }
  51867. else if (qSize === 0 || !q) {
  51868. e = p;
  51869. p = p.nextZ;
  51870. pSize--;
  51871. }
  51872. else if (p.z <= q.z) {
  51873. e = p;
  51874. p = p.nextZ;
  51875. pSize--;
  51876. }
  51877. else {
  51878. e = q;
  51879. q = q.nextZ;
  51880. qSize--;
  51881. }
  51882. if (tail)
  51883. tail.nextZ = e;
  51884. else
  51885. list = e;
  51886. e.prevZ = tail;
  51887. tail = e;
  51888. }
  51889. p = q;
  51890. }
  51891. tail.nextZ = null;
  51892. inSize *= 2;
  51893. } while (numMerges > 1);
  51894. return list;
  51895. }
  51896. // z-order of a point given coords and size of the data bounding box
  51897. function zOrder(x, y, minX, minY, size) {
  51898. // coords are transformed into non-negative 15-bit integer range
  51899. x = 32767 * (x - minX) / size;
  51900. y = 32767 * (y - minY) / size;
  51901. x = (x | (x << 8)) & 0x00FF00FF;
  51902. x = (x | (x << 4)) & 0x0F0F0F0F;
  51903. x = (x | (x << 2)) & 0x33333333;
  51904. x = (x | (x << 1)) & 0x55555555;
  51905. y = (y | (y << 8)) & 0x00FF00FF;
  51906. y = (y | (y << 4)) & 0x0F0F0F0F;
  51907. y = (y | (y << 2)) & 0x33333333;
  51908. y = (y | (y << 1)) & 0x55555555;
  51909. return x | (y << 1);
  51910. }
  51911. // find the leftmost node of a polygon ring
  51912. function getLeftmost(start) {
  51913. var p = start, leftmost = start;
  51914. do {
  51915. if (p.x < leftmost.x)
  51916. leftmost = p;
  51917. p = p.next;
  51918. } while (p !== start);
  51919. return leftmost;
  51920. }
  51921. // check if a point lies within a convex triangle
  51922. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  51923. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  51924. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  51925. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  51926. }
  51927. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  51928. function isValidDiagonal(a, b) {
  51929. return a.next.i !== b.i &&
  51930. a.prev.i !== b.i &&
  51931. !intersectsPolygon(a, b) &&
  51932. locallyInside(a, b) &&
  51933. locallyInside(b, a) &&
  51934. middleInside(a, b);
  51935. }
  51936. // signed area of a triangle
  51937. function area(p, q, r) {
  51938. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  51939. }
  51940. // check if two points are equal
  51941. function equals(p1, p2) {
  51942. return p1.x === p2.x && p1.y === p2.y;
  51943. }
  51944. // check if two segments intersect
  51945. function intersects(p1, q1, p2, q2) {
  51946. if ((equals(p1, q1) && equals(p2, q2)) ||
  51947. (equals(p1, q2) && equals(p2, q1)))
  51948. return true;
  51949. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  51950. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  51951. }
  51952. // check if a polygon diagonal intersects any polygon segments
  51953. function intersectsPolygon(a, b) {
  51954. var p = a;
  51955. do {
  51956. if (p.i !== a.i &&
  51957. p.next.i !== a.i &&
  51958. p.i !== b.i &&
  51959. p.next.i !== b.i &&
  51960. intersects(p, p.next, a, b))
  51961. return true;
  51962. p = p.next;
  51963. } while (p !== a);
  51964. return false;
  51965. }
  51966. // check if a polygon diagonal is locally inside the polygon
  51967. function locallyInside(a, b) {
  51968. return area(a.prev, a, a.next) < 0
  51969. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  51970. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  51971. }
  51972. // check if the middle point of a polygon diagonal is inside the polygon
  51973. function middleInside(a, b) {
  51974. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  51975. do {
  51976. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  51977. inside = !inside;
  51978. p = p.next;
  51979. } while (p !== a);
  51980. return inside;
  51981. }
  51982. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  51983. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  51984. function splitPolygon(a, b) {
  51985. 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;
  51986. a.next = b;
  51987. b.prev = a;
  51988. a2.next = an;
  51989. an.prev = a2;
  51990. b2.next = a2;
  51991. a2.prev = b2;
  51992. bp.next = b2;
  51993. b2.prev = bp;
  51994. return b2;
  51995. }
  51996. // create a node and optionally link it with previous one (in a circular doubly linked list)
  51997. function insertNode(i, x, y, last) {
  51998. var p = new Node(i, x, y);
  51999. if (!last) {
  52000. p.prev = p;
  52001. p.next = p;
  52002. }
  52003. else {
  52004. p.next = last.next;
  52005. p.prev = last;
  52006. last.next.prev = p;
  52007. last.next = p;
  52008. }
  52009. return p;
  52010. }
  52011. function removeNode(p) {
  52012. p.next.prev = p.prev;
  52013. p.prev.next = p.next;
  52014. if (p.prevZ)
  52015. p.prevZ.nextZ = p.nextZ;
  52016. if (p.nextZ)
  52017. p.nextZ.prevZ = p.prevZ;
  52018. }
  52019. function Node(i, x, y) {
  52020. // vertice index in coordinates array
  52021. this.i = i;
  52022. // vertex coordinates
  52023. this.x = x;
  52024. this.y = y;
  52025. // previous and next vertice nodes in a polygon ring
  52026. this.prev = null;
  52027. this.next = null;
  52028. // z-order curve value
  52029. this.z = null;
  52030. // previous and next nodes in z-order
  52031. this.prevZ = null;
  52032. this.nextZ = null;
  52033. // indicates whether this is a steiner point
  52034. this.steiner = false;
  52035. }
  52036. /**
  52037. * return a percentage difference between the polygon area and its triangulation area;
  52038. * used to verify correctness of triangulation
  52039. */
  52040. function deviation(data, holeIndices, dim, triangles) {
  52041. var hasHoles = holeIndices && holeIndices.length;
  52042. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  52043. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  52044. if (hasHoles) {
  52045. for (var i = 0, len = holeIndices.length; i < len; i++) {
  52046. var start = holeIndices[i] * dim;
  52047. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  52048. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  52049. }
  52050. }
  52051. var trianglesArea = 0;
  52052. for (i = 0; i < triangles.length; i += 3) {
  52053. var a = triangles[i] * dim;
  52054. var b = triangles[i + 1] * dim;
  52055. var c = triangles[i + 2] * dim;
  52056. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  52057. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  52058. }
  52059. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  52060. }
  52061. Earcut.deviation = deviation;
  52062. ;
  52063. function signedArea(data, start, end, dim) {
  52064. var sum = 0;
  52065. for (var i = start, j = end - dim; i < end; i += dim) {
  52066. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  52067. j = i;
  52068. }
  52069. return sum;
  52070. }
  52071. /**
  52072. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  52073. */
  52074. function flatten(data) {
  52075. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  52076. for (var i = 0; i < data.length; i++) {
  52077. for (var j = 0; j < data[i].length; j++) {
  52078. for (var d = 0; d < dim; d++)
  52079. result.vertices.push(data[i][j][d]);
  52080. }
  52081. if (i > 0) {
  52082. holeIndex += data[i - 1].length;
  52083. result.holes.push(holeIndex);
  52084. }
  52085. }
  52086. return result;
  52087. }
  52088. Earcut.flatten = flatten;
  52089. ;
  52090. })(Earcut || (Earcut = {}));
  52091. //# sourceMappingURL=babylon.earcut.js.map
  52092. /// <reference path="..\Math\babylon.math.ts" />
  52093. var BABYLON;
  52094. (function (BABYLON) {
  52095. var IndexedVector2 = (function (_super) {
  52096. __extends(IndexedVector2, _super);
  52097. function IndexedVector2(original, index) {
  52098. var _this = _super.call(this, original.x, original.y) || this;
  52099. _this.index = index;
  52100. return _this;
  52101. }
  52102. return IndexedVector2;
  52103. }(BABYLON.Vector2));
  52104. var PolygonPoints = (function () {
  52105. function PolygonPoints() {
  52106. this.elements = new Array();
  52107. }
  52108. PolygonPoints.prototype.add = function (originalPoints) {
  52109. var _this = this;
  52110. var result = new Array();
  52111. originalPoints.forEach(function (point) {
  52112. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  52113. var newPoint = new IndexedVector2(point, _this.elements.length);
  52114. result.push(newPoint);
  52115. _this.elements.push(newPoint);
  52116. }
  52117. });
  52118. return result;
  52119. };
  52120. PolygonPoints.prototype.computeBounds = function () {
  52121. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  52122. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  52123. this.elements.forEach(function (point) {
  52124. // x
  52125. if (point.x < lmin.x) {
  52126. lmin.x = point.x;
  52127. }
  52128. else if (point.x > lmax.x) {
  52129. lmax.x = point.x;
  52130. }
  52131. // y
  52132. if (point.y < lmin.y) {
  52133. lmin.y = point.y;
  52134. }
  52135. else if (point.y > lmax.y) {
  52136. lmax.y = point.y;
  52137. }
  52138. });
  52139. return {
  52140. min: lmin,
  52141. max: lmax,
  52142. width: lmax.x - lmin.x,
  52143. height: lmax.y - lmin.y
  52144. };
  52145. };
  52146. return PolygonPoints;
  52147. }());
  52148. var Polygon = (function () {
  52149. function Polygon() {
  52150. }
  52151. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  52152. return [
  52153. new BABYLON.Vector2(xmin, ymin),
  52154. new BABYLON.Vector2(xmax, ymin),
  52155. new BABYLON.Vector2(xmax, ymax),
  52156. new BABYLON.Vector2(xmin, ymax)
  52157. ];
  52158. };
  52159. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  52160. if (cx === void 0) { cx = 0; }
  52161. if (cy === void 0) { cy = 0; }
  52162. if (numberOfSides === void 0) { numberOfSides = 32; }
  52163. var result = new Array();
  52164. var angle = 0;
  52165. var increment = (Math.PI * 2) / numberOfSides;
  52166. for (var i = 0; i < numberOfSides; i++) {
  52167. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  52168. angle -= increment;
  52169. }
  52170. return result;
  52171. };
  52172. Polygon.Parse = function (input) {
  52173. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  52174. var i, result = [];
  52175. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  52176. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  52177. }
  52178. return result;
  52179. };
  52180. Polygon.StartingAt = function (x, y) {
  52181. return BABYLON.Path2.StartingAt(x, y);
  52182. };
  52183. return Polygon;
  52184. }());
  52185. BABYLON.Polygon = Polygon;
  52186. var PolygonMeshBuilder = (function () {
  52187. function PolygonMeshBuilder(name, contours, scene) {
  52188. this._points = new PolygonPoints();
  52189. this._outlinepoints = new PolygonPoints();
  52190. this._holes = [];
  52191. this._epoints = new Array();
  52192. this._eholes = new Array();
  52193. this._name = name;
  52194. this._scene = scene;
  52195. var points;
  52196. if (contours instanceof BABYLON.Path2) {
  52197. points = contours.getPoints();
  52198. }
  52199. else {
  52200. points = contours;
  52201. }
  52202. this._addToepoint(points);
  52203. this._points.add(points);
  52204. this._outlinepoints.add(points);
  52205. }
  52206. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  52207. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  52208. var p = points_1[_i];
  52209. this._epoints.push(p.x, p.y);
  52210. }
  52211. };
  52212. PolygonMeshBuilder.prototype.addHole = function (hole) {
  52213. this._points.add(hole);
  52214. var holepoints = new PolygonPoints();
  52215. holepoints.add(hole);
  52216. this._holes.push(holepoints);
  52217. this._eholes.push(this._epoints.length / 2);
  52218. this._addToepoint(hole);
  52219. return this;
  52220. };
  52221. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  52222. var _this = this;
  52223. if (updatable === void 0) { updatable = false; }
  52224. var result = new BABYLON.Mesh(this._name, this._scene);
  52225. var normals = [];
  52226. var positions = [];
  52227. var uvs = [];
  52228. var bounds = this._points.computeBounds();
  52229. this._points.elements.forEach(function (p) {
  52230. normals.push(0, 1.0, 0);
  52231. positions.push(p.x, 0, p.y);
  52232. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  52233. });
  52234. var indices = [];
  52235. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  52236. for (var i = 0; i < res.length; i++) {
  52237. indices.push(res[i]);
  52238. }
  52239. if (depth > 0) {
  52240. var positionscount = (positions.length / 3); //get the current pointcount
  52241. this._points.elements.forEach(function (p) {
  52242. normals.push(0, -1.0, 0);
  52243. positions.push(p.x, -depth, p.y);
  52244. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  52245. });
  52246. var totalCount = indices.length;
  52247. for (var i = 0; i < totalCount; i += 3) {
  52248. var i0 = indices[i + 0];
  52249. var i1 = indices[i + 1];
  52250. var i2 = indices[i + 2];
  52251. indices.push(i2 + positionscount);
  52252. indices.push(i1 + positionscount);
  52253. indices.push(i0 + positionscount);
  52254. }
  52255. //Add the sides
  52256. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  52257. this._holes.forEach(function (hole) {
  52258. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  52259. });
  52260. }
  52261. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  52262. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  52263. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  52264. result.setIndices(indices);
  52265. return result;
  52266. };
  52267. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  52268. var StartIndex = positions.length / 3;
  52269. var ulength = 0;
  52270. for (var i = 0; i < points.elements.length; i++) {
  52271. var p = points.elements[i];
  52272. var p1;
  52273. if ((i + 1) > points.elements.length - 1) {
  52274. p1 = points.elements[0];
  52275. }
  52276. else {
  52277. p1 = points.elements[i + 1];
  52278. }
  52279. positions.push(p.x, 0, p.y);
  52280. positions.push(p.x, -depth, p.y);
  52281. positions.push(p1.x, 0, p1.y);
  52282. positions.push(p1.x, -depth, p1.y);
  52283. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  52284. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  52285. var v3 = v2.subtract(v1);
  52286. var v4 = new BABYLON.Vector3(0, 1, 0);
  52287. var vn = BABYLON.Vector3.Cross(v3, v4);
  52288. vn = vn.normalize();
  52289. uvs.push(ulength / bounds.width, 0);
  52290. uvs.push(ulength / bounds.width, 1);
  52291. ulength += v3.length();
  52292. uvs.push((ulength / bounds.width), 0);
  52293. uvs.push((ulength / bounds.width), 1);
  52294. if (!flip) {
  52295. normals.push(-vn.x, -vn.y, -vn.z);
  52296. normals.push(-vn.x, -vn.y, -vn.z);
  52297. normals.push(-vn.x, -vn.y, -vn.z);
  52298. normals.push(-vn.x, -vn.y, -vn.z);
  52299. indices.push(StartIndex);
  52300. indices.push(StartIndex + 1);
  52301. indices.push(StartIndex + 2);
  52302. indices.push(StartIndex + 1);
  52303. indices.push(StartIndex + 3);
  52304. indices.push(StartIndex + 2);
  52305. }
  52306. else {
  52307. normals.push(vn.x, vn.y, vn.z);
  52308. normals.push(vn.x, vn.y, vn.z);
  52309. normals.push(vn.x, vn.y, vn.z);
  52310. normals.push(vn.x, vn.y, vn.z);
  52311. indices.push(StartIndex);
  52312. indices.push(StartIndex + 2);
  52313. indices.push(StartIndex + 1);
  52314. indices.push(StartIndex + 1);
  52315. indices.push(StartIndex + 2);
  52316. indices.push(StartIndex + 3);
  52317. }
  52318. StartIndex += 4;
  52319. }
  52320. ;
  52321. };
  52322. return PolygonMeshBuilder;
  52323. }());
  52324. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  52325. })(BABYLON || (BABYLON = {}));
  52326. //# sourceMappingURL=babylon.polygonMesh.js.map
  52327. var BABYLON;
  52328. (function (BABYLON) {
  52329. // Unique ID when we import meshes from Babylon to CSG
  52330. var currentCSGMeshId = 0;
  52331. // # class Vertex
  52332. // Represents a vertex of a polygon. Use your own vertex class instead of this
  52333. // one to provide additional features like texture coordinates and vertex
  52334. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  52335. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  52336. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  52337. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  52338. // is not used anywhere else.
  52339. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  52340. var Vertex = (function () {
  52341. function Vertex(pos, normal, uv) {
  52342. this.pos = pos;
  52343. this.normal = normal;
  52344. this.uv = uv;
  52345. }
  52346. Vertex.prototype.clone = function () {
  52347. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  52348. };
  52349. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  52350. // orientation of a polygon is flipped.
  52351. Vertex.prototype.flip = function () {
  52352. this.normal = this.normal.scale(-1);
  52353. };
  52354. // Create a new vertex between this vertex and `other` by linearly
  52355. // interpolating all properties using a parameter of `t`. Subclasses should
  52356. // override this to interpolate additional properties.
  52357. Vertex.prototype.interpolate = function (other, t) {
  52358. 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));
  52359. };
  52360. return Vertex;
  52361. }());
  52362. // # class Plane
  52363. // Represents a plane in 3D space.
  52364. var Plane = (function () {
  52365. function Plane(normal, w) {
  52366. this.normal = normal;
  52367. this.w = w;
  52368. }
  52369. Plane.FromPoints = function (a, b, c) {
  52370. var v0 = c.subtract(a);
  52371. var v1 = b.subtract(a);
  52372. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  52373. return null;
  52374. }
  52375. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  52376. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  52377. };
  52378. Plane.prototype.clone = function () {
  52379. return new Plane(this.normal.clone(), this.w);
  52380. };
  52381. Plane.prototype.flip = function () {
  52382. this.normal.scaleInPlace(-1);
  52383. this.w = -this.w;
  52384. };
  52385. // Split `polygon` by this plane if needed, then put the polygon or polygon
  52386. // fragments in the appropriate lists. Coplanar polygons go into either
  52387. // `coplanarFront` or `coplanarBack` depending on their orientation with
  52388. // respect to this plane. Polygons in front or in back of this plane go into
  52389. // either `front` or `back`.
  52390. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  52391. var COPLANAR = 0;
  52392. var FRONT = 1;
  52393. var BACK = 2;
  52394. var SPANNING = 3;
  52395. // Classify each point as well as the entire polygon into one of the above
  52396. // four classes.
  52397. var polygonType = 0;
  52398. var types = [];
  52399. var i;
  52400. var t;
  52401. for (i = 0; i < polygon.vertices.length; i++) {
  52402. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  52403. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  52404. polygonType |= type;
  52405. types.push(type);
  52406. }
  52407. // Put the polygon in the correct list, splitting it when necessary.
  52408. switch (polygonType) {
  52409. case COPLANAR:
  52410. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  52411. break;
  52412. case FRONT:
  52413. front.push(polygon);
  52414. break;
  52415. case BACK:
  52416. back.push(polygon);
  52417. break;
  52418. case SPANNING:
  52419. var f = [], b = [];
  52420. for (i = 0; i < polygon.vertices.length; i++) {
  52421. var j = (i + 1) % polygon.vertices.length;
  52422. var ti = types[i], tj = types[j];
  52423. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  52424. if (ti !== BACK)
  52425. f.push(vi);
  52426. if (ti !== FRONT)
  52427. b.push(ti !== BACK ? vi.clone() : vi);
  52428. if ((ti | tj) === SPANNING) {
  52429. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  52430. var v = vi.interpolate(vj, t);
  52431. f.push(v);
  52432. b.push(v.clone());
  52433. }
  52434. }
  52435. var poly;
  52436. if (f.length >= 3) {
  52437. poly = new Polygon(f, polygon.shared);
  52438. if (poly.plane)
  52439. front.push(poly);
  52440. }
  52441. if (b.length >= 3) {
  52442. poly = new Polygon(b, polygon.shared);
  52443. if (poly.plane)
  52444. back.push(poly);
  52445. }
  52446. break;
  52447. }
  52448. };
  52449. return Plane;
  52450. }());
  52451. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  52452. // point is on the plane.
  52453. Plane.EPSILON = 1e-5;
  52454. // # class Polygon
  52455. // Represents a convex polygon. The vertices used to initialize a polygon must
  52456. // be coplanar and form a convex loop.
  52457. //
  52458. // Each convex polygon has a `shared` property, which is shared between all
  52459. // polygons that are clones of each other or were split from the same polygon.
  52460. // This can be used to define per-polygon properties (such as surface color).
  52461. var Polygon = (function () {
  52462. function Polygon(vertices, shared) {
  52463. this.vertices = vertices;
  52464. this.shared = shared;
  52465. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  52466. }
  52467. Polygon.prototype.clone = function () {
  52468. var vertices = this.vertices.map(function (v) { return v.clone(); });
  52469. return new Polygon(vertices, this.shared);
  52470. };
  52471. Polygon.prototype.flip = function () {
  52472. this.vertices.reverse().map(function (v) { v.flip(); });
  52473. this.plane.flip();
  52474. };
  52475. return Polygon;
  52476. }());
  52477. // # class Node
  52478. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  52479. // by picking a polygon to split along. That polygon (and all other coplanar
  52480. // polygons) are added directly to that node and the other polygons are added to
  52481. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  52482. // no distinction between internal and leaf nodes.
  52483. var Node = (function () {
  52484. function Node(polygons) {
  52485. this.plane = null;
  52486. this.front = null;
  52487. this.back = null;
  52488. this.polygons = [];
  52489. if (polygons) {
  52490. this.build(polygons);
  52491. }
  52492. }
  52493. Node.prototype.clone = function () {
  52494. var node = new Node();
  52495. node.plane = this.plane && this.plane.clone();
  52496. node.front = this.front && this.front.clone();
  52497. node.back = this.back && this.back.clone();
  52498. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  52499. return node;
  52500. };
  52501. // Convert solid space to empty space and empty space to solid space.
  52502. Node.prototype.invert = function () {
  52503. for (var i = 0; i < this.polygons.length; i++) {
  52504. this.polygons[i].flip();
  52505. }
  52506. if (this.plane) {
  52507. this.plane.flip();
  52508. }
  52509. if (this.front) {
  52510. this.front.invert();
  52511. }
  52512. if (this.back) {
  52513. this.back.invert();
  52514. }
  52515. var temp = this.front;
  52516. this.front = this.back;
  52517. this.back = temp;
  52518. };
  52519. // Recursively remove all polygons in `polygons` that are inside this BSP
  52520. // tree.
  52521. Node.prototype.clipPolygons = function (polygons) {
  52522. if (!this.plane)
  52523. return polygons.slice();
  52524. var front = [], back = [];
  52525. for (var i = 0; i < polygons.length; i++) {
  52526. this.plane.splitPolygon(polygons[i], front, back, front, back);
  52527. }
  52528. if (this.front) {
  52529. front = this.front.clipPolygons(front);
  52530. }
  52531. if (this.back) {
  52532. back = this.back.clipPolygons(back);
  52533. }
  52534. else {
  52535. back = [];
  52536. }
  52537. return front.concat(back);
  52538. };
  52539. // Remove all polygons in this BSP tree that are inside the other BSP tree
  52540. // `bsp`.
  52541. Node.prototype.clipTo = function (bsp) {
  52542. this.polygons = bsp.clipPolygons(this.polygons);
  52543. if (this.front)
  52544. this.front.clipTo(bsp);
  52545. if (this.back)
  52546. this.back.clipTo(bsp);
  52547. };
  52548. // Return a list of all polygons in this BSP tree.
  52549. Node.prototype.allPolygons = function () {
  52550. var polygons = this.polygons.slice();
  52551. if (this.front)
  52552. polygons = polygons.concat(this.front.allPolygons());
  52553. if (this.back)
  52554. polygons = polygons.concat(this.back.allPolygons());
  52555. return polygons;
  52556. };
  52557. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  52558. // new polygons are filtered down to the bottom of the tree and become new
  52559. // nodes there. Each set of polygons is partitioned using the first polygon
  52560. // (no heuristic is used to pick a good split).
  52561. Node.prototype.build = function (polygons) {
  52562. if (!polygons.length)
  52563. return;
  52564. if (!this.plane)
  52565. this.plane = polygons[0].plane.clone();
  52566. var front = [], back = [];
  52567. for (var i = 0; i < polygons.length; i++) {
  52568. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  52569. }
  52570. if (front.length) {
  52571. if (!this.front)
  52572. this.front = new Node();
  52573. this.front.build(front);
  52574. }
  52575. if (back.length) {
  52576. if (!this.back)
  52577. this.back = new Node();
  52578. this.back.build(back);
  52579. }
  52580. };
  52581. return Node;
  52582. }());
  52583. var CSG = (function () {
  52584. function CSG() {
  52585. this.polygons = new Array();
  52586. }
  52587. // Convert BABYLON.Mesh to BABYLON.CSG
  52588. CSG.FromMesh = function (mesh) {
  52589. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  52590. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  52591. if (mesh instanceof BABYLON.Mesh) {
  52592. mesh.computeWorldMatrix(true);
  52593. matrix = mesh.getWorldMatrix();
  52594. meshPosition = mesh.position.clone();
  52595. meshRotation = mesh.rotation.clone();
  52596. if (mesh.rotationQuaternion) {
  52597. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  52598. }
  52599. meshScaling = mesh.scaling.clone();
  52600. }
  52601. else {
  52602. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  52603. }
  52604. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52605. var subMeshes = mesh.subMeshes;
  52606. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  52607. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  52608. vertices = [];
  52609. for (var j = 0; j < 3; j++) {
  52610. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  52611. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  52612. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  52613. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  52614. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  52615. vertex = new Vertex(position, normal, uv);
  52616. vertices.push(vertex);
  52617. }
  52618. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  52619. // To handle the case of degenerated triangle
  52620. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  52621. if (polygon.plane)
  52622. polygons.push(polygon);
  52623. }
  52624. }
  52625. var csg = CSG.FromPolygons(polygons);
  52626. csg.matrix = matrix;
  52627. csg.position = meshPosition;
  52628. csg.rotation = meshRotation;
  52629. csg.scaling = meshScaling;
  52630. csg.rotationQuaternion = meshRotationQuaternion;
  52631. currentCSGMeshId++;
  52632. return csg;
  52633. };
  52634. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  52635. CSG.FromPolygons = function (polygons) {
  52636. var csg = new CSG();
  52637. csg.polygons = polygons;
  52638. return csg;
  52639. };
  52640. CSG.prototype.clone = function () {
  52641. var csg = new CSG();
  52642. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  52643. csg.copyTransformAttributes(this);
  52644. return csg;
  52645. };
  52646. CSG.prototype.toPolygons = function () {
  52647. return this.polygons;
  52648. };
  52649. CSG.prototype.union = function (csg) {
  52650. var a = new Node(this.clone().polygons);
  52651. var b = new Node(csg.clone().polygons);
  52652. a.clipTo(b);
  52653. b.clipTo(a);
  52654. b.invert();
  52655. b.clipTo(a);
  52656. b.invert();
  52657. a.build(b.allPolygons());
  52658. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52659. };
  52660. CSG.prototype.unionInPlace = function (csg) {
  52661. var a = new Node(this.polygons);
  52662. var b = new Node(csg.polygons);
  52663. a.clipTo(b);
  52664. b.clipTo(a);
  52665. b.invert();
  52666. b.clipTo(a);
  52667. b.invert();
  52668. a.build(b.allPolygons());
  52669. this.polygons = a.allPolygons();
  52670. };
  52671. CSG.prototype.subtract = function (csg) {
  52672. var a = new Node(this.clone().polygons);
  52673. var b = new Node(csg.clone().polygons);
  52674. a.invert();
  52675. a.clipTo(b);
  52676. b.clipTo(a);
  52677. b.invert();
  52678. b.clipTo(a);
  52679. b.invert();
  52680. a.build(b.allPolygons());
  52681. a.invert();
  52682. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52683. };
  52684. CSG.prototype.subtractInPlace = function (csg) {
  52685. var a = new Node(this.polygons);
  52686. var b = new Node(csg.polygons);
  52687. a.invert();
  52688. a.clipTo(b);
  52689. b.clipTo(a);
  52690. b.invert();
  52691. b.clipTo(a);
  52692. b.invert();
  52693. a.build(b.allPolygons());
  52694. a.invert();
  52695. this.polygons = a.allPolygons();
  52696. };
  52697. CSG.prototype.intersect = function (csg) {
  52698. var a = new Node(this.clone().polygons);
  52699. var b = new Node(csg.clone().polygons);
  52700. a.invert();
  52701. b.clipTo(a);
  52702. b.invert();
  52703. a.clipTo(b);
  52704. b.clipTo(a);
  52705. a.build(b.allPolygons());
  52706. a.invert();
  52707. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52708. };
  52709. CSG.prototype.intersectInPlace = function (csg) {
  52710. var a = new Node(this.polygons);
  52711. var b = new Node(csg.polygons);
  52712. a.invert();
  52713. b.clipTo(a);
  52714. b.invert();
  52715. a.clipTo(b);
  52716. b.clipTo(a);
  52717. a.build(b.allPolygons());
  52718. a.invert();
  52719. this.polygons = a.allPolygons();
  52720. };
  52721. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  52722. // not modified.
  52723. CSG.prototype.inverse = function () {
  52724. var csg = this.clone();
  52725. csg.inverseInPlace();
  52726. return csg;
  52727. };
  52728. CSG.prototype.inverseInPlace = function () {
  52729. this.polygons.map(function (p) { p.flip(); });
  52730. };
  52731. // This is used to keep meshes transformations so they can be restored
  52732. // when we build back a Babylon Mesh
  52733. // NB : All CSG operations are performed in world coordinates
  52734. CSG.prototype.copyTransformAttributes = function (csg) {
  52735. this.matrix = csg.matrix;
  52736. this.position = csg.position;
  52737. this.rotation = csg.rotation;
  52738. this.scaling = csg.scaling;
  52739. this.rotationQuaternion = csg.rotationQuaternion;
  52740. return this;
  52741. };
  52742. // Build Raw mesh from CSG
  52743. // Coordinates here are in world space
  52744. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  52745. var matrix = this.matrix.clone();
  52746. matrix.invert();
  52747. 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;
  52748. if (keepSubMeshes) {
  52749. // Sort Polygons, since subMeshes are indices range
  52750. polygons.sort(function (a, b) {
  52751. if (a.shared.meshId === b.shared.meshId) {
  52752. return a.shared.subMeshId - b.shared.subMeshId;
  52753. }
  52754. else {
  52755. return a.shared.meshId - b.shared.meshId;
  52756. }
  52757. });
  52758. }
  52759. for (var i = 0, il = polygons.length; i < il; i++) {
  52760. polygon = polygons[i];
  52761. // Building SubMeshes
  52762. if (!subMesh_dict[polygon.shared.meshId]) {
  52763. subMesh_dict[polygon.shared.meshId] = {};
  52764. }
  52765. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  52766. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  52767. indexStart: +Infinity,
  52768. indexEnd: -Infinity,
  52769. materialIndex: polygon.shared.materialIndex
  52770. };
  52771. }
  52772. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  52773. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  52774. polygonIndices[0] = 0;
  52775. polygonIndices[1] = j - 1;
  52776. polygonIndices[2] = j;
  52777. for (var k = 0; k < 3; k++) {
  52778. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  52779. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  52780. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  52781. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  52782. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  52783. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  52784. // Check if 2 points can be merged
  52785. if (!(typeof vertex_idx !== 'undefined' &&
  52786. normals[vertex_idx * 3] === localNormal.x &&
  52787. normals[vertex_idx * 3 + 1] === localNormal.y &&
  52788. normals[vertex_idx * 3 + 2] === localNormal.z &&
  52789. uvs[vertex_idx * 2] === uv.x &&
  52790. uvs[vertex_idx * 2 + 1] === uv.y)) {
  52791. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  52792. uvs.push(uv.x, uv.y);
  52793. normals.push(normal.x, normal.y, normal.z);
  52794. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  52795. }
  52796. indices.push(vertex_idx);
  52797. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  52798. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  52799. currentIndex++;
  52800. }
  52801. }
  52802. }
  52803. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  52804. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  52805. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  52806. mesh.setIndices(indices);
  52807. if (keepSubMeshes) {
  52808. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  52809. var materialIndexOffset = 0, materialMaxIndex;
  52810. mesh.subMeshes = new Array();
  52811. for (var m in subMesh_dict) {
  52812. materialMaxIndex = -1;
  52813. for (var sm in subMesh_dict[m]) {
  52814. subMesh_obj = subMesh_dict[m][sm];
  52815. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  52816. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  52817. }
  52818. materialIndexOffset += ++materialMaxIndex;
  52819. }
  52820. }
  52821. return mesh;
  52822. };
  52823. // Build Mesh from CSG taking material and transforms into account
  52824. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  52825. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  52826. mesh.material = material;
  52827. mesh.position.copyFrom(this.position);
  52828. mesh.rotation.copyFrom(this.rotation);
  52829. if (this.rotationQuaternion) {
  52830. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  52831. }
  52832. mesh.scaling.copyFrom(this.scaling);
  52833. mesh.computeWorldMatrix(true);
  52834. return mesh;
  52835. };
  52836. return CSG;
  52837. }());
  52838. BABYLON.CSG = CSG;
  52839. })(BABYLON || (BABYLON = {}));
  52840. //# sourceMappingURL=babylon.csg.js.map
  52841. var BABYLON;
  52842. (function (BABYLON) {
  52843. var LensFlare = (function () {
  52844. function LensFlare(size, position, color, imgUrl, system) {
  52845. this.size = size;
  52846. this.position = position;
  52847. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  52848. this.dispose = function () {
  52849. if (this.texture) {
  52850. this.texture.dispose();
  52851. }
  52852. // Remove from scene
  52853. var index = this._system.lensFlares.indexOf(this);
  52854. this._system.lensFlares.splice(index, 1);
  52855. };
  52856. this.color = color || new BABYLON.Color3(1, 1, 1);
  52857. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  52858. this._system = system;
  52859. system.lensFlares.push(this);
  52860. }
  52861. return LensFlare;
  52862. }());
  52863. BABYLON.LensFlare = LensFlare;
  52864. })(BABYLON || (BABYLON = {}));
  52865. //# sourceMappingURL=babylon.lensFlare.js.map
  52866. var BABYLON;
  52867. (function (BABYLON) {
  52868. var LensFlareSystem = (function () {
  52869. function LensFlareSystem(name, emitter, scene) {
  52870. this.name = name;
  52871. this.lensFlares = new Array();
  52872. this.borderLimit = 300;
  52873. this.viewportBorder = 0;
  52874. this.layerMask = 0x0FFFFFFF;
  52875. this._vertexBuffers = {};
  52876. this._isEnabled = true;
  52877. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52878. this._emitter = emitter;
  52879. this.id = name;
  52880. scene.lensFlareSystems.push(this);
  52881. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  52882. var engine = scene.getEngine();
  52883. // VBO
  52884. var vertices = [];
  52885. vertices.push(1, 1);
  52886. vertices.push(-1, 1);
  52887. vertices.push(-1, -1);
  52888. vertices.push(1, -1);
  52889. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  52890. // Indices
  52891. var indices = [];
  52892. indices.push(0);
  52893. indices.push(1);
  52894. indices.push(2);
  52895. indices.push(0);
  52896. indices.push(2);
  52897. indices.push(3);
  52898. this._indexBuffer = engine.createIndexBuffer(indices);
  52899. // Effects
  52900. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  52901. }
  52902. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  52903. get: function () {
  52904. return this._isEnabled;
  52905. },
  52906. set: function (value) {
  52907. this._isEnabled = value;
  52908. },
  52909. enumerable: true,
  52910. configurable: true
  52911. });
  52912. LensFlareSystem.prototype.getScene = function () {
  52913. return this._scene;
  52914. };
  52915. LensFlareSystem.prototype.getEmitter = function () {
  52916. return this._emitter;
  52917. };
  52918. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  52919. this._emitter = newEmitter;
  52920. };
  52921. LensFlareSystem.prototype.getEmitterPosition = function () {
  52922. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  52923. };
  52924. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  52925. var position = this.getEmitterPosition();
  52926. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  52927. this._positionX = position.x;
  52928. this._positionY = position.y;
  52929. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  52930. if (this.viewportBorder > 0) {
  52931. globalViewport.x -= this.viewportBorder;
  52932. globalViewport.y -= this.viewportBorder;
  52933. globalViewport.width += this.viewportBorder * 2;
  52934. globalViewport.height += this.viewportBorder * 2;
  52935. position.x += this.viewportBorder;
  52936. position.y += this.viewportBorder;
  52937. this._positionX += this.viewportBorder;
  52938. this._positionY += this.viewportBorder;
  52939. }
  52940. if (position.z > 0) {
  52941. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  52942. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  52943. return true;
  52944. }
  52945. return true;
  52946. }
  52947. return false;
  52948. };
  52949. LensFlareSystem.prototype._isVisible = function () {
  52950. if (!this._isEnabled) {
  52951. return false;
  52952. }
  52953. var emitterPosition = this.getEmitterPosition();
  52954. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  52955. var distance = direction.length();
  52956. direction.normalize();
  52957. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  52958. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  52959. return !pickInfo.hit || pickInfo.distance > distance;
  52960. };
  52961. LensFlareSystem.prototype.render = function () {
  52962. if (!this._effect.isReady())
  52963. return false;
  52964. var engine = this._scene.getEngine();
  52965. var viewport = this._scene.activeCamera.viewport;
  52966. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  52967. // Position
  52968. if (!this.computeEffectivePosition(globalViewport)) {
  52969. return false;
  52970. }
  52971. // Visibility
  52972. if (!this._isVisible()) {
  52973. return false;
  52974. }
  52975. // Intensity
  52976. var awayX;
  52977. var awayY;
  52978. if (this._positionX < this.borderLimit + globalViewport.x) {
  52979. awayX = this.borderLimit + globalViewport.x - this._positionX;
  52980. }
  52981. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  52982. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  52983. }
  52984. else {
  52985. awayX = 0;
  52986. }
  52987. if (this._positionY < this.borderLimit + globalViewport.y) {
  52988. awayY = this.borderLimit + globalViewport.y - this._positionY;
  52989. }
  52990. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  52991. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  52992. }
  52993. else {
  52994. awayY = 0;
  52995. }
  52996. var away = (awayX > awayY) ? awayX : awayY;
  52997. away -= this.viewportBorder;
  52998. if (away > this.borderLimit) {
  52999. away = this.borderLimit;
  53000. }
  53001. var intensity = 1.0 - (away / this.borderLimit);
  53002. if (intensity < 0) {
  53003. return false;
  53004. }
  53005. if (intensity > 1.0) {
  53006. intensity = 1.0;
  53007. }
  53008. if (this.viewportBorder > 0) {
  53009. globalViewport.x += this.viewportBorder;
  53010. globalViewport.y += this.viewportBorder;
  53011. globalViewport.width -= this.viewportBorder * 2;
  53012. globalViewport.height -= this.viewportBorder * 2;
  53013. this._positionX -= this.viewportBorder;
  53014. this._positionY -= this.viewportBorder;
  53015. }
  53016. // Position
  53017. var centerX = globalViewport.x + globalViewport.width / 2;
  53018. var centerY = globalViewport.y + globalViewport.height / 2;
  53019. var distX = centerX - this._positionX;
  53020. var distY = centerY - this._positionY;
  53021. // Effects
  53022. engine.enableEffect(this._effect);
  53023. engine.setState(false);
  53024. engine.setDepthBuffer(false);
  53025. // VBOs
  53026. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  53027. // Flares
  53028. for (var index = 0; index < this.lensFlares.length; index++) {
  53029. var flare = this.lensFlares[index];
  53030. engine.setAlphaMode(flare.alphaMode);
  53031. var x = centerX - (distX * flare.position);
  53032. var y = centerY - (distY * flare.position);
  53033. var cw = flare.size;
  53034. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  53035. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  53036. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  53037. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  53038. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  53039. // Texture
  53040. this._effect.setTexture("textureSampler", flare.texture);
  53041. // Color
  53042. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  53043. // Draw order
  53044. engine.draw(true, 0, 6);
  53045. }
  53046. engine.setDepthBuffer(true);
  53047. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53048. return true;
  53049. };
  53050. LensFlareSystem.prototype.dispose = function () {
  53051. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  53052. if (vertexBuffer) {
  53053. vertexBuffer.dispose();
  53054. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  53055. }
  53056. if (this._indexBuffer) {
  53057. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53058. this._indexBuffer = null;
  53059. }
  53060. while (this.lensFlares.length) {
  53061. this.lensFlares[0].dispose();
  53062. }
  53063. // Remove from scene
  53064. var index = this._scene.lensFlareSystems.indexOf(this);
  53065. this._scene.lensFlareSystems.splice(index, 1);
  53066. };
  53067. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  53068. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  53069. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  53070. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  53071. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  53072. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  53073. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  53074. var parsedFlare = parsedLensFlareSystem.flares[index];
  53075. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  53076. }
  53077. return lensFlareSystem;
  53078. };
  53079. LensFlareSystem.prototype.serialize = function () {
  53080. var serializationObject = {};
  53081. serializationObject.id = this.id;
  53082. serializationObject.name = this.name;
  53083. serializationObject.emitterId = this.getEmitter().id;
  53084. serializationObject.borderLimit = this.borderLimit;
  53085. serializationObject.flares = [];
  53086. for (var index = 0; index < this.lensFlares.length; index++) {
  53087. var flare = this.lensFlares[index];
  53088. serializationObject.flares.push({
  53089. size: flare.size,
  53090. position: flare.position,
  53091. color: flare.color.asArray(),
  53092. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  53093. });
  53094. }
  53095. return serializationObject;
  53096. };
  53097. return LensFlareSystem;
  53098. }());
  53099. BABYLON.LensFlareSystem = LensFlareSystem;
  53100. })(BABYLON || (BABYLON = {}));
  53101. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  53102. var BABYLON;
  53103. (function (BABYLON) {
  53104. /**
  53105. * This is a holder class for the physics joint created by the physics plugin.
  53106. * It holds a set of functions to control the underlying joint.
  53107. */
  53108. var PhysicsJoint = (function () {
  53109. function PhysicsJoint(type, jointData) {
  53110. this.type = type;
  53111. this.jointData = jointData;
  53112. jointData.nativeParams = jointData.nativeParams || {};
  53113. }
  53114. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  53115. get: function () {
  53116. return this._physicsJoint;
  53117. },
  53118. set: function (newJoint) {
  53119. if (this._physicsJoint) {
  53120. //remove from the wolrd
  53121. }
  53122. this._physicsJoint = newJoint;
  53123. },
  53124. enumerable: true,
  53125. configurable: true
  53126. });
  53127. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  53128. set: function (physicsPlugin) {
  53129. this._physicsPlugin = physicsPlugin;
  53130. },
  53131. enumerable: true,
  53132. configurable: true
  53133. });
  53134. /**
  53135. * Execute a function that is physics-plugin specific.
  53136. * @param {Function} func the function that will be executed.
  53137. * It accepts two parameters: the physics world and the physics joint.
  53138. */
  53139. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  53140. func(this._physicsPlugin.world, this._physicsJoint);
  53141. };
  53142. return PhysicsJoint;
  53143. }());
  53144. //TODO check if the native joints are the same
  53145. //Joint Types
  53146. PhysicsJoint.DistanceJoint = 0;
  53147. PhysicsJoint.HingeJoint = 1;
  53148. PhysicsJoint.BallAndSocketJoint = 2;
  53149. PhysicsJoint.WheelJoint = 3;
  53150. PhysicsJoint.SliderJoint = 4;
  53151. //OIMO
  53152. PhysicsJoint.PrismaticJoint = 5;
  53153. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  53154. PhysicsJoint.UniversalJoint = 6;
  53155. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  53156. //Cannon
  53157. //Similar to a Ball-Joint. Different in params
  53158. PhysicsJoint.PointToPointJoint = 8;
  53159. //Cannon only at the moment
  53160. PhysicsJoint.SpringJoint = 9;
  53161. PhysicsJoint.LockJoint = 10;
  53162. BABYLON.PhysicsJoint = PhysicsJoint;
  53163. /**
  53164. * A class representing a physics distance joint.
  53165. */
  53166. var DistanceJoint = (function (_super) {
  53167. __extends(DistanceJoint, _super);
  53168. function DistanceJoint(jointData) {
  53169. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  53170. }
  53171. /**
  53172. * Update the predefined distance.
  53173. */
  53174. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  53175. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  53176. };
  53177. return DistanceJoint;
  53178. }(PhysicsJoint));
  53179. BABYLON.DistanceJoint = DistanceJoint;
  53180. var MotorEnabledJoint = (function (_super) {
  53181. __extends(MotorEnabledJoint, _super);
  53182. function MotorEnabledJoint(type, jointData) {
  53183. return _super.call(this, type, jointData) || this;
  53184. }
  53185. /**
  53186. * Set the motor values.
  53187. * Attention, this function is plugin specific. Engines won't react 100% the same.
  53188. * @param {number} force the force to apply
  53189. * @param {number} maxForce max force for this motor.
  53190. */
  53191. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  53192. this._physicsPlugin.setMotor(this, force, maxForce);
  53193. };
  53194. /**
  53195. * Set the motor's limits.
  53196. * Attention, this function is plugin specific. Engines won't react 100% the same.
  53197. */
  53198. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  53199. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  53200. };
  53201. return MotorEnabledJoint;
  53202. }(PhysicsJoint));
  53203. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  53204. /**
  53205. * This class represents a single hinge physics joint
  53206. */
  53207. var HingeJoint = (function (_super) {
  53208. __extends(HingeJoint, _super);
  53209. function HingeJoint(jointData) {
  53210. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  53211. }
  53212. /**
  53213. * Set the motor values.
  53214. * Attention, this function is plugin specific. Engines won't react 100% the same.
  53215. * @param {number} force the force to apply
  53216. * @param {number} maxForce max force for this motor.
  53217. */
  53218. HingeJoint.prototype.setMotor = function (force, maxForce) {
  53219. this._physicsPlugin.setMotor(this, force, maxForce);
  53220. };
  53221. /**
  53222. * Set the motor's limits.
  53223. * Attention, this function is plugin specific. Engines won't react 100% the same.
  53224. */
  53225. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  53226. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  53227. };
  53228. return HingeJoint;
  53229. }(MotorEnabledJoint));
  53230. BABYLON.HingeJoint = HingeJoint;
  53231. /**
  53232. * This class represents a dual hinge physics joint (same as wheel joint)
  53233. */
  53234. var Hinge2Joint = (function (_super) {
  53235. __extends(Hinge2Joint, _super);
  53236. function Hinge2Joint(jointData) {
  53237. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  53238. }
  53239. /**
  53240. * Set the motor values.
  53241. * Attention, this function is plugin specific. Engines won't react 100% the same.
  53242. * @param {number} force the force to apply
  53243. * @param {number} maxForce max force for this motor.
  53244. * @param {motorIndex} the motor's index, 0 or 1.
  53245. */
  53246. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  53247. if (motorIndex === void 0) { motorIndex = 0; }
  53248. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  53249. };
  53250. /**
  53251. * Set the motor limits.
  53252. * Attention, this function is plugin specific. Engines won't react 100% the same.
  53253. * @param {number} upperLimit the upper limit
  53254. * @param {number} lowerLimit lower limit
  53255. * @param {motorIndex} the motor's index, 0 or 1.
  53256. */
  53257. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  53258. if (motorIndex === void 0) { motorIndex = 0; }
  53259. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  53260. };
  53261. return Hinge2Joint;
  53262. }(MotorEnabledJoint));
  53263. BABYLON.Hinge2Joint = Hinge2Joint;
  53264. })(BABYLON || (BABYLON = {}));
  53265. //# sourceMappingURL=babylon.physicsJoint.js.map
  53266. var BABYLON;
  53267. (function (BABYLON) {
  53268. var PhysicsImpostor = (function () {
  53269. function PhysicsImpostor(object, type, _options, _scene) {
  53270. if (_options === void 0) { _options = { mass: 0 }; }
  53271. var _this = this;
  53272. this.object = object;
  53273. this.type = type;
  53274. this._options = _options;
  53275. this._scene = _scene;
  53276. this._bodyUpdateRequired = false;
  53277. this._onBeforePhysicsStepCallbacks = new Array();
  53278. this._onAfterPhysicsStepCallbacks = new Array();
  53279. this._onPhysicsCollideCallbacks = [];
  53280. this._deltaPosition = BABYLON.Vector3.Zero();
  53281. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  53282. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  53283. /**
  53284. * this function is executed by the physics engine.
  53285. */
  53286. this.beforeStep = function () {
  53287. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  53288. //conjugate deltaRotation
  53289. if (_this._deltaRotationConjugated) {
  53290. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  53291. }
  53292. else {
  53293. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  53294. }
  53295. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  53296. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  53297. func(_this);
  53298. });
  53299. };
  53300. /**
  53301. * this function is executed by the physics engine.
  53302. */
  53303. this.afterStep = function () {
  53304. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  53305. func(_this);
  53306. });
  53307. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  53308. _this.object.position.addInPlace(_this._deltaPosition);
  53309. if (_this._deltaRotation) {
  53310. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  53311. }
  53312. };
  53313. /**
  53314. * Legacy collision detection event support
  53315. */
  53316. this.onCollideEvent = null;
  53317. //event and body object due to cannon's event-based architecture.
  53318. this.onCollide = function (e) {
  53319. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  53320. return;
  53321. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  53322. if (otherImpostor) {
  53323. // Legacy collision detection event support
  53324. if (_this.onCollideEvent) {
  53325. _this.onCollideEvent(_this, otherImpostor);
  53326. }
  53327. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  53328. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  53329. }).forEach(function (obj) {
  53330. obj.callback(_this, otherImpostor);
  53331. });
  53332. }
  53333. };
  53334. //sanity check!
  53335. if (!this.object) {
  53336. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  53337. return;
  53338. }
  53339. //legacy support for old syntax.
  53340. if (!this._scene && object.getScene) {
  53341. this._scene = object.getScene();
  53342. }
  53343. this._physicsEngine = this._scene.getPhysicsEngine();
  53344. if (!this._physicsEngine) {
  53345. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  53346. }
  53347. else {
  53348. //set the object's quaternion, if not set
  53349. if (!this.object.rotationQuaternion) {
  53350. if (this.object.rotation) {
  53351. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  53352. }
  53353. else {
  53354. this.object.rotationQuaternion = new BABYLON.Quaternion();
  53355. }
  53356. }
  53357. //default options params
  53358. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  53359. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  53360. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  53361. this._joints = [];
  53362. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  53363. if (!this.object.parent) {
  53364. this._init();
  53365. }
  53366. }
  53367. }
  53368. /**
  53369. * This function will completly initialize this impostor.
  53370. * It will create a new body - but only if this mesh has no parent.
  53371. * If it has, this impostor will not be used other than to define the impostor
  53372. * of the child mesh.
  53373. */
  53374. PhysicsImpostor.prototype._init = function () {
  53375. this._physicsEngine.removeImpostor(this);
  53376. this.physicsBody = null;
  53377. this._parent = this._parent || this._getPhysicsParent();
  53378. if (!this.parent) {
  53379. this._physicsEngine.addImpostor(this);
  53380. }
  53381. };
  53382. PhysicsImpostor.prototype._getPhysicsParent = function () {
  53383. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  53384. var parentMesh = this.object.parent;
  53385. return parentMesh.physicsImpostor;
  53386. }
  53387. return;
  53388. };
  53389. /**
  53390. * Should a new body be generated.
  53391. */
  53392. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  53393. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  53394. };
  53395. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  53396. this.forceUpdate();
  53397. };
  53398. /**
  53399. * Force a regeneration of this or the parent's impostor's body.
  53400. * Use under cautious - This will remove all joints already implemented.
  53401. */
  53402. PhysicsImpostor.prototype.forceUpdate = function () {
  53403. this._init();
  53404. if (this.parent) {
  53405. this.parent.forceUpdate();
  53406. }
  53407. };
  53408. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  53409. /*public get mesh(): AbstractMesh {
  53410. return this._mesh;
  53411. }*/
  53412. /**
  53413. * Gets the body that holds this impostor. Either its own, or its parent.
  53414. */
  53415. get: function () {
  53416. return this._parent ? this._parent.physicsBody : this._physicsBody;
  53417. },
  53418. /**
  53419. * Set the physics body. Used mainly by the physics engine/plugin
  53420. */
  53421. set: function (physicsBody) {
  53422. if (this._physicsBody) {
  53423. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  53424. }
  53425. this._physicsBody = physicsBody;
  53426. this.resetUpdateFlags();
  53427. },
  53428. enumerable: true,
  53429. configurable: true
  53430. });
  53431. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  53432. get: function () {
  53433. return this._parent;
  53434. },
  53435. set: function (value) {
  53436. this._parent = value;
  53437. },
  53438. enumerable: true,
  53439. configurable: true
  53440. });
  53441. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  53442. this._bodyUpdateRequired = false;
  53443. };
  53444. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  53445. if (this.object.getBoundingInfo) {
  53446. var q = this.object.rotationQuaternion;
  53447. //reset rotation
  53448. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  53449. //calculate the world matrix with no rotation
  53450. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  53451. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  53452. //bring back the rotation
  53453. this.object.rotationQuaternion = q;
  53454. //calculate the world matrix with the new rotation
  53455. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  53456. return size;
  53457. }
  53458. else {
  53459. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  53460. }
  53461. };
  53462. PhysicsImpostor.prototype.getObjectCenter = function () {
  53463. if (this.object.getBoundingInfo) {
  53464. return this.object.getBoundingInfo().boundingBox.centerWorld;
  53465. }
  53466. else {
  53467. return this.object.position;
  53468. }
  53469. };
  53470. /**
  53471. * Get a specific parametes from the options parameter.
  53472. */
  53473. PhysicsImpostor.prototype.getParam = function (paramName) {
  53474. return this._options[paramName];
  53475. };
  53476. /**
  53477. * Sets a specific parameter in the options given to the physics plugin
  53478. */
  53479. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  53480. this._options[paramName] = value;
  53481. this._bodyUpdateRequired = true;
  53482. };
  53483. /**
  53484. * Specifically change the body's mass option. Won't recreate the physics body object
  53485. */
  53486. PhysicsImpostor.prototype.setMass = function (mass) {
  53487. if (this.getParam("mass") !== mass) {
  53488. this.setParam("mass", mass);
  53489. }
  53490. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  53491. };
  53492. PhysicsImpostor.prototype.getLinearVelocity = function () {
  53493. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  53494. };
  53495. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  53496. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  53497. };
  53498. PhysicsImpostor.prototype.getAngularVelocity = function () {
  53499. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  53500. };
  53501. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  53502. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  53503. };
  53504. /**
  53505. * Execute a function with the physics plugin native code.
  53506. * Provide a function the will have two variables - the world object and the physics body object.
  53507. */
  53508. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  53509. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  53510. };
  53511. /**
  53512. * Register a function that will be executed before the physics world is stepping forward.
  53513. */
  53514. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  53515. this._onBeforePhysicsStepCallbacks.push(func);
  53516. };
  53517. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  53518. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  53519. if (index > -1) {
  53520. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  53521. }
  53522. else {
  53523. BABYLON.Tools.Warn("Function to remove was not found");
  53524. }
  53525. };
  53526. /**
  53527. * Register a function that will be executed after the physics step
  53528. */
  53529. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  53530. this._onAfterPhysicsStepCallbacks.push(func);
  53531. };
  53532. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  53533. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  53534. if (index > -1) {
  53535. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  53536. }
  53537. else {
  53538. BABYLON.Tools.Warn("Function to remove was not found");
  53539. }
  53540. };
  53541. /**
  53542. * register a function that will be executed when this impostor collides against a different body.
  53543. */
  53544. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  53545. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  53546. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  53547. };
  53548. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  53549. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  53550. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  53551. if (index > -1) {
  53552. this._onPhysicsCollideCallbacks.splice(index, 1);
  53553. }
  53554. else {
  53555. BABYLON.Tools.Warn("Function to remove was not found");
  53556. }
  53557. };
  53558. /**
  53559. * Apply a force
  53560. */
  53561. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  53562. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  53563. };
  53564. /**
  53565. * Apply an impulse
  53566. */
  53567. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  53568. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  53569. };
  53570. /**
  53571. * A help function to create a joint.
  53572. */
  53573. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  53574. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  53575. this.addJoint(otherImpostor, joint);
  53576. };
  53577. /**
  53578. * Add a joint to this impostor with a different impostor.
  53579. */
  53580. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  53581. this._joints.push({
  53582. otherImpostor: otherImpostor,
  53583. joint: joint
  53584. });
  53585. this._physicsEngine.addJoint(this, otherImpostor, joint);
  53586. };
  53587. /**
  53588. * Will keep this body still, in a sleep mode.
  53589. */
  53590. PhysicsImpostor.prototype.sleep = function () {
  53591. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  53592. };
  53593. /**
  53594. * Wake the body up.
  53595. */
  53596. PhysicsImpostor.prototype.wakeUp = function () {
  53597. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  53598. };
  53599. PhysicsImpostor.prototype.clone = function (newObject) {
  53600. if (!newObject)
  53601. return null;
  53602. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  53603. };
  53604. PhysicsImpostor.prototype.dispose = function () {
  53605. var _this = this;
  53606. //no dispose if no physics engine is available.
  53607. if (!this._physicsEngine) {
  53608. return;
  53609. }
  53610. this._joints.forEach(function (j) {
  53611. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  53612. });
  53613. //dispose the physics body
  53614. this._physicsEngine.removeImpostor(this);
  53615. if (this.parent) {
  53616. this.parent.forceUpdate();
  53617. }
  53618. else {
  53619. /*this._object.getChildMeshes().forEach(function(mesh) {
  53620. if (mesh.physicsImpostor) {
  53621. if (disposeChildren) {
  53622. mesh.physicsImpostor.dispose();
  53623. mesh.physicsImpostor = null;
  53624. }
  53625. }
  53626. })*/
  53627. }
  53628. };
  53629. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  53630. this._deltaPosition.copyFrom(position);
  53631. };
  53632. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  53633. if (!this._deltaRotation) {
  53634. this._deltaRotation = new BABYLON.Quaternion();
  53635. }
  53636. this._deltaRotation.copyFrom(rotation);
  53637. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  53638. };
  53639. return PhysicsImpostor;
  53640. }());
  53641. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  53642. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  53643. //Impostor types
  53644. PhysicsImpostor.NoImpostor = 0;
  53645. PhysicsImpostor.SphereImpostor = 1;
  53646. PhysicsImpostor.BoxImpostor = 2;
  53647. PhysicsImpostor.PlaneImpostor = 3;
  53648. PhysicsImpostor.MeshImpostor = 4;
  53649. PhysicsImpostor.CylinderImpostor = 7;
  53650. PhysicsImpostor.ParticleImpostor = 8;
  53651. PhysicsImpostor.HeightmapImpostor = 9;
  53652. BABYLON.PhysicsImpostor = PhysicsImpostor;
  53653. })(BABYLON || (BABYLON = {}));
  53654. //# sourceMappingURL=babylon.physicsImpostor.js.map
  53655. var BABYLON;
  53656. (function (BABYLON) {
  53657. var PhysicsEngine = (function () {
  53658. function PhysicsEngine(gravity, _physicsPlugin) {
  53659. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  53660. this._physicsPlugin = _physicsPlugin;
  53661. //new methods and parameters
  53662. this._impostors = [];
  53663. this._joints = [];
  53664. if (!this._physicsPlugin.isSupported()) {
  53665. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  53666. + "Please make sure it is included.");
  53667. }
  53668. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  53669. this.setGravity(gravity);
  53670. this.setTimeStep();
  53671. }
  53672. PhysicsEngine.prototype.setGravity = function (gravity) {
  53673. this.gravity = gravity;
  53674. this._physicsPlugin.setGravity(this.gravity);
  53675. };
  53676. /**
  53677. * Set the time step of the physics engine.
  53678. * default is 1/60.
  53679. * To slow it down, enter 1/600 for example.
  53680. * To speed it up, 1/30
  53681. * @param {number} newTimeStep the new timestep to apply to this world.
  53682. */
  53683. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  53684. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  53685. this._physicsPlugin.setTimeStep(newTimeStep);
  53686. };
  53687. PhysicsEngine.prototype.dispose = function () {
  53688. this._impostors.forEach(function (impostor) {
  53689. impostor.dispose();
  53690. });
  53691. this._physicsPlugin.dispose();
  53692. };
  53693. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  53694. return this._physicsPlugin.name;
  53695. };
  53696. /**
  53697. * Adding a new impostor for the impostor tracking.
  53698. * This will be done by the impostor itself.
  53699. * @param {PhysicsImpostor} impostor the impostor to add
  53700. */
  53701. PhysicsEngine.prototype.addImpostor = function (impostor) {
  53702. impostor.uniqueId = this._impostors.push(impostor);
  53703. //if no parent, generate the body
  53704. if (!impostor.parent) {
  53705. this._physicsPlugin.generatePhysicsBody(impostor);
  53706. }
  53707. };
  53708. /**
  53709. * Remove an impostor from the engine.
  53710. * This impostor and its mesh will not longer be updated by the physics engine.
  53711. * @param {PhysicsImpostor} impostor the impostor to remove
  53712. */
  53713. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  53714. var index = this._impostors.indexOf(impostor);
  53715. if (index > -1) {
  53716. var removed = this._impostors.splice(index, 1);
  53717. //Is it needed?
  53718. if (removed.length) {
  53719. //this will also remove it from the world.
  53720. removed[0].physicsBody = null;
  53721. }
  53722. }
  53723. };
  53724. /**
  53725. * Add a joint to the physics engine
  53726. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  53727. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  53728. * @param {PhysicsJoint} the joint that will connect both impostors.
  53729. */
  53730. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  53731. var impostorJoint = {
  53732. mainImpostor: mainImpostor,
  53733. connectedImpostor: connectedImpostor,
  53734. joint: joint
  53735. };
  53736. joint.physicsPlugin = this._physicsPlugin;
  53737. this._joints.push(impostorJoint);
  53738. this._physicsPlugin.generateJoint(impostorJoint);
  53739. };
  53740. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  53741. var matchingJoints = this._joints.filter(function (impostorJoint) {
  53742. return (impostorJoint.connectedImpostor === connectedImpostor
  53743. && impostorJoint.joint === joint
  53744. && impostorJoint.mainImpostor === mainImpostor);
  53745. });
  53746. if (matchingJoints.length) {
  53747. this._physicsPlugin.removeJoint(matchingJoints[0]);
  53748. //TODO remove it from the list as well
  53749. }
  53750. };
  53751. /**
  53752. * Called by the scene. no need to call it.
  53753. */
  53754. PhysicsEngine.prototype._step = function (delta) {
  53755. var _this = this;
  53756. //check if any mesh has no body / requires an update
  53757. this._impostors.forEach(function (impostor) {
  53758. if (impostor.isBodyInitRequired()) {
  53759. _this._physicsPlugin.generatePhysicsBody(impostor);
  53760. }
  53761. });
  53762. if (delta > 0.1) {
  53763. delta = 0.1;
  53764. }
  53765. else if (delta <= 0) {
  53766. delta = 1.0 / 60.0;
  53767. }
  53768. this._physicsPlugin.executeStep(delta, this._impostors);
  53769. };
  53770. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  53771. return this._physicsPlugin;
  53772. };
  53773. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  53774. for (var i = 0; i < this._impostors.length; ++i) {
  53775. if (this._impostors[i].object === object) {
  53776. return this._impostors[i];
  53777. }
  53778. }
  53779. };
  53780. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  53781. for (var i = 0; i < this._impostors.length; ++i) {
  53782. if (this._impostors[i].physicsBody === body) {
  53783. return this._impostors[i];
  53784. }
  53785. }
  53786. };
  53787. return PhysicsEngine;
  53788. }());
  53789. // Statics
  53790. PhysicsEngine.Epsilon = 0.001;
  53791. BABYLON.PhysicsEngine = PhysicsEngine;
  53792. })(BABYLON || (BABYLON = {}));
  53793. //# sourceMappingURL=babylon.physicsEngine.js.map
  53794. var BABYLON;
  53795. (function (BABYLON) {
  53796. var CannonJSPlugin = (function () {
  53797. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  53798. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  53799. if (iterations === void 0) { iterations = 10; }
  53800. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  53801. this.name = "CannonJSPlugin";
  53802. this._physicsMaterials = [];
  53803. this._fixedTimeStep = 1 / 60;
  53804. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  53805. this._currentCollisionGroup = 2;
  53806. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  53807. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  53808. this._tmpPosition = BABYLON.Vector3.Zero();
  53809. this._tmpQuaternion = new BABYLON.Quaternion();
  53810. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  53811. this._tmpDeltaRotation = new BABYLON.Quaternion();
  53812. this._tmpUnityRotation = new BABYLON.Quaternion();
  53813. if (!this.isSupported()) {
  53814. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  53815. return;
  53816. }
  53817. this.world = new CANNON.World();
  53818. this.world.broadphase = new CANNON.NaiveBroadphase();
  53819. this.world.solver.iterations = iterations;
  53820. }
  53821. CannonJSPlugin.prototype.setGravity = function (gravity) {
  53822. this.world.gravity.copy(gravity);
  53823. };
  53824. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  53825. this._fixedTimeStep = timeStep;
  53826. };
  53827. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  53828. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  53829. };
  53830. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  53831. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  53832. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  53833. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  53834. };
  53835. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  53836. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  53837. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  53838. impostor.physicsBody.applyForce(impulse, worldPoint);
  53839. };
  53840. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  53841. //parent-child relationship. Does this impostor has a parent impostor?
  53842. if (impostor.parent) {
  53843. if (impostor.physicsBody) {
  53844. this.removePhysicsBody(impostor);
  53845. //TODO is that needed?
  53846. impostor.forceUpdate();
  53847. }
  53848. return;
  53849. }
  53850. //should a new body be created for this impostor?
  53851. if (impostor.isBodyInitRequired()) {
  53852. var shape = this._createShape(impostor);
  53853. //unregister events, if body is being changed
  53854. var oldBody = impostor.physicsBody;
  53855. if (oldBody) {
  53856. this.removePhysicsBody(impostor);
  53857. }
  53858. //create the body and material
  53859. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  53860. var bodyCreationObject = {
  53861. mass: impostor.getParam("mass"),
  53862. material: material
  53863. };
  53864. // A simple extend, in case native options were used.
  53865. var nativeOptions = impostor.getParam("nativeOptions");
  53866. for (var key in nativeOptions) {
  53867. if (nativeOptions.hasOwnProperty(key)) {
  53868. bodyCreationObject[key] = nativeOptions[key];
  53869. }
  53870. }
  53871. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  53872. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  53873. this.world.addEventListener("preStep", impostor.beforeStep);
  53874. this.world.addEventListener("postStep", impostor.afterStep);
  53875. impostor.physicsBody.addShape(shape);
  53876. this.world.add(impostor.physicsBody);
  53877. //try to keep the body moving in the right direction by taking old properties.
  53878. //Should be tested!
  53879. if (oldBody) {
  53880. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  53881. impostor.physicsBody[param].copy(oldBody[param]);
  53882. });
  53883. }
  53884. this._processChildMeshes(impostor);
  53885. }
  53886. //now update the body's transformation
  53887. this._updatePhysicsBodyTransformation(impostor);
  53888. };
  53889. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  53890. var _this = this;
  53891. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  53892. if (meshChildren.length) {
  53893. var processMesh = function (localPosition, mesh) {
  53894. var childImpostor = mesh.getPhysicsImpostor();
  53895. if (childImpostor) {
  53896. var parent = childImpostor.parent;
  53897. if (parent !== mainImpostor) {
  53898. var localPosition = mesh.position;
  53899. if (childImpostor.physicsBody) {
  53900. _this.removePhysicsBody(childImpostor);
  53901. childImpostor.physicsBody = null;
  53902. }
  53903. childImpostor.parent = mainImpostor;
  53904. childImpostor.resetUpdateFlags();
  53905. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  53906. //Add the mass of the children.
  53907. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  53908. }
  53909. }
  53910. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  53911. };
  53912. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  53913. }
  53914. };
  53915. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  53916. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  53917. this.world.removeEventListener("preStep", impostor.beforeStep);
  53918. this.world.removeEventListener("postStep", impostor.afterStep);
  53919. this.world.remove(impostor.physicsBody);
  53920. };
  53921. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  53922. var mainBody = impostorJoint.mainImpostor.physicsBody;
  53923. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  53924. if (!mainBody || !connectedBody) {
  53925. return;
  53926. }
  53927. var constraint;
  53928. var jointData = impostorJoint.joint.jointData;
  53929. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  53930. var constraintData = {
  53931. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  53932. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  53933. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  53934. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  53935. maxForce: jointData.nativeParams.maxForce,
  53936. collideConnected: !!jointData.collision
  53937. };
  53938. switch (impostorJoint.joint.type) {
  53939. case BABYLON.PhysicsJoint.HingeJoint:
  53940. case BABYLON.PhysicsJoint.Hinge2Joint:
  53941. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  53942. break;
  53943. case BABYLON.PhysicsJoint.DistanceJoint:
  53944. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  53945. break;
  53946. case BABYLON.PhysicsJoint.SpringJoint:
  53947. var springData = jointData;
  53948. constraint = new CANNON.Spring(mainBody, connectedBody, {
  53949. restLength: springData.length,
  53950. stiffness: springData.stiffness,
  53951. damping: springData.damping,
  53952. localAnchorA: constraintData.pivotA,
  53953. localAnchorB: constraintData.pivotB
  53954. });
  53955. break;
  53956. case BABYLON.PhysicsJoint.LockJoint:
  53957. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  53958. break;
  53959. case BABYLON.PhysicsJoint.PointToPointJoint:
  53960. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  53961. default:
  53962. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  53963. break;
  53964. }
  53965. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  53966. constraint.collideConnected = !!jointData.collision;
  53967. impostorJoint.joint.physicsJoint = constraint;
  53968. //don't add spring as constraint, as it is not one.
  53969. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  53970. this.world.addConstraint(constraint);
  53971. }
  53972. else {
  53973. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  53974. constraint.applyForce();
  53975. });
  53976. }
  53977. };
  53978. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  53979. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  53980. };
  53981. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  53982. var index;
  53983. var mat;
  53984. for (index = 0; index < this._physicsMaterials.length; index++) {
  53985. mat = this._physicsMaterials[index];
  53986. if (mat.friction === friction && mat.restitution === restitution) {
  53987. return mat;
  53988. }
  53989. }
  53990. var currentMat = new CANNON.Material(name);
  53991. currentMat.friction = friction;
  53992. currentMat.restitution = restitution;
  53993. this._physicsMaterials.push(currentMat);
  53994. return currentMat;
  53995. };
  53996. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  53997. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  53998. };
  53999. CannonJSPlugin.prototype._createShape = function (impostor) {
  54000. var object = impostor.object;
  54001. var returnValue;
  54002. var extendSize = impostor.getObjectExtendSize();
  54003. switch (impostor.type) {
  54004. case BABYLON.PhysicsImpostor.SphereImpostor:
  54005. var radiusX = extendSize.x;
  54006. var radiusY = extendSize.y;
  54007. var radiusZ = extendSize.z;
  54008. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  54009. break;
  54010. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  54011. case BABYLON.PhysicsImpostor.CylinderImpostor:
  54012. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  54013. break;
  54014. case BABYLON.PhysicsImpostor.BoxImpostor:
  54015. var box = extendSize.scale(0.5);
  54016. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  54017. break;
  54018. case BABYLON.PhysicsImpostor.PlaneImpostor:
  54019. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  54020. returnValue = new CANNON.Plane();
  54021. break;
  54022. case BABYLON.PhysicsImpostor.MeshImpostor:
  54023. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  54024. var rawFaces = object.getIndices ? object.getIndices() : [];
  54025. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  54026. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  54027. break;
  54028. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  54029. returnValue = this._createHeightmap(object);
  54030. break;
  54031. case BABYLON.PhysicsImpostor.ParticleImpostor:
  54032. returnValue = new CANNON.Particle();
  54033. break;
  54034. }
  54035. return returnValue;
  54036. };
  54037. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  54038. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54039. var matrix = [];
  54040. //For now pointDepth will not be used and will be automatically calculated.
  54041. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  54042. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  54043. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  54044. var elementSize = dim * 2 / arraySize;
  54045. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  54046. for (var i = 0; i < pos.length; i = i + 3) {
  54047. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  54048. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  54049. var y = pos[i + 1] + minY;
  54050. if (!matrix[x]) {
  54051. matrix[x] = [];
  54052. }
  54053. if (!matrix[x][z]) {
  54054. matrix[x][z] = y;
  54055. }
  54056. matrix[x][z] = Math.max(y, matrix[x][z]);
  54057. }
  54058. for (var x = 0; x <= arraySize; ++x) {
  54059. if (!matrix[x]) {
  54060. var loc = 1;
  54061. while (!matrix[(x + loc) % arraySize]) {
  54062. loc++;
  54063. }
  54064. matrix[x] = matrix[(x + loc) % arraySize].slice();
  54065. //console.log("missing x", x);
  54066. }
  54067. for (var z = 0; z <= arraySize; ++z) {
  54068. if (!matrix[x][z]) {
  54069. var loc = 1;
  54070. var newValue;
  54071. while (newValue === undefined) {
  54072. newValue = matrix[x][(z + loc++) % arraySize];
  54073. }
  54074. matrix[x][z] = newValue;
  54075. }
  54076. }
  54077. }
  54078. var shape = new CANNON.Heightfield(matrix, {
  54079. elementSize: elementSize
  54080. });
  54081. //For future reference, needed for body transformation
  54082. shape.minY = minY;
  54083. return shape;
  54084. };
  54085. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  54086. var object = impostor.object;
  54087. //make sure it is updated...
  54088. object.computeWorldMatrix && object.computeWorldMatrix(true);
  54089. // The delta between the mesh position and the mesh bounding box center
  54090. var center = impostor.getObjectCenter();
  54091. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  54092. this._tmpPosition.copyFrom(center);
  54093. var quaternion = object.rotationQuaternion;
  54094. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  54095. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  54096. //-90 DEG in X, precalculated
  54097. quaternion = quaternion.multiply(this._minus90X);
  54098. //Invert! (Precalculated, 90 deg in X)
  54099. //No need to clone. this will never change.
  54100. impostor.setDeltaRotation(this._plus90X);
  54101. }
  54102. //If it is a heightfield, if should be centered.
  54103. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  54104. var mesh = object;
  54105. //calculate the correct body position:
  54106. var rotationQuaternion = mesh.rotationQuaternion;
  54107. mesh.rotationQuaternion = this._tmpUnityRotation;
  54108. mesh.computeWorldMatrix(true);
  54109. //get original center with no rotation
  54110. var c = center.clone();
  54111. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  54112. //rotation is back
  54113. mesh.rotationQuaternion = rotationQuaternion;
  54114. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  54115. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  54116. mesh.setPivotMatrix(p);
  54117. mesh.computeWorldMatrix(true);
  54118. //calculate the translation
  54119. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  54120. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  54121. //add it inverted to the delta
  54122. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  54123. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  54124. mesh.setPivotMatrix(oldPivot);
  54125. mesh.computeWorldMatrix(true);
  54126. }
  54127. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  54128. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  54129. this._tmpPosition.copyFrom(object.position);
  54130. }
  54131. impostor.setDeltaPosition(this._tmpDeltaPosition);
  54132. //Now update the impostor object
  54133. impostor.physicsBody.position.copy(this._tmpPosition);
  54134. impostor.physicsBody.quaternion.copy(quaternion);
  54135. };
  54136. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  54137. impostor.object.position.copyFrom(impostor.physicsBody.position);
  54138. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  54139. };
  54140. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  54141. impostor.physicsBody.position.copy(newPosition);
  54142. impostor.physicsBody.quaternion.copy(newRotation);
  54143. };
  54144. CannonJSPlugin.prototype.isSupported = function () {
  54145. return window.CANNON !== undefined;
  54146. };
  54147. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  54148. impostor.physicsBody.velocity.copy(velocity);
  54149. };
  54150. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  54151. impostor.physicsBody.angularVelocity.copy(velocity);
  54152. };
  54153. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  54154. var v = impostor.physicsBody.velocity;
  54155. if (!v)
  54156. return null;
  54157. return new BABYLON.Vector3(v.x, v.y, v.z);
  54158. };
  54159. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  54160. var v = impostor.physicsBody.angularVelocity;
  54161. if (!v)
  54162. return null;
  54163. return new BABYLON.Vector3(v.x, v.y, v.z);
  54164. };
  54165. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  54166. impostor.physicsBody.mass = mass;
  54167. impostor.physicsBody.updateMassProperties();
  54168. };
  54169. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  54170. impostor.physicsBody.sleep();
  54171. };
  54172. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  54173. impostor.physicsBody.wakeUp();
  54174. };
  54175. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  54176. joint.physicsJoint.distance = maxDistance;
  54177. };
  54178. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  54179. if (!motorIndex) {
  54180. joint.physicsJoint.enableMotor();
  54181. }
  54182. };
  54183. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  54184. if (!motorIndex) {
  54185. joint.physicsJoint.disableMotor();
  54186. }
  54187. };
  54188. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  54189. if (!motorIndex) {
  54190. joint.physicsJoint.enableMotor();
  54191. joint.physicsJoint.setMotorSpeed(speed);
  54192. if (maxForce) {
  54193. this.setLimit(joint, maxForce);
  54194. }
  54195. }
  54196. };
  54197. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  54198. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  54199. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  54200. };
  54201. CannonJSPlugin.prototype.dispose = function () {
  54202. //nothing to do, actually.
  54203. };
  54204. return CannonJSPlugin;
  54205. }());
  54206. BABYLON.CannonJSPlugin = CannonJSPlugin;
  54207. })(BABYLON || (BABYLON = {}));
  54208. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  54209. var BABYLON;
  54210. (function (BABYLON) {
  54211. var OimoJSPlugin = (function () {
  54212. function OimoJSPlugin(iterations) {
  54213. this.name = "OimoJSPlugin";
  54214. this._tmpImpostorsArray = [];
  54215. this._tmpPositionVector = BABYLON.Vector3.Zero();
  54216. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  54217. this.world.worldscale(1);
  54218. this.world.clear();
  54219. //making sure no stats are calculated
  54220. this.world.isNoStat = true;
  54221. }
  54222. OimoJSPlugin.prototype.setGravity = function (gravity) {
  54223. this.world.gravity.copy(gravity);
  54224. };
  54225. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  54226. this.world.timeStep = timeStep;
  54227. };
  54228. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  54229. var _this = this;
  54230. impostors.forEach(function (impostor) {
  54231. impostor.beforeStep();
  54232. });
  54233. this.world.step();
  54234. impostors.forEach(function (impostor) {
  54235. impostor.afterStep();
  54236. //update the ordered impostors array
  54237. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  54238. });
  54239. //check for collisions
  54240. var contact = this.world.contacts;
  54241. while (contact !== null) {
  54242. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  54243. contact = contact.next;
  54244. continue;
  54245. }
  54246. //is this body colliding with any other? get the impostor
  54247. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  54248. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  54249. if (!mainImpostor || !collidingImpostor) {
  54250. contact = contact.next;
  54251. continue;
  54252. }
  54253. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  54254. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  54255. contact = contact.next;
  54256. }
  54257. };
  54258. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  54259. var mass = impostor.physicsBody.massInfo.mass;
  54260. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  54261. };
  54262. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  54263. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  54264. this.applyImpulse(impostor, force, contactPoint);
  54265. };
  54266. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  54267. var _this = this;
  54268. //parent-child relationship. Does this impostor has a parent impostor?
  54269. if (impostor.parent) {
  54270. if (impostor.physicsBody) {
  54271. this.removePhysicsBody(impostor);
  54272. //TODO is that needed?
  54273. impostor.forceUpdate();
  54274. }
  54275. return;
  54276. }
  54277. if (impostor.isBodyInitRequired()) {
  54278. var bodyConfig = {
  54279. name: impostor.uniqueId,
  54280. //Oimo must have mass, also for static objects.
  54281. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  54282. size: [],
  54283. type: [],
  54284. pos: [],
  54285. rot: [],
  54286. move: impostor.getParam("mass") !== 0,
  54287. //Supporting older versions of Oimo
  54288. world: this.world
  54289. };
  54290. var impostors = [impostor];
  54291. var addToArray = function (parent) {
  54292. if (!parent.getChildMeshes)
  54293. return;
  54294. parent.getChildMeshes().forEach(function (m) {
  54295. if (m.physicsImpostor) {
  54296. impostors.push(m.physicsImpostor);
  54297. m.physicsImpostor._init();
  54298. }
  54299. });
  54300. };
  54301. addToArray(impostor.object);
  54302. var checkWithEpsilon_1 = function (value) {
  54303. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  54304. };
  54305. impostors.forEach(function (i) {
  54306. //get the correct bounding box
  54307. var oldQuaternion = i.object.rotationQuaternion;
  54308. var rot = new OIMO.Euler().setFromQuaternion({
  54309. x: impostor.object.rotationQuaternion.x,
  54310. y: impostor.object.rotationQuaternion.y,
  54311. z: impostor.object.rotationQuaternion.z,
  54312. s: impostor.object.rotationQuaternion.w
  54313. });
  54314. var extendSize = i.getObjectExtendSize();
  54315. if (i === impostor) {
  54316. var center = impostor.getObjectCenter();
  54317. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  54318. //Can also use Array.prototype.push.apply
  54319. bodyConfig.pos.push(center.x);
  54320. bodyConfig.pos.push(center.y);
  54321. bodyConfig.pos.push(center.z);
  54322. //tmp solution
  54323. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  54324. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  54325. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  54326. }
  54327. else {
  54328. bodyConfig.pos.push(i.object.position.x);
  54329. bodyConfig.pos.push(i.object.position.y);
  54330. bodyConfig.pos.push(i.object.position.z);
  54331. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  54332. bodyConfig.rot.push(0);
  54333. bodyConfig.rot.push(0);
  54334. bodyConfig.rot.push(0);
  54335. }
  54336. // register mesh
  54337. switch (i.type) {
  54338. case BABYLON.PhysicsImpostor.ParticleImpostor:
  54339. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  54340. case BABYLON.PhysicsImpostor.SphereImpostor:
  54341. var radiusX = extendSize.x;
  54342. var radiusY = extendSize.y;
  54343. var radiusZ = extendSize.z;
  54344. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  54345. bodyConfig.type.push('sphere');
  54346. //due to the way oimo works with compounds, add 3 times
  54347. bodyConfig.size.push(size);
  54348. bodyConfig.size.push(size);
  54349. bodyConfig.size.push(size);
  54350. break;
  54351. case BABYLON.PhysicsImpostor.CylinderImpostor:
  54352. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  54353. var sizeY = checkWithEpsilon_1(extendSize.y);
  54354. bodyConfig.type.push('cylinder');
  54355. bodyConfig.size.push(sizeX);
  54356. bodyConfig.size.push(sizeY);
  54357. //due to the way oimo works with compounds, add one more value.
  54358. bodyConfig.size.push(sizeY);
  54359. break;
  54360. case BABYLON.PhysicsImpostor.PlaneImpostor:
  54361. case BABYLON.PhysicsImpostor.BoxImpostor:
  54362. default:
  54363. var sizeX = checkWithEpsilon_1(extendSize.x);
  54364. var sizeY = checkWithEpsilon_1(extendSize.y);
  54365. var sizeZ = checkWithEpsilon_1(extendSize.z);
  54366. bodyConfig.type.push('box');
  54367. bodyConfig.size.push(sizeX);
  54368. bodyConfig.size.push(sizeY);
  54369. bodyConfig.size.push(sizeZ);
  54370. break;
  54371. }
  54372. //actually not needed, but hey...
  54373. i.object.rotationQuaternion = oldQuaternion;
  54374. });
  54375. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  54376. }
  54377. else {
  54378. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  54379. }
  54380. impostor.setDeltaPosition(this._tmpPositionVector);
  54381. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  54382. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  54383. };
  54384. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  54385. //impostor.physicsBody.dispose();
  54386. //Same as : (older oimo versions)
  54387. this.world.removeRigidBody(impostor.physicsBody);
  54388. };
  54389. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  54390. var mainBody = impostorJoint.mainImpostor.physicsBody;
  54391. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  54392. if (!mainBody || !connectedBody) {
  54393. return;
  54394. }
  54395. var jointData = impostorJoint.joint.jointData;
  54396. var options = jointData.nativeParams || {};
  54397. var type;
  54398. var nativeJointData = {
  54399. body1: mainBody,
  54400. body2: connectedBody,
  54401. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  54402. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  54403. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  54404. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  54405. min: options.min,
  54406. max: options.max,
  54407. collision: options.collision || jointData.collision,
  54408. spring: options.spring,
  54409. //supporting older version of Oimo
  54410. world: this.world
  54411. };
  54412. switch (impostorJoint.joint.type) {
  54413. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  54414. type = "jointBall";
  54415. break;
  54416. case BABYLON.PhysicsJoint.SpringJoint:
  54417. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  54418. var springData = jointData;
  54419. nativeJointData.min = springData.length || nativeJointData.min;
  54420. //Max should also be set, just make sure it is at least min
  54421. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  54422. case BABYLON.PhysicsJoint.DistanceJoint:
  54423. type = "jointDistance";
  54424. nativeJointData.max = jointData.maxDistance;
  54425. break;
  54426. case BABYLON.PhysicsJoint.PrismaticJoint:
  54427. type = "jointPrisme";
  54428. break;
  54429. case BABYLON.PhysicsJoint.SliderJoint:
  54430. type = "jointSlide";
  54431. break;
  54432. case BABYLON.PhysicsJoint.WheelJoint:
  54433. type = "jointWheel";
  54434. break;
  54435. case BABYLON.PhysicsJoint.HingeJoint:
  54436. default:
  54437. type = "jointHinge";
  54438. break;
  54439. }
  54440. nativeJointData.type = type;
  54441. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  54442. };
  54443. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  54444. //Bug in Oimo prevents us from disposing a joint in the playground
  54445. //joint.joint.physicsJoint.dispose();
  54446. //So we will bruteforce it!
  54447. try {
  54448. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  54449. }
  54450. catch (e) {
  54451. BABYLON.Tools.Warn(e);
  54452. }
  54453. };
  54454. OimoJSPlugin.prototype.isSupported = function () {
  54455. return OIMO !== undefined;
  54456. };
  54457. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  54458. if (!impostor.physicsBody.sleeping) {
  54459. //TODO check that
  54460. if (impostor.physicsBody.shapes.next) {
  54461. var parentShape = this._getLastShape(impostor.physicsBody);
  54462. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  54463. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  54464. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  54465. }
  54466. else {
  54467. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  54468. }
  54469. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  54470. impostor.object.rotationQuaternion.normalize();
  54471. }
  54472. };
  54473. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  54474. var body = impostor.physicsBody;
  54475. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  54476. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  54477. body.syncShapes();
  54478. body.awake();
  54479. };
  54480. OimoJSPlugin.prototype._getLastShape = function (body) {
  54481. var lastShape = body.shapes;
  54482. while (lastShape.next) {
  54483. lastShape = lastShape.next;
  54484. }
  54485. return lastShape;
  54486. };
  54487. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  54488. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  54489. };
  54490. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  54491. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  54492. };
  54493. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  54494. var v = impostor.physicsBody.linearVelocity;
  54495. if (!v)
  54496. return null;
  54497. return new BABYLON.Vector3(v.x, v.y, v.z);
  54498. };
  54499. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  54500. var v = impostor.physicsBody.angularVelocity;
  54501. if (!v)
  54502. return null;
  54503. return new BABYLON.Vector3(v.x, v.y, v.z);
  54504. };
  54505. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  54506. var staticBody = mass === 0;
  54507. //this will actually set the body's density and not its mass.
  54508. //But this is how oimo treats the mass variable.
  54509. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  54510. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  54511. };
  54512. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  54513. impostor.physicsBody.sleep();
  54514. };
  54515. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  54516. impostor.physicsBody.awake();
  54517. };
  54518. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  54519. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  54520. if (minDistance !== void 0) {
  54521. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  54522. }
  54523. };
  54524. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  54525. //TODO separate rotational and transational motors.
  54526. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  54527. if (motor) {
  54528. motor.setMotor(speed, maxForce);
  54529. }
  54530. };
  54531. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  54532. //TODO separate rotational and transational motors.
  54533. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  54534. if (motor) {
  54535. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  54536. }
  54537. };
  54538. OimoJSPlugin.prototype.dispose = function () {
  54539. this.world.clear();
  54540. };
  54541. return OimoJSPlugin;
  54542. }());
  54543. BABYLON.OimoJSPlugin = OimoJSPlugin;
  54544. })(BABYLON || (BABYLON = {}));
  54545. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  54546. var BABYLON;
  54547. (function (BABYLON) {
  54548. var Internals;
  54549. (function (Internals) {
  54550. /*
  54551. * Based on jsTGALoader - Javascript loader for TGA file
  54552. * By Vincent Thibault
  54553. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  54554. */
  54555. var TGATools = (function () {
  54556. function TGATools() {
  54557. }
  54558. TGATools.GetTGAHeader = function (data) {
  54559. var offset = 0;
  54560. var header = {
  54561. id_length: data[offset++],
  54562. colormap_type: data[offset++],
  54563. image_type: data[offset++],
  54564. colormap_index: data[offset++] | data[offset++] << 8,
  54565. colormap_length: data[offset++] | data[offset++] << 8,
  54566. colormap_size: data[offset++],
  54567. origin: [
  54568. data[offset++] | data[offset++] << 8,
  54569. data[offset++] | data[offset++] << 8
  54570. ],
  54571. width: data[offset++] | data[offset++] << 8,
  54572. height: data[offset++] | data[offset++] << 8,
  54573. pixel_size: data[offset++],
  54574. flags: data[offset++]
  54575. };
  54576. return header;
  54577. };
  54578. TGATools.UploadContent = function (gl, data) {
  54579. // Not enough data to contain header ?
  54580. if (data.length < 19) {
  54581. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  54582. return;
  54583. }
  54584. // Read Header
  54585. var offset = 18;
  54586. var header = TGATools.GetTGAHeader(data);
  54587. // Assume it's a valid Targa file.
  54588. if (header.id_length + offset > data.length) {
  54589. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  54590. return;
  54591. }
  54592. // Skip not needed data
  54593. offset += header.id_length;
  54594. var use_rle = false;
  54595. var use_pal = false;
  54596. var use_rgb = false;
  54597. var use_grey = false;
  54598. // Get some informations.
  54599. switch (header.image_type) {
  54600. case TGATools._TYPE_RLE_INDEXED:
  54601. use_rle = true;
  54602. case TGATools._TYPE_INDEXED:
  54603. use_pal = true;
  54604. break;
  54605. case TGATools._TYPE_RLE_RGB:
  54606. use_rle = true;
  54607. case TGATools._TYPE_RGB:
  54608. use_rgb = true;
  54609. break;
  54610. case TGATools._TYPE_RLE_GREY:
  54611. use_rle = true;
  54612. case TGATools._TYPE_GREY:
  54613. use_grey = true;
  54614. break;
  54615. }
  54616. var pixel_data;
  54617. var numAlphaBits = header.flags & 0xf;
  54618. var pixel_size = header.pixel_size >> 3;
  54619. var pixel_total = header.width * header.height * pixel_size;
  54620. // Read palettes
  54621. var palettes;
  54622. if (use_pal) {
  54623. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  54624. }
  54625. // Read LRE
  54626. if (use_rle) {
  54627. pixel_data = new Uint8Array(pixel_total);
  54628. var c, count, i;
  54629. var localOffset = 0;
  54630. var pixels = new Uint8Array(pixel_size);
  54631. while (offset < pixel_total && localOffset < pixel_total) {
  54632. c = data[offset++];
  54633. count = (c & 0x7f) + 1;
  54634. // RLE pixels
  54635. if (c & 0x80) {
  54636. // Bind pixel tmp array
  54637. for (i = 0; i < pixel_size; ++i) {
  54638. pixels[i] = data[offset++];
  54639. }
  54640. // Copy pixel array
  54641. for (i = 0; i < count; ++i) {
  54642. pixel_data.set(pixels, localOffset + i * pixel_size);
  54643. }
  54644. localOffset += pixel_size * count;
  54645. }
  54646. else {
  54647. count *= pixel_size;
  54648. for (i = 0; i < count; ++i) {
  54649. pixel_data[localOffset + i] = data[offset++];
  54650. }
  54651. localOffset += count;
  54652. }
  54653. }
  54654. }
  54655. else {
  54656. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  54657. }
  54658. // Load to texture
  54659. var x_start, y_start, x_step, y_step, y_end, x_end;
  54660. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  54661. default:
  54662. case TGATools._ORIGIN_UL:
  54663. x_start = 0;
  54664. x_step = 1;
  54665. x_end = header.width;
  54666. y_start = 0;
  54667. y_step = 1;
  54668. y_end = header.height;
  54669. break;
  54670. case TGATools._ORIGIN_BL:
  54671. x_start = 0;
  54672. x_step = 1;
  54673. x_end = header.width;
  54674. y_start = header.height - 1;
  54675. y_step = -1;
  54676. y_end = -1;
  54677. break;
  54678. case TGATools._ORIGIN_UR:
  54679. x_start = header.width - 1;
  54680. x_step = -1;
  54681. x_end = -1;
  54682. y_start = 0;
  54683. y_step = 1;
  54684. y_end = header.height;
  54685. break;
  54686. case TGATools._ORIGIN_BR:
  54687. x_start = header.width - 1;
  54688. x_step = -1;
  54689. x_end = -1;
  54690. y_start = header.height - 1;
  54691. y_step = -1;
  54692. y_end = -1;
  54693. break;
  54694. }
  54695. // Load the specify method
  54696. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  54697. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  54698. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  54699. };
  54700. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  54701. var image = pixel_data, colormap = palettes;
  54702. var width = header.width, height = header.height;
  54703. var color, i = 0, x, y;
  54704. var imageData = new Uint8Array(width * height * 4);
  54705. for (y = y_start; y !== y_end; y += y_step) {
  54706. for (x = x_start; x !== x_end; x += x_step, i++) {
  54707. color = image[i];
  54708. imageData[(x + width * y) * 4 + 3] = 255;
  54709. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  54710. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  54711. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  54712. }
  54713. }
  54714. return imageData;
  54715. };
  54716. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  54717. var image = pixel_data;
  54718. var width = header.width, height = header.height;
  54719. var color, i = 0, x, y;
  54720. var imageData = new Uint8Array(width * height * 4);
  54721. for (y = y_start; y !== y_end; y += y_step) {
  54722. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  54723. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  54724. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  54725. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  54726. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  54727. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  54728. }
  54729. }
  54730. return imageData;
  54731. };
  54732. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  54733. var image = pixel_data;
  54734. var width = header.width, height = header.height;
  54735. var i = 0, x, y;
  54736. var imageData = new Uint8Array(width * height * 4);
  54737. for (y = y_start; y !== y_end; y += y_step) {
  54738. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  54739. imageData[(x + width * y) * 4 + 3] = 255;
  54740. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  54741. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  54742. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  54743. }
  54744. }
  54745. return imageData;
  54746. };
  54747. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  54748. var image = pixel_data;
  54749. var width = header.width, height = header.height;
  54750. var i = 0, x, y;
  54751. var imageData = new Uint8Array(width * height * 4);
  54752. for (y = y_start; y !== y_end; y += y_step) {
  54753. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  54754. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  54755. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  54756. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  54757. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  54758. }
  54759. }
  54760. return imageData;
  54761. };
  54762. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  54763. var image = pixel_data;
  54764. var width = header.width, height = header.height;
  54765. var color, i = 0, x, y;
  54766. var imageData = new Uint8Array(width * height * 4);
  54767. for (y = y_start; y !== y_end; y += y_step) {
  54768. for (x = x_start; x !== x_end; x += x_step, i++) {
  54769. color = image[i];
  54770. imageData[(x + width * y) * 4 + 0] = color;
  54771. imageData[(x + width * y) * 4 + 1] = color;
  54772. imageData[(x + width * y) * 4 + 2] = color;
  54773. imageData[(x + width * y) * 4 + 3] = 255;
  54774. }
  54775. }
  54776. return imageData;
  54777. };
  54778. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  54779. var image = pixel_data;
  54780. var width = header.width, height = header.height;
  54781. var i = 0, x, y;
  54782. var imageData = new Uint8Array(width * height * 4);
  54783. for (y = y_start; y !== y_end; y += y_step) {
  54784. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  54785. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  54786. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  54787. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  54788. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  54789. }
  54790. }
  54791. return imageData;
  54792. };
  54793. return TGATools;
  54794. }());
  54795. TGATools._TYPE_NO_DATA = 0;
  54796. TGATools._TYPE_INDEXED = 1;
  54797. TGATools._TYPE_RGB = 2;
  54798. TGATools._TYPE_GREY = 3;
  54799. TGATools._TYPE_RLE_INDEXED = 9;
  54800. TGATools._TYPE_RLE_RGB = 10;
  54801. TGATools._TYPE_RLE_GREY = 11;
  54802. TGATools._ORIGIN_MASK = 0x30;
  54803. TGATools._ORIGIN_SHIFT = 0x04;
  54804. TGATools._ORIGIN_BL = 0x00;
  54805. TGATools._ORIGIN_BR = 0x01;
  54806. TGATools._ORIGIN_UL = 0x02;
  54807. TGATools._ORIGIN_UR = 0x03;
  54808. Internals.TGATools = TGATools;
  54809. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54810. })(BABYLON || (BABYLON = {}));
  54811. //# sourceMappingURL=babylon.tga.js.map
  54812. var BABYLON;
  54813. (function (BABYLON) {
  54814. var Internals;
  54815. (function (Internals) {
  54816. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  54817. // All values and structures referenced from:
  54818. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  54819. var DDS_MAGIC = 0x20534444;
  54820. 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;
  54821. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  54822. 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;
  54823. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  54824. function FourCCToInt32(value) {
  54825. return value.charCodeAt(0) +
  54826. (value.charCodeAt(1) << 8) +
  54827. (value.charCodeAt(2) << 16) +
  54828. (value.charCodeAt(3) << 24);
  54829. }
  54830. function Int32ToFourCC(value) {
  54831. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  54832. }
  54833. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  54834. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  54835. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  54836. var headerLengthInt = 31; // The header length in 32 bit ints
  54837. // Offsets into the header array
  54838. var off_magic = 0;
  54839. var off_size = 1;
  54840. var off_flags = 2;
  54841. var off_height = 3;
  54842. var off_width = 4;
  54843. var off_mipmapCount = 7;
  54844. var off_pfFlags = 20;
  54845. var off_pfFourCC = 21;
  54846. var off_RGBbpp = 22;
  54847. var off_RMask = 23;
  54848. var off_GMask = 24;
  54849. var off_BMask = 25;
  54850. var off_AMask = 26;
  54851. var off_caps1 = 27;
  54852. var off_caps2 = 28;
  54853. ;
  54854. var DDSTools = (function () {
  54855. function DDSTools() {
  54856. }
  54857. DDSTools.GetDDSInfo = function (arrayBuffer) {
  54858. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  54859. var mipmapCount = 1;
  54860. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  54861. mipmapCount = Math.max(1, header[off_mipmapCount]);
  54862. }
  54863. return {
  54864. width: header[off_width],
  54865. height: header[off_height],
  54866. mipmapCount: mipmapCount,
  54867. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  54868. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  54869. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  54870. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  54871. };
  54872. };
  54873. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  54874. var byteArray = new Uint8Array(dataLength);
  54875. var srcData = new Uint8Array(arrayBuffer);
  54876. var index = 0;
  54877. for (var y = height - 1; y >= 0; y--) {
  54878. for (var x = 0; x < width; x++) {
  54879. var srcPos = dataOffset + (x + y * width) * 4;
  54880. byteArray[index + 2] = srcData[srcPos];
  54881. byteArray[index + 1] = srcData[srcPos + 1];
  54882. byteArray[index] = srcData[srcPos + 2];
  54883. byteArray[index + 3] = srcData[srcPos + 3];
  54884. index += 4;
  54885. }
  54886. }
  54887. return byteArray;
  54888. };
  54889. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  54890. var byteArray = new Uint8Array(dataLength);
  54891. var srcData = new Uint8Array(arrayBuffer);
  54892. var index = 0;
  54893. for (var y = height - 1; y >= 0; y--) {
  54894. for (var x = 0; x < width; x++) {
  54895. var srcPos = dataOffset + (x + y * width) * 3;
  54896. byteArray[index + 2] = srcData[srcPos];
  54897. byteArray[index + 1] = srcData[srcPos + 1];
  54898. byteArray[index] = srcData[srcPos + 2];
  54899. index += 3;
  54900. }
  54901. }
  54902. return byteArray;
  54903. };
  54904. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  54905. var byteArray = new Uint8Array(dataLength);
  54906. var srcData = new Uint8Array(arrayBuffer);
  54907. var index = 0;
  54908. for (var y = height - 1; y >= 0; y--) {
  54909. for (var x = 0; x < width; x++) {
  54910. var srcPos = dataOffset + (x + y * width);
  54911. byteArray[index] = srcData[srcPos];
  54912. index++;
  54913. }
  54914. }
  54915. return byteArray;
  54916. };
  54917. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  54918. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  54919. if (header[off_magic] != DDS_MAGIC) {
  54920. BABYLON.Tools.Error("Invalid magic number in DDS header");
  54921. return;
  54922. }
  54923. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  54924. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  54925. return;
  54926. }
  54927. if (info.isFourCC) {
  54928. fourCC = header[off_pfFourCC];
  54929. switch (fourCC) {
  54930. case FOURCC_DXT1:
  54931. blockBytes = 8;
  54932. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  54933. break;
  54934. case FOURCC_DXT3:
  54935. blockBytes = 16;
  54936. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  54937. break;
  54938. case FOURCC_DXT5:
  54939. blockBytes = 16;
  54940. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  54941. break;
  54942. default:
  54943. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  54944. return;
  54945. }
  54946. }
  54947. mipmapCount = 1;
  54948. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  54949. mipmapCount = Math.max(1, header[off_mipmapCount]);
  54950. }
  54951. var bpp = header[off_RGBbpp];
  54952. for (var face = 0; face < faces; face++) {
  54953. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  54954. width = header[off_width];
  54955. height = header[off_height];
  54956. dataOffset = header[off_size] + 4;
  54957. for (i = 0; i < mipmapCount; ++i) {
  54958. if (info.isRGB) {
  54959. if (bpp === 24) {
  54960. dataLength = width * height * 3;
  54961. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  54962. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  54963. }
  54964. else {
  54965. dataLength = width * height * 4;
  54966. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  54967. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  54968. }
  54969. }
  54970. else if (info.isLuminance) {
  54971. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  54972. var unpaddedRowSize = width;
  54973. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  54974. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  54975. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  54976. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  54977. }
  54978. else {
  54979. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  54980. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  54981. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  54982. }
  54983. dataOffset += dataLength;
  54984. width *= 0.5;
  54985. height *= 0.5;
  54986. width = Math.max(1.0, width);
  54987. height = Math.max(1.0, height);
  54988. }
  54989. }
  54990. };
  54991. return DDSTools;
  54992. }());
  54993. Internals.DDSTools = DDSTools;
  54994. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54995. })(BABYLON || (BABYLON = {}));
  54996. //# sourceMappingURL=babylon.dds.js.map
  54997. var BABYLON;
  54998. (function (BABYLON) {
  54999. var Internals;
  55000. (function (Internals) {
  55001. /**
  55002. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  55003. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  55004. */
  55005. var KhronosTextureContainer = (function () {
  55006. /**
  55007. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  55008. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  55009. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  55010. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  55011. */
  55012. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  55013. this.arrayBuffer = arrayBuffer;
  55014. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  55015. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  55016. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  55017. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  55018. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  55019. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  55020. BABYLON.Tools.Error("texture missing KTX identifier");
  55021. return;
  55022. }
  55023. // load the reset of the header in native 32 bit int
  55024. var header = new Int32Array(this.arrayBuffer, 12, 13);
  55025. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  55026. var oppositeEndianess = header[0] === 0x01020304;
  55027. // read all the header elements in order they exist in the file, without modification (sans endainness)
  55028. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  55029. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  55030. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  55031. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  55032. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  55033. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  55034. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  55035. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  55036. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  55037. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  55038. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  55039. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  55040. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  55041. if (this.glType !== 0) {
  55042. BABYLON.Tools.Error("only compressed formats currently supported");
  55043. return;
  55044. }
  55045. else {
  55046. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  55047. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  55048. }
  55049. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  55050. BABYLON.Tools.Error("only 2D textures currently supported");
  55051. return;
  55052. }
  55053. if (this.numberOfArrayElements !== 0) {
  55054. BABYLON.Tools.Error("texture arrays not currently supported");
  55055. return;
  55056. }
  55057. if (this.numberOfFaces !== facesExpected) {
  55058. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  55059. return;
  55060. }
  55061. // we now have a completely validated file, so could use existence of loadType as success
  55062. // would need to make this more elaborate & adjust checks above to support more than one load type
  55063. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  55064. }
  55065. // not as fast hardware based, but will probably never need to use
  55066. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  55067. return ((val & 0xFF) << 24)
  55068. | ((val & 0xFF00) << 8)
  55069. | ((val >> 8) & 0xFF00)
  55070. | ((val >> 24) & 0xFF);
  55071. };
  55072. /**
  55073. * It is assumed that the texture has already been created & is currently bound
  55074. */
  55075. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  55076. switch (this.loadType) {
  55077. case KhronosTextureContainer.COMPRESSED_2D:
  55078. this._upload2DCompressedLevels(gl, loadMipmaps);
  55079. break;
  55080. case KhronosTextureContainer.TEX_2D:
  55081. case KhronosTextureContainer.COMPRESSED_3D:
  55082. case KhronosTextureContainer.TEX_3D:
  55083. }
  55084. };
  55085. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  55086. // initialize width & height for level 1
  55087. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  55088. var width = this.pixelWidth;
  55089. var height = this.pixelHeight;
  55090. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  55091. for (var level = 0; level < mipmapCount; level++) {
  55092. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  55093. for (var face = 0; face < this.numberOfFaces; face++) {
  55094. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  55095. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  55096. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  55097. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  55098. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  55099. }
  55100. width = Math.max(1.0, width * 0.5);
  55101. height = Math.max(1.0, height * 0.5);
  55102. }
  55103. };
  55104. return KhronosTextureContainer;
  55105. }());
  55106. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  55107. // load types
  55108. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  55109. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  55110. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  55111. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  55112. Internals.KhronosTextureContainer = KhronosTextureContainer;
  55113. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55114. })(BABYLON || (BABYLON = {}));
  55115. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  55116. var BABYLON;
  55117. (function (BABYLON) {
  55118. var Debug;
  55119. (function (Debug) {
  55120. /**
  55121. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  55122. */
  55123. var SkeletonViewer = (function () {
  55124. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  55125. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  55126. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  55127. this.skeleton = skeleton;
  55128. this.mesh = mesh;
  55129. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  55130. this.renderingGroupId = renderingGroupId;
  55131. this.color = BABYLON.Color3.White();
  55132. this._debugLines = [];
  55133. this._isEnabled = false;
  55134. this._scene = scene;
  55135. this.update();
  55136. this._renderFunction = this.update.bind(this);
  55137. }
  55138. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  55139. get: function () {
  55140. return this._isEnabled;
  55141. },
  55142. set: function (value) {
  55143. if (this._isEnabled === value) {
  55144. return;
  55145. }
  55146. this._isEnabled = value;
  55147. if (value) {
  55148. this._scene.registerBeforeRender(this._renderFunction);
  55149. }
  55150. else {
  55151. this._scene.unregisterBeforeRender(this._renderFunction);
  55152. }
  55153. },
  55154. enumerable: true,
  55155. configurable: true
  55156. });
  55157. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  55158. if (x === void 0) { x = 0; }
  55159. if (y === void 0) { y = 0; }
  55160. if (z === void 0) { z = 0; }
  55161. var tmat = BABYLON.Tmp.Matrix[0];
  55162. var parentBone = bone.getParent();
  55163. tmat.copyFrom(bone.getLocalMatrix());
  55164. if (x !== 0 || y !== 0 || z !== 0) {
  55165. var tmat2 = BABYLON.Tmp.Matrix[1];
  55166. BABYLON.Matrix.IdentityToRef(tmat2);
  55167. tmat2.m[12] = x;
  55168. tmat2.m[13] = y;
  55169. tmat2.m[14] = z;
  55170. tmat2.multiplyToRef(tmat, tmat);
  55171. }
  55172. if (parentBone) {
  55173. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  55174. }
  55175. tmat.multiplyToRef(meshMat, tmat);
  55176. position.x = tmat.m[12];
  55177. position.y = tmat.m[13];
  55178. position.z = tmat.m[14];
  55179. };
  55180. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  55181. var len = bones.length;
  55182. for (var i = 0; i < len; i++) {
  55183. var bone = bones[i];
  55184. var points = this._debugLines[i];
  55185. if (!points) {
  55186. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55187. this._debugLines[i] = points;
  55188. }
  55189. this._getBonePosition(points[0], bone, meshMat);
  55190. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  55191. }
  55192. };
  55193. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  55194. var len = bones.length;
  55195. var boneNum = 0;
  55196. for (var i = len - 1; i >= 0; i--) {
  55197. var childBone = bones[i];
  55198. var parentBone = childBone.getParent();
  55199. if (!parentBone) {
  55200. continue;
  55201. }
  55202. var points = this._debugLines[boneNum];
  55203. if (!points) {
  55204. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55205. this._debugLines[boneNum] = points;
  55206. }
  55207. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  55208. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  55209. boneNum++;
  55210. }
  55211. };
  55212. SkeletonViewer.prototype.update = function () {
  55213. if (this.autoUpdateBonesMatrices) {
  55214. this.skeleton.computeAbsoluteTransforms();
  55215. }
  55216. if (this.skeleton.bones[0].length === undefined) {
  55217. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  55218. }
  55219. else {
  55220. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  55221. }
  55222. if (!this._debugMesh) {
  55223. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  55224. this._debugMesh.renderingGroupId = this.renderingGroupId;
  55225. }
  55226. else {
  55227. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  55228. }
  55229. this._debugMesh.color = this.color;
  55230. };
  55231. SkeletonViewer.prototype.dispose = function () {
  55232. if (this._debugMesh) {
  55233. this.isEnabled = false;
  55234. this._debugMesh.dispose();
  55235. this._debugMesh = null;
  55236. }
  55237. };
  55238. return SkeletonViewer;
  55239. }());
  55240. Debug.SkeletonViewer = SkeletonViewer;
  55241. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  55242. })(BABYLON || (BABYLON = {}));
  55243. //# sourceMappingURL=babylon.skeletonViewer.js.map
  55244. var BABYLON;
  55245. (function (BABYLON) {
  55246. var Debug;
  55247. (function (Debug) {
  55248. var AxesViewer = (function () {
  55249. function AxesViewer(scene, scaleLines) {
  55250. if (scaleLines === void 0) { scaleLines = 1; }
  55251. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55252. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55253. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55254. this.scaleLines = 1;
  55255. this.scaleLines = scaleLines;
  55256. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  55257. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  55258. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  55259. this._xmesh.renderingGroupId = 2;
  55260. this._ymesh.renderingGroupId = 2;
  55261. this._zmesh.renderingGroupId = 2;
  55262. this._xmesh.material.checkReadyOnlyOnce = true;
  55263. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  55264. this._ymesh.material.checkReadyOnlyOnce = true;
  55265. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  55266. this._zmesh.material.checkReadyOnlyOnce = true;
  55267. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  55268. this.scene = scene;
  55269. }
  55270. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  55271. var scaleLines = this.scaleLines;
  55272. var point1 = this._xline[0];
  55273. var point2 = this._xline[1];
  55274. point1.x = position.x;
  55275. point1.y = position.y;
  55276. point1.z = position.z;
  55277. point2.x = point1.x + xaxis.x * scaleLines;
  55278. point2.y = point1.y + xaxis.y * scaleLines;
  55279. point2.z = point1.z + xaxis.z * scaleLines;
  55280. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  55281. point1 = this._yline[0];
  55282. point2 = this._yline[1];
  55283. point1.x = position.x;
  55284. point1.y = position.y;
  55285. point1.z = position.z;
  55286. point2.x = point1.x + yaxis.x * scaleLines;
  55287. point2.y = point1.y + yaxis.y * scaleLines;
  55288. point2.z = point1.z + yaxis.z * scaleLines;
  55289. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  55290. point1 = this._zline[0];
  55291. point2 = this._zline[1];
  55292. point1.x = position.x;
  55293. point1.y = position.y;
  55294. point1.z = position.z;
  55295. point2.x = point1.x + zaxis.x * scaleLines;
  55296. point2.y = point1.y + zaxis.y * scaleLines;
  55297. point2.z = point1.z + zaxis.z * scaleLines;
  55298. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  55299. };
  55300. AxesViewer.prototype.dispose = function () {
  55301. if (this._xmesh) {
  55302. this._xmesh.dispose();
  55303. this._ymesh.dispose();
  55304. this._zmesh.dispose();
  55305. this._xmesh = null;
  55306. this._ymesh = null;
  55307. this._zmesh = null;
  55308. this._xline = null;
  55309. this._yline = null;
  55310. this._zline = null;
  55311. this.scene = null;
  55312. }
  55313. };
  55314. return AxesViewer;
  55315. }());
  55316. Debug.AxesViewer = AxesViewer;
  55317. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  55318. })(BABYLON || (BABYLON = {}));
  55319. //# sourceMappingURL=babylon.axesViewer.js.map
  55320. var BABYLON;
  55321. (function (BABYLON) {
  55322. var Debug;
  55323. (function (Debug) {
  55324. var BoneAxesViewer = (function (_super) {
  55325. __extends(BoneAxesViewer, _super);
  55326. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  55327. if (scaleLines === void 0) { scaleLines = 1; }
  55328. var _this = _super.call(this, scene, scaleLines) || this;
  55329. _this.pos = BABYLON.Vector3.Zero();
  55330. _this.xaxis = BABYLON.Vector3.Zero();
  55331. _this.yaxis = BABYLON.Vector3.Zero();
  55332. _this.zaxis = BABYLON.Vector3.Zero();
  55333. _this.mesh = mesh;
  55334. _this.bone = bone;
  55335. return _this;
  55336. }
  55337. BoneAxesViewer.prototype.update = function () {
  55338. var bone = this.bone;
  55339. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  55340. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  55341. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  55342. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  55343. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  55344. };
  55345. BoneAxesViewer.prototype.dispose = function () {
  55346. if (this.pos) {
  55347. this.pos = null;
  55348. this.xaxis = null;
  55349. this.yaxis = null;
  55350. this.zaxis = null;
  55351. this.mesh = null;
  55352. this.bone = null;
  55353. _super.prototype.dispose.call(this);
  55354. }
  55355. };
  55356. return BoneAxesViewer;
  55357. }(Debug.AxesViewer));
  55358. Debug.BoneAxesViewer = BoneAxesViewer;
  55359. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  55360. })(BABYLON || (BABYLON = {}));
  55361. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  55362. var BABYLON;
  55363. (function (BABYLON) {
  55364. var RayHelper = (function () {
  55365. function RayHelper(ray) {
  55366. this.ray = ray;
  55367. }
  55368. RayHelper.CreateAndShow = function (ray, scene, color) {
  55369. var helper = new RayHelper(ray);
  55370. helper.show(scene, color);
  55371. return helper;
  55372. };
  55373. RayHelper.prototype.show = function (scene, color) {
  55374. if (!this._renderFunction) {
  55375. var ray = this.ray;
  55376. this._renderFunction = this._render.bind(this);
  55377. this._scene = scene;
  55378. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  55379. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  55380. this._scene.registerBeforeRender(this._renderFunction);
  55381. }
  55382. if (color) {
  55383. this._renderLine.color.copyFrom(color);
  55384. }
  55385. };
  55386. RayHelper.prototype.hide = function () {
  55387. if (this._renderFunction) {
  55388. this._scene.unregisterBeforeRender(this._renderFunction);
  55389. this._scene = null;
  55390. this._renderFunction = null;
  55391. this._renderLine.dispose();
  55392. this._renderLine = null;
  55393. this._renderPoints = null;
  55394. }
  55395. };
  55396. RayHelper.prototype._render = function () {
  55397. var ray = this.ray;
  55398. var point = this._renderPoints[1];
  55399. var len = Math.min(ray.length, 1000000);
  55400. point.copyFrom(ray.direction);
  55401. point.scaleInPlace(len);
  55402. point.addInPlace(ray.origin);
  55403. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  55404. };
  55405. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  55406. this._attachedToMesh = mesh;
  55407. var ray = this.ray;
  55408. if (!ray.direction) {
  55409. ray.direction = BABYLON.Vector3.Zero();
  55410. }
  55411. if (!ray.origin) {
  55412. ray.origin = BABYLON.Vector3.Zero();
  55413. }
  55414. if (length) {
  55415. ray.length = length;
  55416. }
  55417. if (!meshSpaceOrigin) {
  55418. meshSpaceOrigin = BABYLON.Vector3.Zero();
  55419. }
  55420. if (!meshSpaceDirection) {
  55421. // -1 so that this will work with Mesh.lookAt
  55422. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  55423. }
  55424. if (!this._meshSpaceDirection) {
  55425. this._meshSpaceDirection = meshSpaceDirection.clone();
  55426. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  55427. }
  55428. else {
  55429. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  55430. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  55431. }
  55432. if (!this._updateToMeshFunction) {
  55433. this._updateToMeshFunction = this._updateToMesh.bind(this);
  55434. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  55435. }
  55436. this._updateToMesh();
  55437. };
  55438. RayHelper.prototype.detachFromMesh = function () {
  55439. if (this._attachedToMesh) {
  55440. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  55441. this._attachedToMesh = null;
  55442. this._updateToMeshFunction = null;
  55443. }
  55444. };
  55445. RayHelper.prototype._updateToMesh = function () {
  55446. var ray = this.ray;
  55447. if (this._attachedToMesh._isDisposed) {
  55448. this.detachFromMesh();
  55449. return;
  55450. }
  55451. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  55452. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  55453. };
  55454. RayHelper.prototype.dispose = function () {
  55455. this.hide();
  55456. this.detachFromMesh();
  55457. this.ray = null;
  55458. };
  55459. return RayHelper;
  55460. }());
  55461. BABYLON.RayHelper = RayHelper;
  55462. })(BABYLON || (BABYLON = {}));
  55463. //# sourceMappingURL=babylon.rayHelper.js.map
  55464. var BABYLON;
  55465. (function (BABYLON) {
  55466. var DebugLayer = (function () {
  55467. function DebugLayer(scene) {
  55468. this._scene = scene;
  55469. }
  55470. /** Creates the inspector window. */
  55471. DebugLayer.prototype._createInspector = function (config) {
  55472. if (config === void 0) { config = {}; }
  55473. var popup = config.popup || false;
  55474. var initialTab = config.initialTab || 0;
  55475. var parentElement = config.parentElement || null;
  55476. if (!this._inspector) {
  55477. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  55478. } // else nothing to do,; instance is already existing
  55479. };
  55480. DebugLayer.prototype.isVisible = function () {
  55481. if (!this._inspector) {
  55482. return false;
  55483. }
  55484. return true;
  55485. };
  55486. DebugLayer.prototype.hide = function () {
  55487. if (this._inspector) {
  55488. try {
  55489. this._inspector.dispose();
  55490. }
  55491. catch (e) {
  55492. // If the inspector has been removed directly from the inspector tool
  55493. }
  55494. this._inspector = null;
  55495. }
  55496. };
  55497. DebugLayer.prototype.show = function (config) {
  55498. if (config === void 0) { config = {}; }
  55499. if (typeof INSPECTOR == 'undefined') {
  55500. // Load inspector and add it to the DOM
  55501. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  55502. }
  55503. else {
  55504. // Otherwise creates the inspector
  55505. this._createInspector(config);
  55506. }
  55507. };
  55508. return DebugLayer;
  55509. }());
  55510. // Get protocol used - http or https
  55511. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//www.babylonjs.com/babylon.inspector.bundle.js';
  55512. BABYLON.DebugLayer = DebugLayer;
  55513. })(BABYLON || (BABYLON = {}));
  55514. //# sourceMappingURL=babylon.debugLayer.js.map
  55515. var BABYLON;
  55516. (function (BABYLON) {
  55517. var BoundingBoxRenderer = (function () {
  55518. function BoundingBoxRenderer(scene) {
  55519. this.frontColor = new BABYLON.Color3(1, 1, 1);
  55520. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  55521. this.showBackLines = true;
  55522. this.renderList = new BABYLON.SmartArray(32);
  55523. this._vertexBuffers = {};
  55524. this._scene = scene;
  55525. }
  55526. BoundingBoxRenderer.prototype._prepareRessources = function () {
  55527. if (this._colorShader) {
  55528. return;
  55529. }
  55530. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  55531. attributes: [BABYLON.VertexBuffer.PositionKind],
  55532. uniforms: ["worldViewProjection", "color"]
  55533. });
  55534. var engine = this._scene.getEngine();
  55535. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  55536. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  55537. 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]);
  55538. };
  55539. BoundingBoxRenderer.prototype.reset = function () {
  55540. this.renderList.reset();
  55541. };
  55542. BoundingBoxRenderer.prototype.render = function () {
  55543. if (this.renderList.length === 0) {
  55544. return;
  55545. }
  55546. this._prepareRessources();
  55547. if (!this._colorShader.isReady()) {
  55548. return;
  55549. }
  55550. var engine = this._scene.getEngine();
  55551. engine.setDepthWrite(false);
  55552. this._colorShader._preBind();
  55553. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  55554. var boundingBox = this.renderList.data[boundingBoxIndex];
  55555. var min = boundingBox.minimum;
  55556. var max = boundingBox.maximum;
  55557. var diff = max.subtract(min);
  55558. var median = min.add(diff.scale(0.5));
  55559. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  55560. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  55561. .multiply(boundingBox.getWorldMatrix());
  55562. // VBOs
  55563. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  55564. if (this.showBackLines) {
  55565. // Back
  55566. engine.setDepthFunctionToGreaterOrEqual();
  55567. this._scene.resetCachedMaterial();
  55568. this._colorShader.setColor4("color", this.backColor.toColor4());
  55569. this._colorShader.bind(worldMatrix);
  55570. // Draw order
  55571. engine.draw(false, 0, 24);
  55572. }
  55573. // Front
  55574. engine.setDepthFunctionToLess();
  55575. this._scene.resetCachedMaterial();
  55576. this._colorShader.setColor4("color", this.frontColor.toColor4());
  55577. this._colorShader.bind(worldMatrix);
  55578. // Draw order
  55579. engine.draw(false, 0, 24);
  55580. }
  55581. this._colorShader.unbind();
  55582. engine.setDepthFunctionToLessOrEqual();
  55583. engine.setDepthWrite(true);
  55584. };
  55585. BoundingBoxRenderer.prototype.dispose = function () {
  55586. if (!this._colorShader) {
  55587. return;
  55588. }
  55589. this.renderList.dispose();
  55590. this._colorShader.dispose();
  55591. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55592. if (buffer) {
  55593. buffer.dispose();
  55594. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  55595. }
  55596. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55597. };
  55598. return BoundingBoxRenderer;
  55599. }());
  55600. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  55601. })(BABYLON || (BABYLON = {}));
  55602. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  55603. var BABYLON;
  55604. (function (BABYLON) {
  55605. var MorphTarget = (function () {
  55606. function MorphTarget(name, influence) {
  55607. if (influence === void 0) { influence = 0; }
  55608. this.name = name;
  55609. this.onInfluenceChanged = new BABYLON.Observable();
  55610. this.influence = influence;
  55611. }
  55612. Object.defineProperty(MorphTarget.prototype, "influence", {
  55613. get: function () {
  55614. return this._influence;
  55615. },
  55616. set: function (influence) {
  55617. if (this._influence === influence) {
  55618. return;
  55619. }
  55620. var previous = this._influence;
  55621. this._influence = influence;
  55622. if (this.onInfluenceChanged.hasObservers) {
  55623. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  55624. }
  55625. },
  55626. enumerable: true,
  55627. configurable: true
  55628. });
  55629. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  55630. get: function () {
  55631. return this._normals !== undefined;
  55632. },
  55633. enumerable: true,
  55634. configurable: true
  55635. });
  55636. MorphTarget.prototype.setPositions = function (data) {
  55637. this._positions = new Float32Array(data);
  55638. };
  55639. MorphTarget.prototype.getPositions = function () {
  55640. return this._positions;
  55641. };
  55642. MorphTarget.prototype.setNormals = function (data) {
  55643. this._normals = new Float32Array(data);
  55644. };
  55645. MorphTarget.prototype.getNormals = function () {
  55646. return this._normals;
  55647. };
  55648. /**
  55649. * Serializes the current target into a Serialization object.
  55650. * Returns the serialized object.
  55651. */
  55652. MorphTarget.prototype.serialize = function () {
  55653. var serializationObject = {};
  55654. serializationObject.name = this.name;
  55655. serializationObject.influence = this.influence;
  55656. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  55657. if (this.hasNormals) {
  55658. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  55659. }
  55660. return serializationObject;
  55661. };
  55662. // Statics
  55663. MorphTarget.Parse = function (serializationObject) {
  55664. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  55665. result.setPositions(serializationObject.positions);
  55666. if (serializationObject.normals) {
  55667. result.setNormals(serializationObject.normals);
  55668. }
  55669. return result;
  55670. };
  55671. MorphTarget.FromMesh = function (mesh, name, influence) {
  55672. if (!name) {
  55673. name = mesh.name;
  55674. }
  55675. var result = new MorphTarget(name, influence);
  55676. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  55677. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55678. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  55679. }
  55680. return result;
  55681. };
  55682. return MorphTarget;
  55683. }());
  55684. BABYLON.MorphTarget = MorphTarget;
  55685. })(BABYLON || (BABYLON = {}));
  55686. //# sourceMappingURL=babylon.morphTarget.js.map
  55687. var BABYLON;
  55688. (function (BABYLON) {
  55689. var MorphTargetManager = (function () {
  55690. function MorphTargetManager(scene) {
  55691. this._targets = new Array();
  55692. this._targetObservable = new Array();
  55693. this._activeTargets = new BABYLON.SmartArray(16);
  55694. this._supportsNormals = false;
  55695. this._vertexCount = 0;
  55696. this._uniqueId = 0;
  55697. if (!scene) {
  55698. scene = BABYLON.Engine.LastCreatedScene;
  55699. }
  55700. this._scene = scene;
  55701. this._scene.morphTargetManagers.push(this);
  55702. this._uniqueId = scene.getUniqueId();
  55703. }
  55704. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  55705. get: function () {
  55706. return this._uniqueId;
  55707. },
  55708. enumerable: true,
  55709. configurable: true
  55710. });
  55711. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  55712. get: function () {
  55713. return this._vertexCount;
  55714. },
  55715. enumerable: true,
  55716. configurable: true
  55717. });
  55718. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  55719. get: function () {
  55720. return this._supportsNormals;
  55721. },
  55722. enumerable: true,
  55723. configurable: true
  55724. });
  55725. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  55726. get: function () {
  55727. return this._activeTargets.length;
  55728. },
  55729. enumerable: true,
  55730. configurable: true
  55731. });
  55732. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  55733. get: function () {
  55734. return this._influences;
  55735. },
  55736. enumerable: true,
  55737. configurable: true
  55738. });
  55739. MorphTargetManager.prototype.getActiveTarget = function (index) {
  55740. return this._activeTargets.data[index];
  55741. };
  55742. MorphTargetManager.prototype.addTarget = function (target) {
  55743. var _this = this;
  55744. if (this._vertexCount) {
  55745. if (this._vertexCount !== target.getPositions().length / 3) {
  55746. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  55747. return;
  55748. }
  55749. }
  55750. this._targets.push(target);
  55751. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  55752. _this._syncActiveTargets(needUpdate);
  55753. }));
  55754. this._syncActiveTargets(true);
  55755. };
  55756. MorphTargetManager.prototype.removeTarget = function (target) {
  55757. var index = this._targets.indexOf(target);
  55758. if (index >= 0) {
  55759. this._targets.splice(index, 1);
  55760. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  55761. this._vertexCount = 0;
  55762. this._syncActiveTargets(true);
  55763. }
  55764. };
  55765. /**
  55766. * Serializes the current manager into a Serialization object.
  55767. * Returns the serialized object.
  55768. */
  55769. MorphTargetManager.prototype.serialize = function () {
  55770. var serializationObject = {};
  55771. serializationObject.id = this.uniqueId;
  55772. serializationObject.targets = [];
  55773. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  55774. var target = _a[_i];
  55775. serializationObject.targets.push(target.serialize());
  55776. }
  55777. return serializationObject;
  55778. };
  55779. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  55780. this._syncActiveTargets(needUpdate);
  55781. };
  55782. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  55783. this._activeTargets.reset();
  55784. var tempInfluences = [];
  55785. this._supportsNormals = true;
  55786. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  55787. var target = _a[_i];
  55788. if (target.influence > 0) {
  55789. this._activeTargets.push(target);
  55790. tempInfluences.push(target.influence);
  55791. this._supportsNormals = this._supportsNormals && target.hasNormals;
  55792. if (this._vertexCount === 0) {
  55793. this._vertexCount = target.getPositions().length / 3;
  55794. }
  55795. }
  55796. }
  55797. this._influences = new Float32Array(tempInfluences);
  55798. if (needUpdate) {
  55799. // Flag meshes as dirty to resync with the active targets
  55800. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  55801. var mesh = _c[_b];
  55802. if (mesh.morphTargetManager === this) {
  55803. mesh._syncGeometryWithMorphTargetManager();
  55804. }
  55805. }
  55806. }
  55807. };
  55808. // Statics
  55809. MorphTargetManager.Parse = function (serializationObject, scene) {
  55810. var result = new MorphTargetManager(scene);
  55811. result._uniqueId = serializationObject.id;
  55812. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  55813. var targetData = _a[_i];
  55814. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  55815. }
  55816. return result;
  55817. };
  55818. return MorphTargetManager;
  55819. }());
  55820. BABYLON.MorphTargetManager = MorphTargetManager;
  55821. })(BABYLON || (BABYLON = {}));
  55822. //# sourceMappingURL=babylon.morphTargetManager.js.map
  55823. var BABYLON;
  55824. (function (BABYLON) {
  55825. /**
  55826. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  55827. * It can help converting any input color in a desired output one. This can then be used to create effects
  55828. * from sepia, black and white to sixties or futuristic rendering...
  55829. *
  55830. * The only supported format is currently 3dl.
  55831. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  55832. */
  55833. var ColorGradingTexture = (function (_super) {
  55834. __extends(ColorGradingTexture, _super);
  55835. /**
  55836. * Instantiates a ColorGradingTexture from the following parameters.
  55837. *
  55838. * @param url The location of the color gradind data (currently only supporting 3dl)
  55839. * @param scene The scene the texture will be used in
  55840. */
  55841. function ColorGradingTexture(url, scene) {
  55842. var _this = _super.call(this, scene) || this;
  55843. if (!url) {
  55844. return _this;
  55845. }
  55846. _this._textureMatrix = BABYLON.Matrix.Identity();
  55847. _this.name = url;
  55848. _this.url = url;
  55849. _this.hasAlpha = false;
  55850. _this.isCube = false;
  55851. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55852. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55853. _this.anisotropicFilteringLevel = 1;
  55854. _this._texture = _this._getFromCache(url, true);
  55855. if (!_this._texture) {
  55856. if (!scene.useDelayedTextureLoading) {
  55857. _this.loadTexture();
  55858. }
  55859. else {
  55860. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  55861. }
  55862. }
  55863. return _this;
  55864. }
  55865. /**
  55866. * Returns the texture matrix used in most of the material.
  55867. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  55868. */
  55869. ColorGradingTexture.prototype.getTextureMatrix = function () {
  55870. return this._textureMatrix;
  55871. };
  55872. /**
  55873. * Occurs when the file being loaded is a .3dl LUT file.
  55874. */
  55875. ColorGradingTexture.prototype.load3dlTexture = function () {
  55876. var _this = this;
  55877. var mipLevels = 0;
  55878. var floatArrayView = null;
  55879. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55880. this._texture = texture;
  55881. var callback = function (text) {
  55882. var data;
  55883. var tempData;
  55884. var line;
  55885. var lines = text.split('\n');
  55886. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  55887. var maxColor = 0;
  55888. for (var i = 0; i < lines.length; i++) {
  55889. line = lines[i];
  55890. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  55891. continue;
  55892. if (line.indexOf('#') === 0)
  55893. continue;
  55894. var words = line.split(" ");
  55895. if (size === 0) {
  55896. // Number of space + one
  55897. size = words.length;
  55898. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  55899. tempData = new Float32Array(size * size * size * 4);
  55900. continue;
  55901. }
  55902. if (size != 0) {
  55903. var r = Math.max(parseInt(words[0]), 0);
  55904. var g = Math.max(parseInt(words[1]), 0);
  55905. var b = Math.max(parseInt(words[2]), 0);
  55906. maxColor = Math.max(r, maxColor);
  55907. maxColor = Math.max(g, maxColor);
  55908. maxColor = Math.max(b, maxColor);
  55909. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  55910. tempData[pixelStorageIndex + 0] = r;
  55911. tempData[pixelStorageIndex + 1] = g;
  55912. tempData[pixelStorageIndex + 2] = b;
  55913. tempData[pixelStorageIndex + 3] = 0;
  55914. pixelIndexSlice++;
  55915. if (pixelIndexSlice % size == 0) {
  55916. pixelIndexH++;
  55917. pixelIndexSlice = 0;
  55918. if (pixelIndexH % size == 0) {
  55919. pixelIndexW++;
  55920. pixelIndexH = 0;
  55921. }
  55922. }
  55923. }
  55924. }
  55925. for (var i = 0; i < tempData.length; i++) {
  55926. var value = tempData[i];
  55927. data[i] = (value / maxColor * 255);
  55928. }
  55929. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  55930. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  55931. };
  55932. BABYLON.Tools.LoadFile(this.url, callback);
  55933. return this._texture;
  55934. };
  55935. /**
  55936. * Starts the loading process of the texture.
  55937. */
  55938. ColorGradingTexture.prototype.loadTexture = function () {
  55939. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  55940. this.load3dlTexture();
  55941. }
  55942. };
  55943. /**
  55944. * Clones the color gradind texture.
  55945. */
  55946. ColorGradingTexture.prototype.clone = function () {
  55947. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  55948. // Base texture
  55949. newTexture.level = this.level;
  55950. return newTexture;
  55951. };
  55952. /**
  55953. * Called during delayed load for textures.
  55954. */
  55955. ColorGradingTexture.prototype.delayLoad = function () {
  55956. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  55957. return;
  55958. }
  55959. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  55960. this._texture = this._getFromCache(this.url, true);
  55961. if (!this._texture) {
  55962. this.loadTexture();
  55963. }
  55964. };
  55965. /**
  55966. * Binds the color grading to the shader.
  55967. * @param colorGrading The texture to bind
  55968. * @param effect The effect to bind to
  55969. */
  55970. ColorGradingTexture.Bind = function (colorGrading, effect) {
  55971. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  55972. var x = colorGrading.level; // Texture Level
  55973. var y = colorGrading.getSize().height; // Texture Size example with 8
  55974. var z = y - 1.0; // SizeMinusOne 8 - 1
  55975. var w = 1 / y; // Space of 1 slice 1 / 8
  55976. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  55977. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  55978. 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
  55979. 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
  55980. 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
  55981. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  55982. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  55983. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  55984. };
  55985. /**
  55986. * Prepare the list of uniforms associated with the ColorGrading effects.
  55987. * @param uniformsList The list of uniforms used in the effect
  55988. * @param samplersList The list of samplers used in the effect
  55989. */
  55990. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  55991. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  55992. samplersList.push("cameraColorGrading2DSampler");
  55993. };
  55994. /**
  55995. * Parses a color grading texture serialized by Babylon.
  55996. * @param parsedTexture The texture information being parsedTexture
  55997. * @param scene The scene to load the texture in
  55998. * @param rootUrl The root url of the data assets to load
  55999. * @return A color gradind texture
  56000. */
  56001. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56002. var texture = null;
  56003. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  56004. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  56005. texture.name = parsedTexture.name;
  56006. texture.level = parsedTexture.level;
  56007. }
  56008. return texture;
  56009. };
  56010. /**
  56011. * Serializes the LUT texture to json format.
  56012. */
  56013. ColorGradingTexture.prototype.serialize = function () {
  56014. if (!this.name) {
  56015. return null;
  56016. }
  56017. var serializationObject = {};
  56018. serializationObject.name = this.name;
  56019. serializationObject.level = this.level;
  56020. serializationObject.customType = "BABYLON.ColorGradingTexture";
  56021. return serializationObject;
  56022. };
  56023. return ColorGradingTexture;
  56024. }(BABYLON.BaseTexture));
  56025. /**
  56026. * Empty line regex stored for GC.
  56027. */
  56028. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  56029. BABYLON.ColorGradingTexture = ColorGradingTexture;
  56030. })(BABYLON || (BABYLON = {}));
  56031. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  56032. var BABYLON;
  56033. (function (BABYLON) {
  56034. /**
  56035. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  56036. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  56037. * 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;
  56038. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  56039. */
  56040. var ColorCurves = (function () {
  56041. function ColorCurves() {
  56042. this._dirty = true;
  56043. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  56044. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  56045. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  56046. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  56047. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  56048. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  56049. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  56050. this._globalHue = 30;
  56051. this._globalDensity = 0;
  56052. this._globalSaturation = 0;
  56053. this._globalExposure = 0;
  56054. this._highlightsHue = 30;
  56055. this._highlightsDensity = 0;
  56056. this._highlightsSaturation = 0;
  56057. this._highlightsExposure = 0;
  56058. this._midtonesHue = 30;
  56059. this._midtonesDensity = 0;
  56060. this._midtonesSaturation = 0;
  56061. this._midtonesExposure = 0;
  56062. this._shadowsHue = 30;
  56063. this._shadowsDensity = 0;
  56064. this._shadowsSaturation = 0;
  56065. this._shadowsExposure = 0;
  56066. }
  56067. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  56068. /**
  56069. * Gets the global Hue value.
  56070. * 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).
  56071. */
  56072. get: function () {
  56073. return this._globalHue;
  56074. },
  56075. /**
  56076. * Sets the global Hue value.
  56077. * 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).
  56078. */
  56079. set: function (value) {
  56080. this._globalHue = value;
  56081. this._dirty = true;
  56082. },
  56083. enumerable: true,
  56084. configurable: true
  56085. });
  56086. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  56087. /**
  56088. * Gets the global Density value.
  56089. * 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.
  56090. * Values less than zero provide a filter of opposite hue.
  56091. */
  56092. get: function () {
  56093. return this._globalDensity;
  56094. },
  56095. /**
  56096. * Sets the global Density value.
  56097. * 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.
  56098. * Values less than zero provide a filter of opposite hue.
  56099. */
  56100. set: function (value) {
  56101. this._globalDensity = value;
  56102. this._dirty = true;
  56103. },
  56104. enumerable: true,
  56105. configurable: true
  56106. });
  56107. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  56108. /**
  56109. * Gets the global Saturation value.
  56110. * 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.
  56111. */
  56112. get: function () {
  56113. return this._globalSaturation;
  56114. },
  56115. /**
  56116. * Sets the global Saturation value.
  56117. * 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.
  56118. */
  56119. set: function (value) {
  56120. this._globalSaturation = value;
  56121. this._dirty = true;
  56122. },
  56123. enumerable: true,
  56124. configurable: true
  56125. });
  56126. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  56127. /**
  56128. * Gets the highlights Hue value.
  56129. * 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).
  56130. */
  56131. get: function () {
  56132. return this._highlightsHue;
  56133. },
  56134. /**
  56135. * Sets the highlights Hue value.
  56136. * 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).
  56137. */
  56138. set: function (value) {
  56139. this._highlightsHue = value;
  56140. this._dirty = true;
  56141. },
  56142. enumerable: true,
  56143. configurable: true
  56144. });
  56145. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  56146. /**
  56147. * Gets the highlights Density value.
  56148. * 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.
  56149. * Values less than zero provide a filter of opposite hue.
  56150. */
  56151. get: function () {
  56152. return this._highlightsDensity;
  56153. },
  56154. /**
  56155. * Sets the highlights Density value.
  56156. * 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.
  56157. * Values less than zero provide a filter of opposite hue.
  56158. */
  56159. set: function (value) {
  56160. this._highlightsDensity = value;
  56161. this._dirty = true;
  56162. },
  56163. enumerable: true,
  56164. configurable: true
  56165. });
  56166. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  56167. /**
  56168. * Gets the highlights Saturation value.
  56169. * 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.
  56170. */
  56171. get: function () {
  56172. return this._highlightsSaturation;
  56173. },
  56174. /**
  56175. * Sets the highlights Saturation value.
  56176. * 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.
  56177. */
  56178. set: function (value) {
  56179. this._highlightsSaturation = value;
  56180. this._dirty = true;
  56181. },
  56182. enumerable: true,
  56183. configurable: true
  56184. });
  56185. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  56186. /**
  56187. * Gets the highlights Exposure value.
  56188. * 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.
  56189. */
  56190. get: function () {
  56191. return this._highlightsExposure;
  56192. },
  56193. /**
  56194. * Sets the highlights Exposure value.
  56195. * 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.
  56196. */
  56197. set: function (value) {
  56198. this._highlightsExposure = value;
  56199. this._dirty = true;
  56200. },
  56201. enumerable: true,
  56202. configurable: true
  56203. });
  56204. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  56205. /**
  56206. * Gets the midtones Hue value.
  56207. * 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).
  56208. */
  56209. get: function () {
  56210. return this._midtonesHue;
  56211. },
  56212. /**
  56213. * Sets the midtones Hue value.
  56214. * 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).
  56215. */
  56216. set: function (value) {
  56217. this._midtonesHue = value;
  56218. this._dirty = true;
  56219. },
  56220. enumerable: true,
  56221. configurable: true
  56222. });
  56223. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  56224. /**
  56225. * Gets the midtones Density value.
  56226. * 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.
  56227. * Values less than zero provide a filter of opposite hue.
  56228. */
  56229. get: function () {
  56230. return this._midtonesDensity;
  56231. },
  56232. /**
  56233. * Sets the midtones Density value.
  56234. * 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.
  56235. * Values less than zero provide a filter of opposite hue.
  56236. */
  56237. set: function (value) {
  56238. this._midtonesDensity = value;
  56239. this._dirty = true;
  56240. },
  56241. enumerable: true,
  56242. configurable: true
  56243. });
  56244. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  56245. /**
  56246. * Gets the midtones Saturation value.
  56247. * 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.
  56248. */
  56249. get: function () {
  56250. return this._midtonesSaturation;
  56251. },
  56252. /**
  56253. * Sets the midtones Saturation value.
  56254. * 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.
  56255. */
  56256. set: function (value) {
  56257. this._midtonesSaturation = value;
  56258. this._dirty = true;
  56259. },
  56260. enumerable: true,
  56261. configurable: true
  56262. });
  56263. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  56264. /**
  56265. * Gets the midtones Exposure value.
  56266. * 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.
  56267. */
  56268. get: function () {
  56269. return this._midtonesExposure;
  56270. },
  56271. /**
  56272. * Sets the midtones Exposure value.
  56273. * 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.
  56274. */
  56275. set: function (value) {
  56276. this._midtonesExposure = value;
  56277. this._dirty = true;
  56278. },
  56279. enumerable: true,
  56280. configurable: true
  56281. });
  56282. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  56283. /**
  56284. * Gets the shadows Hue value.
  56285. * 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).
  56286. */
  56287. get: function () {
  56288. return this._shadowsHue;
  56289. },
  56290. /**
  56291. * Sets the shadows Hue value.
  56292. * 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).
  56293. */
  56294. set: function (value) {
  56295. this._shadowsHue = value;
  56296. this._dirty = true;
  56297. },
  56298. enumerable: true,
  56299. configurable: true
  56300. });
  56301. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  56302. /**
  56303. * Gets the shadows Density value.
  56304. * 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.
  56305. * Values less than zero provide a filter of opposite hue.
  56306. */
  56307. get: function () {
  56308. return this._shadowsDensity;
  56309. },
  56310. /**
  56311. * Sets the shadows Density value.
  56312. * 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.
  56313. * Values less than zero provide a filter of opposite hue.
  56314. */
  56315. set: function (value) {
  56316. this._shadowsDensity = value;
  56317. this._dirty = true;
  56318. },
  56319. enumerable: true,
  56320. configurable: true
  56321. });
  56322. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  56323. /**
  56324. * Gets the shadows Saturation value.
  56325. * 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.
  56326. */
  56327. get: function () {
  56328. return this._shadowsSaturation;
  56329. },
  56330. /**
  56331. * Sets the shadows Saturation value.
  56332. * 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.
  56333. */
  56334. set: function (value) {
  56335. this._shadowsSaturation = value;
  56336. this._dirty = true;
  56337. },
  56338. enumerable: true,
  56339. configurable: true
  56340. });
  56341. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  56342. /**
  56343. * Gets the shadows Exposure value.
  56344. * 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.
  56345. */
  56346. get: function () {
  56347. return this._shadowsExposure;
  56348. },
  56349. /**
  56350. * Sets the shadows Exposure value.
  56351. * 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.
  56352. */
  56353. set: function (value) {
  56354. this._shadowsExposure = value;
  56355. this._dirty = true;
  56356. },
  56357. enumerable: true,
  56358. configurable: true
  56359. });
  56360. /**
  56361. * Binds the color curves to the shader.
  56362. * @param colorCurves The color curve to bind
  56363. * @param effect The effect to bind to
  56364. */
  56365. ColorCurves.Bind = function (colorCurves, effect) {
  56366. if (colorCurves._dirty) {
  56367. colorCurves._dirty = false;
  56368. // Fill in global info.
  56369. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  56370. // Compute highlights info.
  56371. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  56372. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  56373. // Compute midtones info.
  56374. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  56375. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  56376. // Compute shadows info.
  56377. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  56378. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  56379. // Compute deltas (neutral is midtones).
  56380. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  56381. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  56382. }
  56383. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  56384. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  56385. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  56386. };
  56387. /**
  56388. * Prepare the list of uniforms associated with the ColorCurves effects.
  56389. * @param uniformsList The list of uniforms used in the effect
  56390. */
  56391. ColorCurves.PrepareUniforms = function (uniformsList) {
  56392. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  56393. };
  56394. /**
  56395. * Returns color grading data based on a hue, density, saturation and exposure value.
  56396. * @param filterHue The hue of the color filter.
  56397. * @param filterDensity The density of the color filter.
  56398. * @param saturation The saturation.
  56399. * @param exposure The exposure.
  56400. * @param result The result data container.
  56401. */
  56402. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  56403. if (hue == null) {
  56404. return;
  56405. }
  56406. hue = ColorCurves.clamp(hue, 0, 360);
  56407. density = ColorCurves.clamp(density, -100, 100);
  56408. saturation = ColorCurves.clamp(saturation, -100, 100);
  56409. exposure = ColorCurves.clamp(exposure, -100, 100);
  56410. // Remap the slider/config filter density with non-linear mapping and also scale by half
  56411. // so that the maximum filter density is only 50% control. This provides fine control
  56412. // for small values and reasonable range.
  56413. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  56414. density *= 0.5;
  56415. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  56416. if (density < 0) {
  56417. density *= -1;
  56418. hue = (hue + 180) % 360;
  56419. }
  56420. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  56421. result.scaleToRef(2, result);
  56422. result.a = 1 + 0.01 * saturation;
  56423. };
  56424. /**
  56425. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  56426. * @param value The input slider value in range [-100,100].
  56427. * @returns Adjusted value.
  56428. */
  56429. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  56430. value /= 100;
  56431. var x = Math.abs(value);
  56432. x = Math.pow(x, 2);
  56433. if (value < 0) {
  56434. x *= -1;
  56435. }
  56436. x *= 100;
  56437. return x;
  56438. };
  56439. /**
  56440. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  56441. * @param hue The hue (H) input.
  56442. * @param saturation The saturation (S) input.
  56443. * @param brightness The brightness (B) input.
  56444. * @result An RGBA color represented as Vector4.
  56445. */
  56446. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  56447. var h = ColorCurves.clamp(hue, 0, 360);
  56448. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  56449. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  56450. if (s === 0) {
  56451. result.r = v;
  56452. result.g = v;
  56453. result.b = v;
  56454. }
  56455. else {
  56456. // sector 0 to 5
  56457. h /= 60;
  56458. var i = Math.floor(h);
  56459. // fractional part of h
  56460. var f = h - i;
  56461. var p = v * (1 - s);
  56462. var q = v * (1 - s * f);
  56463. var t = v * (1 - s * (1 - f));
  56464. switch (i) {
  56465. case 0:
  56466. result.r = v;
  56467. result.g = t;
  56468. result.b = p;
  56469. break;
  56470. case 1:
  56471. result.r = q;
  56472. result.g = v;
  56473. result.b = p;
  56474. break;
  56475. case 2:
  56476. result.r = p;
  56477. result.g = v;
  56478. result.b = t;
  56479. break;
  56480. case 3:
  56481. result.r = p;
  56482. result.g = q;
  56483. result.b = v;
  56484. break;
  56485. case 4:
  56486. result.r = t;
  56487. result.g = p;
  56488. result.b = v;
  56489. break;
  56490. default:
  56491. result.r = v;
  56492. result.g = p;
  56493. result.b = q;
  56494. break;
  56495. }
  56496. }
  56497. result.a = 1;
  56498. };
  56499. /**
  56500. * Returns a value clamped between min and max
  56501. * @param value The value to clamp
  56502. * @param min The minimum of value
  56503. * @param max The maximum of value
  56504. * @returns The clamped value.
  56505. */
  56506. ColorCurves.clamp = function (value, min, max) {
  56507. return Math.min(Math.max(value, min), max);
  56508. };
  56509. /**
  56510. * Clones the current color curve instance.
  56511. * @return The cloned curves
  56512. */
  56513. ColorCurves.prototype.clone = function () {
  56514. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  56515. };
  56516. /**
  56517. * Serializes the current color curve instance to a json representation.
  56518. * @return a JSON representation
  56519. */
  56520. ColorCurves.prototype.serialize = function () {
  56521. return BABYLON.SerializationHelper.Serialize(this);
  56522. };
  56523. /**
  56524. * Parses the color curve from a json representation.
  56525. * @param source the JSON source to parse
  56526. * @return The parsed curves
  56527. */
  56528. ColorCurves.Parse = function (source) {
  56529. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  56530. };
  56531. return ColorCurves;
  56532. }());
  56533. __decorate([
  56534. BABYLON.serialize()
  56535. ], ColorCurves.prototype, "_globalHue", void 0);
  56536. __decorate([
  56537. BABYLON.serialize()
  56538. ], ColorCurves.prototype, "_globalDensity", void 0);
  56539. __decorate([
  56540. BABYLON.serialize()
  56541. ], ColorCurves.prototype, "_globalSaturation", void 0);
  56542. __decorate([
  56543. BABYLON.serialize()
  56544. ], ColorCurves.prototype, "_globalExposure", void 0);
  56545. __decorate([
  56546. BABYLON.serialize()
  56547. ], ColorCurves.prototype, "_highlightsHue", void 0);
  56548. __decorate([
  56549. BABYLON.serialize()
  56550. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  56551. __decorate([
  56552. BABYLON.serialize()
  56553. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  56554. __decorate([
  56555. BABYLON.serialize()
  56556. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  56557. __decorate([
  56558. BABYLON.serialize()
  56559. ], ColorCurves.prototype, "_midtonesHue", void 0);
  56560. __decorate([
  56561. BABYLON.serialize()
  56562. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  56563. __decorate([
  56564. BABYLON.serialize()
  56565. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  56566. __decorate([
  56567. BABYLON.serialize()
  56568. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  56569. BABYLON.ColorCurves = ColorCurves;
  56570. })(BABYLON || (BABYLON = {}));
  56571. //# sourceMappingURL=babylon.colorCurves.js.map
  56572. var BABYLON;
  56573. (function (BABYLON) {
  56574. var Octree = (function () {
  56575. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  56576. if (maxDepth === void 0) { maxDepth = 2; }
  56577. this.maxDepth = maxDepth;
  56578. this.dynamicContent = new Array();
  56579. this._maxBlockCapacity = maxBlockCapacity || 64;
  56580. this._selectionContent = new BABYLON.SmartArray(1024);
  56581. this._creationFunc = creationFunc;
  56582. }
  56583. // Methods
  56584. Octree.prototype.update = function (worldMin, worldMax, entries) {
  56585. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  56586. };
  56587. Octree.prototype.addMesh = function (entry) {
  56588. for (var index = 0; index < this.blocks.length; index++) {
  56589. var block = this.blocks[index];
  56590. block.addEntry(entry);
  56591. }
  56592. };
  56593. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  56594. this._selectionContent.reset();
  56595. for (var index = 0; index < this.blocks.length; index++) {
  56596. var block = this.blocks[index];
  56597. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  56598. }
  56599. if (allowDuplicate) {
  56600. this._selectionContent.concat(this.dynamicContent);
  56601. }
  56602. else {
  56603. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  56604. }
  56605. return this._selectionContent;
  56606. };
  56607. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  56608. this._selectionContent.reset();
  56609. for (var index = 0; index < this.blocks.length; index++) {
  56610. var block = this.blocks[index];
  56611. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  56612. }
  56613. if (allowDuplicate) {
  56614. this._selectionContent.concat(this.dynamicContent);
  56615. }
  56616. else {
  56617. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  56618. }
  56619. return this._selectionContent;
  56620. };
  56621. Octree.prototype.intersectsRay = function (ray) {
  56622. this._selectionContent.reset();
  56623. for (var index = 0; index < this.blocks.length; index++) {
  56624. var block = this.blocks[index];
  56625. block.intersectsRay(ray, this._selectionContent);
  56626. }
  56627. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  56628. return this._selectionContent;
  56629. };
  56630. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  56631. target.blocks = new Array();
  56632. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  56633. // Segmenting space
  56634. for (var x = 0; x < 2; x++) {
  56635. for (var y = 0; y < 2; y++) {
  56636. for (var z = 0; z < 2; z++) {
  56637. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  56638. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  56639. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  56640. block.addEntries(entries);
  56641. target.blocks.push(block);
  56642. }
  56643. }
  56644. }
  56645. };
  56646. return Octree;
  56647. }());
  56648. Octree.CreationFuncForMeshes = function (entry, block) {
  56649. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  56650. block.entries.push(entry);
  56651. }
  56652. };
  56653. Octree.CreationFuncForSubMeshes = function (entry, block) {
  56654. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  56655. block.entries.push(entry);
  56656. }
  56657. };
  56658. BABYLON.Octree = Octree;
  56659. })(BABYLON || (BABYLON = {}));
  56660. //# sourceMappingURL=babylon.octree.js.map
  56661. var BABYLON;
  56662. (function (BABYLON) {
  56663. var OctreeBlock = (function () {
  56664. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  56665. this.entries = new Array();
  56666. this._boundingVectors = new Array();
  56667. this._capacity = capacity;
  56668. this._depth = depth;
  56669. this._maxDepth = maxDepth;
  56670. this._creationFunc = creationFunc;
  56671. this._minPoint = minPoint;
  56672. this._maxPoint = maxPoint;
  56673. this._boundingVectors.push(minPoint.clone());
  56674. this._boundingVectors.push(maxPoint.clone());
  56675. this._boundingVectors.push(minPoint.clone());
  56676. this._boundingVectors[2].x = maxPoint.x;
  56677. this._boundingVectors.push(minPoint.clone());
  56678. this._boundingVectors[3].y = maxPoint.y;
  56679. this._boundingVectors.push(minPoint.clone());
  56680. this._boundingVectors[4].z = maxPoint.z;
  56681. this._boundingVectors.push(maxPoint.clone());
  56682. this._boundingVectors[5].z = minPoint.z;
  56683. this._boundingVectors.push(maxPoint.clone());
  56684. this._boundingVectors[6].x = minPoint.x;
  56685. this._boundingVectors.push(maxPoint.clone());
  56686. this._boundingVectors[7].y = minPoint.y;
  56687. }
  56688. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  56689. // Property
  56690. get: function () {
  56691. return this._capacity;
  56692. },
  56693. enumerable: true,
  56694. configurable: true
  56695. });
  56696. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  56697. get: function () {
  56698. return this._minPoint;
  56699. },
  56700. enumerable: true,
  56701. configurable: true
  56702. });
  56703. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  56704. get: function () {
  56705. return this._maxPoint;
  56706. },
  56707. enumerable: true,
  56708. configurable: true
  56709. });
  56710. // Methods
  56711. OctreeBlock.prototype.addEntry = function (entry) {
  56712. if (this.blocks) {
  56713. for (var index = 0; index < this.blocks.length; index++) {
  56714. var block = this.blocks[index];
  56715. block.addEntry(entry);
  56716. }
  56717. return;
  56718. }
  56719. this._creationFunc(entry, this);
  56720. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  56721. this.createInnerBlocks();
  56722. }
  56723. };
  56724. OctreeBlock.prototype.addEntries = function (entries) {
  56725. for (var index = 0; index < entries.length; index++) {
  56726. var mesh = entries[index];
  56727. this.addEntry(mesh);
  56728. }
  56729. };
  56730. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  56731. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  56732. if (this.blocks) {
  56733. for (var index = 0; index < this.blocks.length; index++) {
  56734. var block = this.blocks[index];
  56735. block.select(frustumPlanes, selection, allowDuplicate);
  56736. }
  56737. return;
  56738. }
  56739. if (allowDuplicate) {
  56740. selection.concat(this.entries);
  56741. }
  56742. else {
  56743. selection.concatWithNoDuplicate(this.entries);
  56744. }
  56745. }
  56746. };
  56747. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  56748. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  56749. if (this.blocks) {
  56750. for (var index = 0; index < this.blocks.length; index++) {
  56751. var block = this.blocks[index];
  56752. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  56753. }
  56754. return;
  56755. }
  56756. if (allowDuplicate) {
  56757. selection.concat(this.entries);
  56758. }
  56759. else {
  56760. selection.concatWithNoDuplicate(this.entries);
  56761. }
  56762. }
  56763. };
  56764. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  56765. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  56766. if (this.blocks) {
  56767. for (var index = 0; index < this.blocks.length; index++) {
  56768. var block = this.blocks[index];
  56769. block.intersectsRay(ray, selection);
  56770. }
  56771. return;
  56772. }
  56773. selection.concatWithNoDuplicate(this.entries);
  56774. }
  56775. };
  56776. OctreeBlock.prototype.createInnerBlocks = function () {
  56777. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  56778. };
  56779. return OctreeBlock;
  56780. }());
  56781. BABYLON.OctreeBlock = OctreeBlock;
  56782. })(BABYLON || (BABYLON = {}));
  56783. //# sourceMappingURL=babylon.octreeBlock.js.map
  56784. var BABYLON;
  56785. (function (BABYLON) {
  56786. var SIMDVector3 = (function () {
  56787. function SIMDVector3() {
  56788. }
  56789. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  56790. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  56791. };
  56792. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  56793. var m = transformation.m;
  56794. var m0 = SIMD.Float32x4.load(m, 0);
  56795. var m1 = SIMD.Float32x4.load(m, 4);
  56796. var m2 = SIMD.Float32x4.load(m, 8);
  56797. var m3 = SIMD.Float32x4.load(m, 12);
  56798. 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));
  56799. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  56800. result.x = SIMD.Float32x4.extractLane(r, 0);
  56801. result.y = SIMD.Float32x4.extractLane(r, 1);
  56802. result.z = SIMD.Float32x4.extractLane(r, 2);
  56803. };
  56804. return SIMDVector3;
  56805. }());
  56806. var SIMDMatrix = (function () {
  56807. function SIMDMatrix() {
  56808. }
  56809. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  56810. var tm = this.m;
  56811. var om = other.m;
  56812. var m0 = SIMD.Float32x4.load(om, 0);
  56813. var m1 = SIMD.Float32x4.load(om, 4);
  56814. var m2 = SIMD.Float32x4.load(om, 8);
  56815. var m3 = SIMD.Float32x4.load(om, 12);
  56816. for (var i = 0; i < 16; i += 4) {
  56817. 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)))));
  56818. }
  56819. return this;
  56820. };
  56821. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  56822. var src = this.m;
  56823. var dest = other.m;
  56824. // Load the 4 rows
  56825. var src0 = SIMD.Float32x4.load(src, 0);
  56826. var src1 = SIMD.Float32x4.load(src, 4);
  56827. var src2 = SIMD.Float32x4.load(src, 8);
  56828. var src3 = SIMD.Float32x4.load(src, 12);
  56829. // Transpose the source matrix. Sort of. Not a true transpose operation
  56830. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  56831. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  56832. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  56833. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  56834. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  56835. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  56836. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  56837. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  56838. // This is a true transposition, but it will lead to an incorrect result
  56839. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  56840. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  56841. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  56842. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  56843. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  56844. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  56845. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  56846. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  56847. // ----
  56848. tmp1 = SIMD.Float32x4.mul(row2, row3);
  56849. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  56850. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  56851. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  56852. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  56853. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  56854. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  56855. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  56856. // ----
  56857. tmp1 = SIMD.Float32x4.mul(row1, row2);
  56858. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  56859. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  56860. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  56861. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  56862. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  56863. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  56864. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  56865. // ----
  56866. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  56867. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  56868. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  56869. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  56870. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  56871. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  56872. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  56873. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  56874. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  56875. // ----
  56876. tmp1 = SIMD.Float32x4.mul(row0, row1);
  56877. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  56878. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  56879. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  56880. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  56881. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  56882. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  56883. // ----
  56884. tmp1 = SIMD.Float32x4.mul(row0, row3);
  56885. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  56886. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  56887. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  56888. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  56889. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  56890. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  56891. // ----
  56892. tmp1 = SIMD.Float32x4.mul(row0, row2);
  56893. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  56894. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  56895. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  56896. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  56897. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  56898. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  56899. // Compute determinant
  56900. var det = SIMD.Float32x4.mul(row0, minor0);
  56901. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  56902. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  56903. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  56904. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  56905. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  56906. // These shuffles aren't necessary if the faulty transposition is done
  56907. // up at the top of this function.
  56908. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  56909. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  56910. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  56911. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  56912. // Compute final values by multiplying with 1/det
  56913. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  56914. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  56915. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  56916. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  56917. return this;
  56918. };
  56919. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  56920. var out = result.m;
  56921. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  56922. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  56923. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  56924. // cc.kmVec3Subtract(f, pCenter, pEye);
  56925. var f = SIMD.Float32x4.sub(center, eye);
  56926. // cc.kmVec3Normalize(f, f);
  56927. var tmp = SIMD.Float32x4.mul(f, f);
  56928. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  56929. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  56930. // cc.kmVec3Assign(up, pUp);
  56931. // cc.kmVec3Normalize(up, up);
  56932. tmp = SIMD.Float32x4.mul(up, up);
  56933. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  56934. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  56935. // cc.kmVec3Cross(s, f, up);
  56936. 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)));
  56937. // cc.kmVec3Normalize(s, s);
  56938. tmp = SIMD.Float32x4.mul(s, s);
  56939. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  56940. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  56941. // cc.kmVec3Cross(u, s, f);
  56942. 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)));
  56943. // cc.kmVec3Normalize(s, s);
  56944. tmp = SIMD.Float32x4.mul(s, s);
  56945. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  56946. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  56947. var zero = SIMD.Float32x4.splat(0.0);
  56948. s = SIMD.Float32x4.neg(s);
  56949. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  56950. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  56951. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  56952. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  56953. 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);
  56954. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  56955. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  56956. 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)))));
  56957. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  56958. 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)))));
  56959. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  56960. 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)))));
  56961. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  56962. 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)))));
  56963. };
  56964. return SIMDMatrix;
  56965. }());
  56966. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  56967. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  56968. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  56969. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  56970. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  56971. var SIMDHelper = (function () {
  56972. function SIMDHelper() {
  56973. }
  56974. Object.defineProperty(SIMDHelper, "IsEnabled", {
  56975. get: function () {
  56976. return SIMDHelper._isEnabled;
  56977. },
  56978. enumerable: true,
  56979. configurable: true
  56980. });
  56981. SIMDHelper.DisableSIMD = function () {
  56982. // Replace functions
  56983. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  56984. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  56985. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  56986. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  56987. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  56988. SIMDHelper._isEnabled = false;
  56989. };
  56990. SIMDHelper.EnableSIMD = function () {
  56991. if (self.SIMD === undefined) {
  56992. return;
  56993. }
  56994. // check if polyfills needed
  56995. if (!self.Math.fround) {
  56996. self.Math.fround = (function (array) { return function (x) {
  56997. return array[0] = x, array[0];
  56998. }; })(new Float32Array(1));
  56999. }
  57000. if (!self.Math.imul) {
  57001. self.Math.imul = function (a, b) {
  57002. var ah = (a >>> 16) & 0xffff;
  57003. var al = a & 0xffff;
  57004. var bh = (b >>> 16) & 0xffff;
  57005. var bl = b & 0xffff;
  57006. // the shift by 0 fixes the sign on the high part
  57007. // the final |0 converts the unsigned value into a signed value
  57008. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  57009. };
  57010. }
  57011. // Replace functions
  57012. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  57013. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  57014. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  57015. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  57016. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  57017. SIMDHelper._isEnabled = true;
  57018. };
  57019. return SIMDHelper;
  57020. }());
  57021. SIMDHelper._isEnabled = false;
  57022. BABYLON.SIMDHelper = SIMDHelper;
  57023. })(BABYLON || (BABYLON = {}));
  57024. //# sourceMappingURL=babylon.math.SIMD.js.map
  57025. var BABYLON;
  57026. (function (BABYLON) {
  57027. var VRDistortionCorrectionPostProcess = (function (_super) {
  57028. __extends(VRDistortionCorrectionPostProcess, _super);
  57029. //ANY
  57030. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  57031. var _this = _super.call(this, name, "vrDistortionCorrection", [
  57032. 'LensCenter',
  57033. 'Scale',
  57034. 'ScaleIn',
  57035. 'HmdWarpParam'
  57036. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  57037. _this._isRightEye = isRightEye;
  57038. _this._distortionFactors = vrMetrics.distortionK;
  57039. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  57040. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  57041. _this.onSizeChangedObservable.add(function () {
  57042. _this.aspectRatio = _this.width * .5 / _this.height;
  57043. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  57044. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  57045. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  57046. });
  57047. _this.onApplyObservable.add(function (effect) {
  57048. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  57049. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  57050. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  57051. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  57052. });
  57053. return _this;
  57054. }
  57055. return VRDistortionCorrectionPostProcess;
  57056. }(BABYLON.PostProcess));
  57057. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  57058. })(BABYLON || (BABYLON = {}));
  57059. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  57060. var BABYLON;
  57061. (function (BABYLON) {
  57062. var AnaglyphPostProcess = (function (_super) {
  57063. __extends(AnaglyphPostProcess, _super);
  57064. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  57065. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  57066. _this._passedProcess = rigCameras[0]._rigPostProcess;
  57067. _this.onApplyObservable.add(function (effect) {
  57068. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  57069. });
  57070. return _this;
  57071. }
  57072. return AnaglyphPostProcess;
  57073. }(BABYLON.PostProcess));
  57074. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  57075. })(BABYLON || (BABYLON = {}));
  57076. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  57077. var BABYLON;
  57078. (function (BABYLON) {
  57079. var StereoscopicInterlacePostProcess = (function (_super) {
  57080. __extends(StereoscopicInterlacePostProcess, _super);
  57081. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  57082. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  57083. _this._passedProcess = rigCameras[0]._rigPostProcess;
  57084. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  57085. _this.onSizeChangedObservable.add(function () {
  57086. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  57087. });
  57088. _this.onApplyObservable.add(function (effect) {
  57089. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  57090. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  57091. });
  57092. return _this;
  57093. }
  57094. return StereoscopicInterlacePostProcess;
  57095. }(BABYLON.PostProcess));
  57096. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  57097. })(BABYLON || (BABYLON = {}));
  57098. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  57099. var BABYLON;
  57100. (function (BABYLON) {
  57101. var FreeCameraDeviceOrientationInput = (function () {
  57102. function FreeCameraDeviceOrientationInput() {
  57103. var _this = this;
  57104. this._screenOrientationAngle = 0;
  57105. this._screenQuaternion = new BABYLON.Quaternion();
  57106. this._alpha = 0;
  57107. this._beta = 0;
  57108. this._gamma = 0;
  57109. this._orientationChanged = function () {
  57110. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  57111. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  57112. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  57113. };
  57114. this._deviceOrientation = function (evt) {
  57115. _this._alpha = evt.alpha;
  57116. _this._beta = evt.beta;
  57117. _this._gamma = evt.gamma;
  57118. };
  57119. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  57120. this._orientationChanged();
  57121. }
  57122. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  57123. get: function () {
  57124. return this._camera;
  57125. },
  57126. set: function (camera) {
  57127. this._camera = camera;
  57128. if (!this._camera.rotationQuaternion)
  57129. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  57130. },
  57131. enumerable: true,
  57132. configurable: true
  57133. });
  57134. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  57135. window.addEventListener("orientationchange", this._orientationChanged);
  57136. window.addEventListener("deviceorientation", this._deviceOrientation);
  57137. //In certain cases, the attach control is called AFTER orientation was changed,
  57138. //So this is needed.
  57139. this._orientationChanged();
  57140. };
  57141. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  57142. window.removeEventListener("orientationchange", this._orientationChanged);
  57143. window.removeEventListener("deviceorientation", this._deviceOrientation);
  57144. };
  57145. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  57146. //if no device orientation provided, don't update the rotation.
  57147. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  57148. if (!this._alpha)
  57149. return;
  57150. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  57151. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  57152. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  57153. //Mirror on XY Plane
  57154. this._camera.rotationQuaternion.z *= -1;
  57155. this._camera.rotationQuaternion.w *= -1;
  57156. };
  57157. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  57158. return "FreeCameraDeviceOrientationInput";
  57159. };
  57160. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  57161. return "deviceOrientation";
  57162. };
  57163. return FreeCameraDeviceOrientationInput;
  57164. }());
  57165. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  57166. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  57167. })(BABYLON || (BABYLON = {}));
  57168. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  57169. var BABYLON;
  57170. (function (BABYLON) {
  57171. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  57172. function ArcRotateCameraVRDeviceOrientationInput() {
  57173. this.alphaCorrection = 1;
  57174. this.betaCorrection = 1;
  57175. this.gammaCorrection = 1;
  57176. this._alpha = 0;
  57177. this._beta = 0;
  57178. this._gamma = 0;
  57179. this._dirty = false;
  57180. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  57181. }
  57182. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  57183. this.camera.attachControl(element, noPreventDefault);
  57184. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  57185. };
  57186. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  57187. var camera = this.camera;
  57188. this._alpha = +evt.alpha | 0;
  57189. this._beta = +evt.beta | 0;
  57190. this._gamma = +evt.gamma | 0;
  57191. this._dirty = true;
  57192. };
  57193. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  57194. if (this._dirty) {
  57195. this._dirty = false;
  57196. if (this._gamma < 0) {
  57197. this._gamma = 180 + this._gamma;
  57198. }
  57199. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  57200. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  57201. }
  57202. };
  57203. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  57204. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  57205. };
  57206. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  57207. return "ArcRotateCameraVRDeviceOrientationInput";
  57208. };
  57209. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  57210. return "VRDeviceOrientation";
  57211. };
  57212. return ArcRotateCameraVRDeviceOrientationInput;
  57213. }());
  57214. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  57215. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  57216. })(BABYLON || (BABYLON = {}));
  57217. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  57218. var BABYLON;
  57219. (function (BABYLON) {
  57220. var VRCameraMetrics = (function () {
  57221. function VRCameraMetrics() {
  57222. this.compensateDistortion = true;
  57223. }
  57224. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  57225. get: function () {
  57226. return this.hResolution / (2 * this.vResolution);
  57227. },
  57228. enumerable: true,
  57229. configurable: true
  57230. });
  57231. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  57232. get: function () {
  57233. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  57234. },
  57235. enumerable: true,
  57236. configurable: true
  57237. });
  57238. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  57239. get: function () {
  57240. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  57241. var h = (4 * meters) / this.hScreenSize;
  57242. return BABYLON.Matrix.Translation(h, 0, 0);
  57243. },
  57244. enumerable: true,
  57245. configurable: true
  57246. });
  57247. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  57248. get: function () {
  57249. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  57250. var h = (4 * meters) / this.hScreenSize;
  57251. return BABYLON.Matrix.Translation(-h, 0, 0);
  57252. },
  57253. enumerable: true,
  57254. configurable: true
  57255. });
  57256. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  57257. get: function () {
  57258. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  57259. },
  57260. enumerable: true,
  57261. configurable: true
  57262. });
  57263. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  57264. get: function () {
  57265. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  57266. },
  57267. enumerable: true,
  57268. configurable: true
  57269. });
  57270. VRCameraMetrics.GetDefault = function () {
  57271. var result = new VRCameraMetrics();
  57272. result.hResolution = 1280;
  57273. result.vResolution = 800;
  57274. result.hScreenSize = 0.149759993;
  57275. result.vScreenSize = 0.0935999975;
  57276. result.vScreenCenter = 0.0467999987;
  57277. result.eyeToScreenDistance = 0.0410000011;
  57278. result.lensSeparationDistance = 0.0635000020;
  57279. result.interpupillaryDistance = 0.0640000030;
  57280. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  57281. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  57282. result.postProcessScaleFactor = 1.714605507808412;
  57283. result.lensCenterOffset = 0.151976421;
  57284. return result;
  57285. };
  57286. return VRCameraMetrics;
  57287. }());
  57288. BABYLON.VRCameraMetrics = VRCameraMetrics;
  57289. })(BABYLON || (BABYLON = {}));
  57290. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  57291. var BABYLON;
  57292. (function (BABYLON) {
  57293. var WebVRFreeCamera = (function (_super) {
  57294. __extends(WebVRFreeCamera, _super);
  57295. function WebVRFreeCamera(name, position, scene, webVROptions) {
  57296. if (webVROptions === void 0) { webVROptions = {}; }
  57297. var _this = _super.call(this, name, position, scene) || this;
  57298. _this.webVROptions = webVROptions;
  57299. _this._vrDevice = null;
  57300. _this.rawPose = null;
  57301. _this._vrEnabled = false;
  57302. _this._specsVersion = 1.1;
  57303. _this._attached = false;
  57304. _this._positionOffset = BABYLON.Vector3.Zero();
  57305. _this._descendants = [];
  57306. _this.devicePosition = BABYLON.Vector3.Zero();
  57307. _this.deviceScaleFactor = 1;
  57308. _this.controllers = [];
  57309. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  57310. //legacy support - the compensation boolean was removed.
  57311. if (arguments.length === 5) {
  57312. _this.webVROptions = arguments[4];
  57313. }
  57314. // default webVR options
  57315. if (_this.webVROptions.trackPosition == undefined) {
  57316. _this.webVROptions.trackPosition = true;
  57317. }
  57318. if (_this.webVROptions.controllerMeshes == undefined) {
  57319. _this.webVROptions.controllerMeshes = true;
  57320. }
  57321. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  57322. _this.webVROptions.defaultLightningOnControllers = true;
  57323. }
  57324. _this.rotationQuaternion = new BABYLON.Quaternion();
  57325. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  57326. if (_this.webVROptions && _this.webVROptions.positionScale) {
  57327. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  57328. }
  57329. //enable VR
  57330. _this.getEngine().initWebVR();
  57331. if (!_this.getEngine().vrDisplaysPromise) {
  57332. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  57333. }
  57334. else {
  57335. //check specs version
  57336. if (!window.VRFrameData) {
  57337. _this._specsVersion = 1.0;
  57338. _this._frameData = {};
  57339. }
  57340. else {
  57341. _this._frameData = new VRFrameData();
  57342. }
  57343. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  57344. if (devices.length > 0) {
  57345. _this._vrEnabled = true;
  57346. if (_this.webVROptions.displayName) {
  57347. var found = devices.some(function (device) {
  57348. if (device.displayName === _this.webVROptions.displayName) {
  57349. _this._vrDevice = device;
  57350. return true;
  57351. }
  57352. else {
  57353. return false;
  57354. }
  57355. });
  57356. if (!found) {
  57357. _this._vrDevice = devices[0];
  57358. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  57359. }
  57360. }
  57361. else {
  57362. //choose the first one
  57363. _this._vrDevice = devices[0];
  57364. }
  57365. //reset the rig parameters.
  57366. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  57367. if (_this._attached) {
  57368. _this.getEngine().enableVR(_this._vrDevice);
  57369. }
  57370. }
  57371. else {
  57372. BABYLON.Tools.Error("No WebVR devices found!");
  57373. }
  57374. });
  57375. }
  57376. // try to attach the controllers, if found.
  57377. _this.initControllers();
  57378. /**
  57379. * The idea behind the following lines:
  57380. * objects that have the camera as parent should actually have the rig cameras as a parent.
  57381. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  57382. * the second will not show it correctly.
  57383. *
  57384. * To solve this - each object that has the camera as parent will be added to a protected array.
  57385. * When the rig camera renders, it will take this array and set all of those to be its children.
  57386. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  57387. * Amazing!
  57388. */
  57389. scene.onBeforeCameraRenderObservable.add(function (camera) {
  57390. if (camera.parent === _this && _this.rigParenting) {
  57391. _this._descendants = _this.getDescendants(true, function (n) {
  57392. // don't take the cameras or the controllers!
  57393. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  57394. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  57395. return !isController && !isRigCamera;
  57396. });
  57397. _this._descendants.forEach(function (node) {
  57398. node.parent = camera;
  57399. });
  57400. }
  57401. });
  57402. scene.onAfterCameraRenderObservable.add(function (camera) {
  57403. if (camera.parent === _this && _this.rigParenting) {
  57404. _this._descendants.forEach(function (node) {
  57405. node.parent = _this;
  57406. });
  57407. }
  57408. });
  57409. return _this;
  57410. }
  57411. WebVRFreeCamera.prototype._checkInputs = function () {
  57412. if (this._vrEnabled) {
  57413. if (this._specsVersion === 1.1) {
  57414. this._vrDevice.getFrameData(this._frameData);
  57415. }
  57416. else {
  57417. //backwards comp
  57418. var pose = this._vrDevice.getPose();
  57419. this._frameData.pose = pose;
  57420. // calculate view and projection matrix
  57421. }
  57422. this.updateFromDevice(this._frameData.pose);
  57423. }
  57424. _super.prototype._checkInputs.call(this);
  57425. };
  57426. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  57427. if (poseData && poseData.orientation) {
  57428. this.rawPose = poseData;
  57429. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  57430. if (this.getScene().useRightHandedSystem) {
  57431. this.deviceRotationQuaternion.z *= -1;
  57432. this.deviceRotationQuaternion.w *= -1;
  57433. }
  57434. if (this.webVROptions.trackPosition && this.rawPose.position) {
  57435. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  57436. if (this.getScene().useRightHandedSystem) {
  57437. this.devicePosition.z *= -1;
  57438. }
  57439. }
  57440. }
  57441. };
  57442. /**
  57443. * WebVR's attach control will start broadcasting frames to the device.
  57444. * Note that in certain browsers (chrome for example) this function must be called
  57445. * within a user-interaction callback. Example:
  57446. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  57447. *
  57448. * @param {HTMLElement} element
  57449. * @param {boolean} [noPreventDefault]
  57450. *
  57451. * @memberOf WebVRFreeCamera
  57452. */
  57453. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  57454. _super.prototype.attachControl.call(this, element, noPreventDefault);
  57455. this._attached = true;
  57456. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  57457. if (this._vrEnabled) {
  57458. this.getEngine().enableVR(this._vrDevice);
  57459. }
  57460. };
  57461. WebVRFreeCamera.prototype.detachControl = function (element) {
  57462. _super.prototype.detachControl.call(this, element);
  57463. this._vrEnabled = false;
  57464. this._attached = false;
  57465. this.getEngine().disableVR();
  57466. };
  57467. WebVRFreeCamera.prototype.getClassName = function () {
  57468. return "WebVRFreeCamera";
  57469. };
  57470. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  57471. //uses the vrDisplay's "resetPose()".
  57472. //pitch and roll won't be affected.
  57473. this._vrDevice.resetPose();
  57474. };
  57475. WebVRFreeCamera.prototype._updateRigCameras = function () {
  57476. var camLeft = this._rigCameras[0];
  57477. var camRight = this._rigCameras[1];
  57478. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  57479. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  57480. camLeft.position.copyFrom(this.devicePosition);
  57481. camRight.position.copyFrom(this.devicePosition);
  57482. };
  57483. /**
  57484. * This function is called by the two RIG cameras.
  57485. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  57486. */
  57487. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  57488. var _this = this;
  57489. //WebVR 1.0
  57490. if (this._cameraRigParams["specs"] === 1.0) {
  57491. this._updateCameraRotationMatrix();
  57492. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  57493. // Computing target and final matrix
  57494. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  57495. if (this.getScene().useRightHandedSystem) {
  57496. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  57497. }
  57498. else {
  57499. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  57500. }
  57501. //now move the eye in the right direction
  57502. var eyeParams = this._cameraRigParams["eyeParameters"];
  57503. var offset = eyeParams.offset;
  57504. // it will actually always be 0, but just in case
  57505. if (this.getScene().useRightHandedSystem) {
  57506. offset[2] *= -1;
  57507. }
  57508. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  57509. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  57510. }
  57511. else {
  57512. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  57513. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  57514. if (!this.getScene().useRightHandedSystem) {
  57515. [2, 6, 8, 9, 14].forEach(function (num) {
  57516. _this._webvrViewMatrix.m[num] *= -1;
  57517. });
  57518. }
  57519. // update the camera rotation matrix
  57520. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  57521. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  57522. // Computing target and final matrix
  57523. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  57524. }
  57525. var parentCamera = this._cameraRigParams["parentCamera"];
  57526. // should the view matrix be updated with scale and position offset?
  57527. if (parentCamera.deviceScaleFactor !== 1) {
  57528. this._webvrViewMatrix.invert();
  57529. // scale the position, if set
  57530. if (parentCamera.deviceScaleFactor) {
  57531. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  57532. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  57533. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  57534. }
  57535. this._webvrViewMatrix.invert();
  57536. }
  57537. return this._webvrViewMatrix;
  57538. };
  57539. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  57540. var _this = this;
  57541. if (this._cameraRigParams["specs"] === 1.0) {
  57542. var eyeParams = this._cameraRigParams["eyeParameters"];
  57543. // deprecated!!
  57544. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  57545. }
  57546. else {
  57547. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  57548. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  57549. //babylon compatible matrix
  57550. if (!this.getScene().useRightHandedSystem) {
  57551. [8, 9, 10, 11].forEach(function (num) {
  57552. _this._projectionMatrix.m[num] *= -1;
  57553. });
  57554. }
  57555. }
  57556. return this._projectionMatrix;
  57557. };
  57558. WebVRFreeCamera.prototype.initControllers = function () {
  57559. var _this = this;
  57560. this.controllers = [];
  57561. new BABYLON.Gamepads(function (gp) {
  57562. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  57563. var webVrController = gp;
  57564. if (_this.webVROptions.controllerMeshes) {
  57565. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  57566. if (_this.webVROptions.defaultLightningOnControllers) {
  57567. if (!_this._lightOnControllers) {
  57568. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  57569. }
  57570. loadedMesh.getChildren().forEach(function (mesh) {
  57571. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  57572. });
  57573. }
  57574. });
  57575. }
  57576. webVrController.attachToPoseControlledCamera(_this);
  57577. // since this is async - sanity check. Is the controller already stored?
  57578. if (_this.controllers.indexOf(webVrController) === -1) {
  57579. //add to the controllers array
  57580. _this.controllers.push(webVrController);
  57581. //did we find enough controllers? Great! let the developer know.
  57582. if (_this.onControllersAttached && _this.controllers.length === 2) {
  57583. _this.onControllersAttached(_this.controllers);
  57584. }
  57585. }
  57586. }
  57587. });
  57588. };
  57589. return WebVRFreeCamera;
  57590. }(BABYLON.FreeCamera));
  57591. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  57592. })(BABYLON || (BABYLON = {}));
  57593. //# sourceMappingURL=babylon.webVRCamera.js.map
  57594. /// <reference path="babylon.freeCamera.ts" />
  57595. var BABYLON;
  57596. (function (BABYLON) {
  57597. // We're mainly based on the logic defined into the FreeCamera code
  57598. var DeviceOrientationCamera = (function (_super) {
  57599. __extends(DeviceOrientationCamera, _super);
  57600. function DeviceOrientationCamera(name, position, scene) {
  57601. var _this = _super.call(this, name, position, scene) || this;
  57602. _this._quaternionCache = new BABYLON.Quaternion();
  57603. _this.inputs.addDeviceOrientation();
  57604. return _this;
  57605. }
  57606. DeviceOrientationCamera.prototype.getClassName = function () {
  57607. return "DeviceOrientationCamera";
  57608. };
  57609. DeviceOrientationCamera.prototype._checkInputs = function () {
  57610. _super.prototype._checkInputs.call(this);
  57611. this._quaternionCache.copyFrom(this.rotationQuaternion);
  57612. if (this._initialQuaternion) {
  57613. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  57614. }
  57615. };
  57616. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  57617. var _this = this;
  57618. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  57619. //can only work if this camera has a rotation quaternion already.
  57620. if (!this.rotationQuaternion)
  57621. return;
  57622. if (!this._initialQuaternion) {
  57623. this._initialQuaternion = new BABYLON.Quaternion();
  57624. }
  57625. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  57626. ['x', 'y', 'z'].forEach(function (axisName) {
  57627. if (!axis[axisName]) {
  57628. _this._initialQuaternion[axisName] = 0;
  57629. }
  57630. else {
  57631. _this._initialQuaternion[axisName] *= -1;
  57632. }
  57633. });
  57634. this._initialQuaternion.normalize();
  57635. //force rotation update
  57636. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  57637. };
  57638. return DeviceOrientationCamera;
  57639. }(BABYLON.FreeCamera));
  57640. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  57641. })(BABYLON || (BABYLON = {}));
  57642. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  57643. var BABYLON;
  57644. (function (BABYLON) {
  57645. var VRDeviceOrientationFreeCamera = (function (_super) {
  57646. __extends(VRDeviceOrientationFreeCamera, _super);
  57647. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  57648. if (compensateDistortion === void 0) { compensateDistortion = true; }
  57649. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  57650. var _this = _super.call(this, name, position, scene) || this;
  57651. vrCameraMetrics.compensateDistortion = compensateDistortion;
  57652. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  57653. return _this;
  57654. }
  57655. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  57656. return "VRDeviceOrientationFreeCamera";
  57657. };
  57658. return VRDeviceOrientationFreeCamera;
  57659. }(BABYLON.DeviceOrientationCamera));
  57660. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  57661. var VRDeviceOrientationGamepadCamera = (function (_super) {
  57662. __extends(VRDeviceOrientationGamepadCamera, _super);
  57663. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  57664. if (compensateDistortion === void 0) { compensateDistortion = true; }
  57665. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  57666. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  57667. _this.inputs.addGamepad();
  57668. return _this;
  57669. }
  57670. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  57671. return "VRDeviceOrientationGamepadCamera";
  57672. };
  57673. return VRDeviceOrientationGamepadCamera;
  57674. }(VRDeviceOrientationFreeCamera));
  57675. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  57676. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  57677. __extends(VRDeviceOrientationArcRotateCamera, _super);
  57678. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  57679. if (compensateDistortion === void 0) { compensateDistortion = true; }
  57680. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  57681. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  57682. vrCameraMetrics.compensateDistortion = compensateDistortion;
  57683. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  57684. _this.inputs.addVRDeviceOrientation();
  57685. return _this;
  57686. }
  57687. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  57688. return "VRDeviceOrientationArcRotateCamera";
  57689. };
  57690. return VRDeviceOrientationArcRotateCamera;
  57691. }(BABYLON.ArcRotateCamera));
  57692. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  57693. })(BABYLON || (BABYLON = {}));
  57694. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  57695. /// <reference path="babylon.freeCamera.ts" />
  57696. /// <reference path="babylon.arcRotateCamera.ts" />
  57697. /// <reference path="babylon.gamepadCamera.ts" />
  57698. /// <reference path="babylon.universalCamera.ts" />
  57699. var BABYLON;
  57700. (function (BABYLON) {
  57701. var AnaglyphFreeCamera = (function (_super) {
  57702. __extends(AnaglyphFreeCamera, _super);
  57703. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  57704. var _this = _super.call(this, name, position, scene) || this;
  57705. _this.interaxialDistance = interaxialDistance;
  57706. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  57707. return _this;
  57708. }
  57709. AnaglyphFreeCamera.prototype.getClassName = function () {
  57710. return "AnaglyphFreeCamera";
  57711. };
  57712. return AnaglyphFreeCamera;
  57713. }(BABYLON.FreeCamera));
  57714. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  57715. var AnaglyphArcRotateCamera = (function (_super) {
  57716. __extends(AnaglyphArcRotateCamera, _super);
  57717. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  57718. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  57719. _this.interaxialDistance = interaxialDistance;
  57720. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  57721. return _this;
  57722. }
  57723. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  57724. return "AnaglyphArcRotateCamera";
  57725. };
  57726. return AnaglyphArcRotateCamera;
  57727. }(BABYLON.ArcRotateCamera));
  57728. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  57729. var AnaglyphGamepadCamera = (function (_super) {
  57730. __extends(AnaglyphGamepadCamera, _super);
  57731. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  57732. var _this = _super.call(this, name, position, scene) || this;
  57733. _this.interaxialDistance = interaxialDistance;
  57734. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  57735. return _this;
  57736. }
  57737. AnaglyphGamepadCamera.prototype.getClassName = function () {
  57738. return "AnaglyphGamepadCamera";
  57739. };
  57740. return AnaglyphGamepadCamera;
  57741. }(BABYLON.GamepadCamera));
  57742. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  57743. var AnaglyphUniversalCamera = (function (_super) {
  57744. __extends(AnaglyphUniversalCamera, _super);
  57745. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  57746. var _this = _super.call(this, name, position, scene) || this;
  57747. _this.interaxialDistance = interaxialDistance;
  57748. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  57749. return _this;
  57750. }
  57751. AnaglyphUniversalCamera.prototype.getClassName = function () {
  57752. return "AnaglyphUniversalCamera";
  57753. };
  57754. return AnaglyphUniversalCamera;
  57755. }(BABYLON.UniversalCamera));
  57756. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  57757. var StereoscopicFreeCamera = (function (_super) {
  57758. __extends(StereoscopicFreeCamera, _super);
  57759. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  57760. var _this = _super.call(this, name, position, scene) || this;
  57761. _this.interaxialDistance = interaxialDistance;
  57762. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  57763. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  57764. return _this;
  57765. }
  57766. StereoscopicFreeCamera.prototype.getClassName = function () {
  57767. return "StereoscopicFreeCamera";
  57768. };
  57769. return StereoscopicFreeCamera;
  57770. }(BABYLON.FreeCamera));
  57771. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  57772. var StereoscopicArcRotateCamera = (function (_super) {
  57773. __extends(StereoscopicArcRotateCamera, _super);
  57774. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  57775. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  57776. _this.interaxialDistance = interaxialDistance;
  57777. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  57778. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  57779. return _this;
  57780. }
  57781. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  57782. return "StereoscopicArcRotateCamera";
  57783. };
  57784. return StereoscopicArcRotateCamera;
  57785. }(BABYLON.ArcRotateCamera));
  57786. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  57787. var StereoscopicGamepadCamera = (function (_super) {
  57788. __extends(StereoscopicGamepadCamera, _super);
  57789. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  57790. var _this = _super.call(this, name, position, scene) || this;
  57791. _this.interaxialDistance = interaxialDistance;
  57792. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  57793. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  57794. return _this;
  57795. }
  57796. StereoscopicGamepadCamera.prototype.getClassName = function () {
  57797. return "StereoscopicGamepadCamera";
  57798. };
  57799. return StereoscopicGamepadCamera;
  57800. }(BABYLON.GamepadCamera));
  57801. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  57802. var StereoscopicUniversalCamera = (function (_super) {
  57803. __extends(StereoscopicUniversalCamera, _super);
  57804. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  57805. var _this = _super.call(this, name, position, scene) || this;
  57806. _this.interaxialDistance = interaxialDistance;
  57807. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  57808. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  57809. return _this;
  57810. }
  57811. StereoscopicUniversalCamera.prototype.getClassName = function () {
  57812. return "StereoscopicUniversalCamera";
  57813. };
  57814. return StereoscopicUniversalCamera;
  57815. }(BABYLON.UniversalCamera));
  57816. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  57817. })(BABYLON || (BABYLON = {}));
  57818. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  57819. // Mainly based on these 2 articles :
  57820. // 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
  57821. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  57822. var BABYLON;
  57823. (function (BABYLON) {
  57824. var JoystickAxis;
  57825. (function (JoystickAxis) {
  57826. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  57827. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  57828. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  57829. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  57830. var VirtualJoystick = (function () {
  57831. function VirtualJoystick(leftJoystick) {
  57832. var _this = this;
  57833. if (leftJoystick) {
  57834. this._leftJoystick = true;
  57835. }
  57836. else {
  57837. this._leftJoystick = false;
  57838. }
  57839. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  57840. VirtualJoystick._globalJoystickIndex++;
  57841. // By default left & right arrow keys are moving the X
  57842. // and up & down keys are moving the Y
  57843. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  57844. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  57845. this.reverseLeftRight = false;
  57846. this.reverseUpDown = false;
  57847. // collections of pointers
  57848. this._touches = new BABYLON.StringDictionary();
  57849. this.deltaPosition = BABYLON.Vector3.Zero();
  57850. this._joystickSensibility = 25;
  57851. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  57852. this._rotationSpeed = 25;
  57853. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  57854. this._rotateOnAxisRelativeToMesh = false;
  57855. this._onResize = function (evt) {
  57856. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  57857. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  57858. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  57859. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  57860. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  57861. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  57862. };
  57863. // injecting a canvas element on top of the canvas 3D game
  57864. if (!VirtualJoystick.vjCanvas) {
  57865. window.addEventListener("resize", this._onResize, false);
  57866. VirtualJoystick.vjCanvas = document.createElement("canvas");
  57867. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  57868. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  57869. VirtualJoystick.vjCanvas.width = window.innerWidth;
  57870. VirtualJoystick.vjCanvas.height = window.innerHeight;
  57871. VirtualJoystick.vjCanvas.style.width = "100%";
  57872. VirtualJoystick.vjCanvas.style.height = "100%";
  57873. VirtualJoystick.vjCanvas.style.position = "absolute";
  57874. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  57875. VirtualJoystick.vjCanvas.style.top = "0px";
  57876. VirtualJoystick.vjCanvas.style.left = "0px";
  57877. VirtualJoystick.vjCanvas.style.zIndex = "5";
  57878. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  57879. // Support for jQuery PEP polyfill
  57880. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  57881. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  57882. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  57883. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  57884. document.body.appendChild(VirtualJoystick.vjCanvas);
  57885. }
  57886. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  57887. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  57888. this.pressed = false;
  57889. // default joystick color
  57890. this._joystickColor = "cyan";
  57891. this._joystickPointerID = -1;
  57892. // current joystick position
  57893. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  57894. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  57895. // origin joystick position
  57896. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  57897. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  57898. this._onPointerDownHandlerRef = function (evt) {
  57899. _this._onPointerDown(evt);
  57900. };
  57901. this._onPointerMoveHandlerRef = function (evt) {
  57902. _this._onPointerMove(evt);
  57903. };
  57904. this._onPointerOutHandlerRef = function (evt) {
  57905. _this._onPointerUp(evt);
  57906. };
  57907. this._onPointerUpHandlerRef = function (evt) {
  57908. _this._onPointerUp(evt);
  57909. };
  57910. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  57911. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  57912. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  57913. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  57914. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  57915. evt.preventDefault(); // Disables system menu
  57916. }, false);
  57917. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  57918. }
  57919. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  57920. this._joystickSensibility = newJoystickSensibility;
  57921. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  57922. };
  57923. VirtualJoystick.prototype._onPointerDown = function (e) {
  57924. var positionOnScreenCondition;
  57925. e.preventDefault();
  57926. if (this._leftJoystick === true) {
  57927. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  57928. }
  57929. else {
  57930. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  57931. }
  57932. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  57933. // First contact will be dedicated to the virtual joystick
  57934. this._joystickPointerID = e.pointerId;
  57935. this._joystickPointerStartPos.x = e.clientX;
  57936. this._joystickPointerStartPos.y = e.clientY;
  57937. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  57938. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  57939. this._deltaJoystickVector.x = 0;
  57940. this._deltaJoystickVector.y = 0;
  57941. this.pressed = true;
  57942. this._touches.add(e.pointerId.toString(), e);
  57943. }
  57944. else {
  57945. // You can only trigger the action buttons with a joystick declared
  57946. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  57947. this._action();
  57948. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  57949. }
  57950. }
  57951. };
  57952. VirtualJoystick.prototype._onPointerMove = function (e) {
  57953. // If the current pointer is the one associated to the joystick (first touch contact)
  57954. if (this._joystickPointerID == e.pointerId) {
  57955. this._joystickPointerPos.x = e.clientX;
  57956. this._joystickPointerPos.y = e.clientY;
  57957. this._deltaJoystickVector = this._joystickPointerPos.clone();
  57958. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  57959. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  57960. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  57961. switch (this._axisTargetedByLeftAndRight) {
  57962. case JoystickAxis.X:
  57963. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  57964. break;
  57965. case JoystickAxis.Y:
  57966. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  57967. break;
  57968. case JoystickAxis.Z:
  57969. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  57970. break;
  57971. }
  57972. var directionUpDown = this.reverseUpDown ? 1 : -1;
  57973. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  57974. switch (this._axisTargetedByUpAndDown) {
  57975. case JoystickAxis.X:
  57976. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  57977. break;
  57978. case JoystickAxis.Y:
  57979. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  57980. break;
  57981. case JoystickAxis.Z:
  57982. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  57983. break;
  57984. }
  57985. }
  57986. else {
  57987. var data = this._touches.get(e.pointerId.toString());
  57988. if (data) {
  57989. data.x = e.clientX;
  57990. data.y = e.clientY;
  57991. }
  57992. }
  57993. };
  57994. VirtualJoystick.prototype._onPointerUp = function (e) {
  57995. if (this._joystickPointerID == e.pointerId) {
  57996. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  57997. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  57998. this._joystickPointerID = -1;
  57999. this.pressed = false;
  58000. }
  58001. else {
  58002. var touch = this._touches.get(e.pointerId.toString());
  58003. if (touch) {
  58004. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  58005. }
  58006. }
  58007. this._deltaJoystickVector.x = 0;
  58008. this._deltaJoystickVector.y = 0;
  58009. this._touches.remove(e.pointerId.toString());
  58010. };
  58011. /**
  58012. * Change the color of the virtual joystick
  58013. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  58014. */
  58015. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  58016. this._joystickColor = newColor;
  58017. };
  58018. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  58019. this._action = action;
  58020. };
  58021. // Define which axis you'd like to control for left & right
  58022. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  58023. switch (axis) {
  58024. case JoystickAxis.X:
  58025. case JoystickAxis.Y:
  58026. case JoystickAxis.Z:
  58027. this._axisTargetedByLeftAndRight = axis;
  58028. break;
  58029. default:
  58030. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  58031. break;
  58032. }
  58033. };
  58034. // Define which axis you'd like to control for up & down
  58035. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  58036. switch (axis) {
  58037. case JoystickAxis.X:
  58038. case JoystickAxis.Y:
  58039. case JoystickAxis.Z:
  58040. this._axisTargetedByUpAndDown = axis;
  58041. break;
  58042. default:
  58043. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  58044. break;
  58045. }
  58046. };
  58047. VirtualJoystick.prototype._clearCanvas = function () {
  58048. if (this._leftJoystick) {
  58049. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  58050. }
  58051. else {
  58052. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  58053. }
  58054. };
  58055. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  58056. var _this = this;
  58057. if (this.pressed) {
  58058. this._touches.forEach(function (key, touch) {
  58059. if (touch.pointerId === _this._joystickPointerID) {
  58060. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  58061. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  58062. VirtualJoystick.vjCanvasContext.beginPath();
  58063. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  58064. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  58065. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  58066. VirtualJoystick.vjCanvasContext.stroke();
  58067. VirtualJoystick.vjCanvasContext.closePath();
  58068. VirtualJoystick.vjCanvasContext.beginPath();
  58069. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  58070. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  58071. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  58072. VirtualJoystick.vjCanvasContext.stroke();
  58073. VirtualJoystick.vjCanvasContext.closePath();
  58074. VirtualJoystick.vjCanvasContext.beginPath();
  58075. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  58076. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  58077. VirtualJoystick.vjCanvasContext.stroke();
  58078. VirtualJoystick.vjCanvasContext.closePath();
  58079. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  58080. }
  58081. else {
  58082. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  58083. VirtualJoystick.vjCanvasContext.beginPath();
  58084. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  58085. VirtualJoystick.vjCanvasContext.beginPath();
  58086. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  58087. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  58088. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  58089. VirtualJoystick.vjCanvasContext.stroke();
  58090. VirtualJoystick.vjCanvasContext.closePath();
  58091. touch.prevX = touch.x;
  58092. touch.prevY = touch.y;
  58093. }
  58094. ;
  58095. });
  58096. }
  58097. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  58098. };
  58099. VirtualJoystick.prototype.releaseCanvas = function () {
  58100. if (VirtualJoystick.vjCanvas) {
  58101. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  58102. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  58103. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  58104. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  58105. window.removeEventListener("resize", this._onResize);
  58106. document.body.removeChild(VirtualJoystick.vjCanvas);
  58107. VirtualJoystick.vjCanvas = null;
  58108. }
  58109. };
  58110. return VirtualJoystick;
  58111. }());
  58112. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  58113. VirtualJoystick._globalJoystickIndex = 0;
  58114. BABYLON.VirtualJoystick = VirtualJoystick;
  58115. })(BABYLON || (BABYLON = {}));
  58116. //# sourceMappingURL=babylon.virtualJoystick.js.map
  58117. var BABYLON;
  58118. (function (BABYLON) {
  58119. // We're mainly based on the logic defined into the FreeCamera code
  58120. var VirtualJoysticksCamera = (function (_super) {
  58121. __extends(VirtualJoysticksCamera, _super);
  58122. function VirtualJoysticksCamera(name, position, scene) {
  58123. var _this = _super.call(this, name, position, scene) || this;
  58124. _this.inputs.addVirtualJoystick();
  58125. return _this;
  58126. }
  58127. VirtualJoysticksCamera.prototype.getClassName = function () {
  58128. return "VirtualJoysticksCamera";
  58129. };
  58130. return VirtualJoysticksCamera;
  58131. }(BABYLON.FreeCamera));
  58132. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  58133. })(BABYLON || (BABYLON = {}));
  58134. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  58135. var BABYLON;
  58136. (function (BABYLON) {
  58137. var FreeCameraVirtualJoystickInput = (function () {
  58138. function FreeCameraVirtualJoystickInput() {
  58139. }
  58140. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  58141. return this._leftjoystick;
  58142. };
  58143. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  58144. return this._rightjoystick;
  58145. };
  58146. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  58147. if (this._leftjoystick) {
  58148. var camera = this.camera;
  58149. var speed = camera._computeLocalCameraSpeed() * 50;
  58150. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  58151. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  58152. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  58153. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  58154. if (!this._leftjoystick.pressed) {
  58155. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  58156. }
  58157. if (!this._rightjoystick.pressed) {
  58158. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  58159. }
  58160. }
  58161. };
  58162. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  58163. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  58164. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  58165. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  58166. this._leftjoystick.setJoystickSensibility(0.15);
  58167. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  58168. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  58169. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  58170. this._rightjoystick.reverseUpDown = true;
  58171. this._rightjoystick.setJoystickSensibility(0.05);
  58172. this._rightjoystick.setJoystickColor("yellow");
  58173. };
  58174. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  58175. this._leftjoystick.releaseCanvas();
  58176. this._rightjoystick.releaseCanvas();
  58177. };
  58178. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  58179. return "FreeCameraVirtualJoystickInput";
  58180. };
  58181. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  58182. return "virtualJoystick";
  58183. };
  58184. return FreeCameraVirtualJoystickInput;
  58185. }());
  58186. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  58187. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  58188. })(BABYLON || (BABYLON = {}));
  58189. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  58190. var BABYLON;
  58191. (function (BABYLON) {
  58192. var SimplificationSettings = (function () {
  58193. function SimplificationSettings(quality, distance, optimizeMesh) {
  58194. this.quality = quality;
  58195. this.distance = distance;
  58196. this.optimizeMesh = optimizeMesh;
  58197. }
  58198. return SimplificationSettings;
  58199. }());
  58200. BABYLON.SimplificationSettings = SimplificationSettings;
  58201. var SimplificationQueue = (function () {
  58202. function SimplificationQueue() {
  58203. this.running = false;
  58204. this._simplificationArray = [];
  58205. }
  58206. SimplificationQueue.prototype.addTask = function (task) {
  58207. this._simplificationArray.push(task);
  58208. };
  58209. SimplificationQueue.prototype.executeNext = function () {
  58210. var task = this._simplificationArray.pop();
  58211. if (task) {
  58212. this.running = true;
  58213. this.runSimplification(task);
  58214. }
  58215. else {
  58216. this.running = false;
  58217. }
  58218. };
  58219. SimplificationQueue.prototype.runSimplification = function (task) {
  58220. var _this = this;
  58221. if (task.parallelProcessing) {
  58222. //parallel simplifier
  58223. task.settings.forEach(function (setting) {
  58224. var simplifier = _this.getSimplifier(task);
  58225. simplifier.simplify(setting, function (newMesh) {
  58226. task.mesh.addLODLevel(setting.distance, newMesh);
  58227. newMesh.isVisible = true;
  58228. //check if it is the last
  58229. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  58230. //all done, run the success callback.
  58231. task.successCallback();
  58232. }
  58233. _this.executeNext();
  58234. });
  58235. });
  58236. }
  58237. else {
  58238. //single simplifier.
  58239. var simplifier = this.getSimplifier(task);
  58240. var runDecimation = function (setting, callback) {
  58241. simplifier.simplify(setting, function (newMesh) {
  58242. task.mesh.addLODLevel(setting.distance, newMesh);
  58243. newMesh.isVisible = true;
  58244. //run the next quality level
  58245. callback();
  58246. });
  58247. };
  58248. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  58249. runDecimation(task.settings[loop.index], function () {
  58250. loop.executeNext();
  58251. });
  58252. }, function () {
  58253. //execution ended, run the success callback.
  58254. if (task.successCallback) {
  58255. task.successCallback();
  58256. }
  58257. _this.executeNext();
  58258. });
  58259. }
  58260. };
  58261. SimplificationQueue.prototype.getSimplifier = function (task) {
  58262. switch (task.simplificationType) {
  58263. case SimplificationType.QUADRATIC:
  58264. default:
  58265. return new QuadraticErrorSimplification(task.mesh);
  58266. }
  58267. };
  58268. return SimplificationQueue;
  58269. }());
  58270. BABYLON.SimplificationQueue = SimplificationQueue;
  58271. /**
  58272. * The implemented types of simplification.
  58273. * At the moment only Quadratic Error Decimation is implemented.
  58274. */
  58275. var SimplificationType;
  58276. (function (SimplificationType) {
  58277. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  58278. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  58279. var DecimationTriangle = (function () {
  58280. function DecimationTriangle(vertices) {
  58281. this.vertices = vertices;
  58282. this.error = new Array(4);
  58283. this.deleted = false;
  58284. this.isDirty = false;
  58285. this.deletePending = false;
  58286. this.borderFactor = 0;
  58287. }
  58288. return DecimationTriangle;
  58289. }());
  58290. BABYLON.DecimationTriangle = DecimationTriangle;
  58291. var DecimationVertex = (function () {
  58292. function DecimationVertex(position, id) {
  58293. this.position = position;
  58294. this.id = id;
  58295. this.isBorder = true;
  58296. this.q = new QuadraticMatrix();
  58297. this.triangleCount = 0;
  58298. this.triangleStart = 0;
  58299. this.originalOffsets = [];
  58300. }
  58301. DecimationVertex.prototype.updatePosition = function (newPosition) {
  58302. this.position.copyFrom(newPosition);
  58303. };
  58304. return DecimationVertex;
  58305. }());
  58306. BABYLON.DecimationVertex = DecimationVertex;
  58307. var QuadraticMatrix = (function () {
  58308. function QuadraticMatrix(data) {
  58309. this.data = new Array(10);
  58310. for (var i = 0; i < 10; ++i) {
  58311. if (data && data[i]) {
  58312. this.data[i] = data[i];
  58313. }
  58314. else {
  58315. this.data[i] = 0;
  58316. }
  58317. }
  58318. }
  58319. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  58320. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  58321. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  58322. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  58323. return det;
  58324. };
  58325. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  58326. for (var i = 0; i < 10; ++i) {
  58327. this.data[i] += matrix.data[i];
  58328. }
  58329. };
  58330. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  58331. for (var i = 0; i < 10; ++i) {
  58332. this.data[i] += data[i];
  58333. }
  58334. };
  58335. QuadraticMatrix.prototype.add = function (matrix) {
  58336. var m = new QuadraticMatrix();
  58337. for (var i = 0; i < 10; ++i) {
  58338. m.data[i] = this.data[i] + matrix.data[i];
  58339. }
  58340. return m;
  58341. };
  58342. QuadraticMatrix.FromData = function (a, b, c, d) {
  58343. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  58344. };
  58345. //returning an array to avoid garbage collection
  58346. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  58347. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  58348. };
  58349. return QuadraticMatrix;
  58350. }());
  58351. BABYLON.QuadraticMatrix = QuadraticMatrix;
  58352. var Reference = (function () {
  58353. function Reference(vertexId, triangleId) {
  58354. this.vertexId = vertexId;
  58355. this.triangleId = triangleId;
  58356. }
  58357. return Reference;
  58358. }());
  58359. BABYLON.Reference = Reference;
  58360. /**
  58361. * An implementation of the Quadratic Error simplification algorithm.
  58362. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  58363. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  58364. * @author RaananW
  58365. */
  58366. var QuadraticErrorSimplification = (function () {
  58367. function QuadraticErrorSimplification(_mesh) {
  58368. this._mesh = _mesh;
  58369. this.initialized = false;
  58370. this.syncIterations = 5000;
  58371. this.aggressiveness = 7;
  58372. this.decimationIterations = 100;
  58373. this.boundingBoxEpsilon = BABYLON.Epsilon;
  58374. }
  58375. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  58376. var _this = this;
  58377. this.initDecimatedMesh();
  58378. //iterating through the submeshes array, one after the other.
  58379. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  58380. _this.initWithMesh(loop.index, function () {
  58381. _this.runDecimation(settings, loop.index, function () {
  58382. loop.executeNext();
  58383. });
  58384. }, settings.optimizeMesh);
  58385. }, function () {
  58386. setTimeout(function () {
  58387. successCallback(_this._reconstructedMesh);
  58388. }, 0);
  58389. });
  58390. };
  58391. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  58392. var _this = this;
  58393. var gCount = 0;
  58394. triangle.vertices.forEach(function (vertex) {
  58395. var count = 0;
  58396. var vPos = vertex.position;
  58397. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  58398. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  58399. ++count;
  58400. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  58401. ++count;
  58402. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  58403. ++count;
  58404. if (count > 1) {
  58405. ++gCount;
  58406. }
  58407. ;
  58408. });
  58409. if (gCount > 1) {
  58410. console.log(triangle, gCount);
  58411. }
  58412. return gCount > 1;
  58413. };
  58414. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  58415. var _this = this;
  58416. var targetCount = ~~(this.triangles.length * settings.quality);
  58417. var deletedTriangles = 0;
  58418. var triangleCount = this.triangles.length;
  58419. var iterationFunction = function (iteration, callback) {
  58420. setTimeout(function () {
  58421. if (iteration % 5 === 0) {
  58422. _this.updateMesh(iteration === 0);
  58423. }
  58424. for (var i = 0; i < _this.triangles.length; ++i) {
  58425. _this.triangles[i].isDirty = false;
  58426. }
  58427. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  58428. var trianglesIterator = function (i) {
  58429. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  58430. var t = _this.triangles[tIdx];
  58431. if (!t)
  58432. return;
  58433. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  58434. return;
  58435. }
  58436. for (var j = 0; j < 3; ++j) {
  58437. if (t.error[j] < threshold) {
  58438. var deleted0 = [];
  58439. var deleted1 = [];
  58440. var v0 = t.vertices[j];
  58441. var v1 = t.vertices[(j + 1) % 3];
  58442. if (v0.isBorder || v1.isBorder)
  58443. continue;
  58444. var p = BABYLON.Vector3.Zero();
  58445. var n = BABYLON.Vector3.Zero();
  58446. var uv = BABYLON.Vector2.Zero();
  58447. var color = new BABYLON.Color4(0, 0, 0, 1);
  58448. _this.calculateError(v0, v1, p, n, uv, color);
  58449. var delTr = [];
  58450. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  58451. continue;
  58452. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  58453. continue;
  58454. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  58455. continue;
  58456. var uniqueArray = [];
  58457. delTr.forEach(function (deletedT) {
  58458. if (uniqueArray.indexOf(deletedT) === -1) {
  58459. deletedT.deletePending = true;
  58460. uniqueArray.push(deletedT);
  58461. }
  58462. });
  58463. if (uniqueArray.length % 2 !== 0) {
  58464. continue;
  58465. }
  58466. v0.q = v1.q.add(v0.q);
  58467. v0.updatePosition(p);
  58468. var tStart = _this.references.length;
  58469. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  58470. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  58471. var tCount = _this.references.length - tStart;
  58472. if (tCount <= v0.triangleCount) {
  58473. if (tCount) {
  58474. for (var c = 0; c < tCount; c++) {
  58475. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  58476. }
  58477. }
  58478. }
  58479. else {
  58480. v0.triangleStart = tStart;
  58481. }
  58482. v0.triangleCount = tCount;
  58483. break;
  58484. }
  58485. }
  58486. };
  58487. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  58488. }, 0);
  58489. };
  58490. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  58491. if (triangleCount - deletedTriangles <= targetCount)
  58492. loop.breakLoop();
  58493. else {
  58494. iterationFunction(loop.index, function () {
  58495. loop.executeNext();
  58496. });
  58497. }
  58498. }, function () {
  58499. setTimeout(function () {
  58500. //reconstruct this part of the mesh
  58501. _this.reconstructMesh(submeshIndex);
  58502. successCallback();
  58503. }, 0);
  58504. });
  58505. };
  58506. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  58507. var _this = this;
  58508. this.vertices = [];
  58509. this.triangles = [];
  58510. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58511. var indices = this._mesh.getIndices();
  58512. var submesh = this._mesh.subMeshes[submeshIndex];
  58513. var findInVertices = function (positionToSearch) {
  58514. if (optimizeMesh) {
  58515. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  58516. if (_this.vertices[ii].position.equals(positionToSearch)) {
  58517. return _this.vertices[ii];
  58518. }
  58519. }
  58520. }
  58521. return null;
  58522. };
  58523. var vertexReferences = [];
  58524. var vertexInit = function (i) {
  58525. var offset = i + submesh.verticesStart;
  58526. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  58527. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  58528. vertex.originalOffsets.push(offset);
  58529. if (vertex.id === _this.vertices.length) {
  58530. _this.vertices.push(vertex);
  58531. }
  58532. vertexReferences.push(vertex.id);
  58533. };
  58534. //var totalVertices = mesh.getTotalVertices();
  58535. var totalVertices = submesh.verticesCount;
  58536. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  58537. var indicesInit = function (i) {
  58538. var offset = (submesh.indexStart / 3) + i;
  58539. var pos = (offset * 3);
  58540. var i0 = indices[pos + 0];
  58541. var i1 = indices[pos + 1];
  58542. var i2 = indices[pos + 2];
  58543. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  58544. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  58545. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  58546. var triangle = new DecimationTriangle([v0, v1, v2]);
  58547. triangle.originalOffset = pos;
  58548. _this.triangles.push(triangle);
  58549. };
  58550. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  58551. _this.init(callback);
  58552. });
  58553. });
  58554. };
  58555. QuadraticErrorSimplification.prototype.init = function (callback) {
  58556. var _this = this;
  58557. var triangleInit1 = function (i) {
  58558. var t = _this.triangles[i];
  58559. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  58560. for (var j = 0; j < 3; j++) {
  58561. 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))));
  58562. }
  58563. };
  58564. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  58565. var triangleInit2 = function (i) {
  58566. var t = _this.triangles[i];
  58567. for (var j = 0; j < 3; ++j) {
  58568. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  58569. }
  58570. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  58571. };
  58572. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  58573. _this.initialized = true;
  58574. callback();
  58575. });
  58576. });
  58577. };
  58578. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  58579. var newTriangles = [];
  58580. var i;
  58581. for (i = 0; i < this.vertices.length; ++i) {
  58582. this.vertices[i].triangleCount = 0;
  58583. }
  58584. var t;
  58585. var j;
  58586. for (i = 0; i < this.triangles.length; ++i) {
  58587. if (!this.triangles[i].deleted) {
  58588. t = this.triangles[i];
  58589. for (j = 0; j < 3; ++j) {
  58590. t.vertices[j].triangleCount = 1;
  58591. }
  58592. newTriangles.push(t);
  58593. }
  58594. }
  58595. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  58596. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  58597. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  58598. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  58599. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58600. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58601. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58602. var vertexCount = 0;
  58603. for (i = 0; i < this.vertices.length; ++i) {
  58604. var vertex = this.vertices[i];
  58605. vertex.id = vertexCount;
  58606. if (vertex.triangleCount) {
  58607. vertex.originalOffsets.forEach(function (originalOffset) {
  58608. newPositionData.push(vertex.position.x);
  58609. newPositionData.push(vertex.position.y);
  58610. newPositionData.push(vertex.position.z);
  58611. newNormalData.push(normalData[originalOffset * 3]);
  58612. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  58613. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  58614. if (uvs && uvs.length) {
  58615. newUVsData.push(uvs[(originalOffset * 2)]);
  58616. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  58617. }
  58618. else if (colorsData && colorsData.length) {
  58619. newColorsData.push(colorsData[(originalOffset * 4)]);
  58620. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  58621. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  58622. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  58623. }
  58624. ++vertexCount;
  58625. });
  58626. }
  58627. }
  58628. var startingIndex = this._reconstructedMesh.getTotalIndices();
  58629. var startingVertex = this._reconstructedMesh.getTotalVertices();
  58630. var submeshesArray = this._reconstructedMesh.subMeshes;
  58631. this._reconstructedMesh.subMeshes = [];
  58632. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  58633. var originalIndices = this._mesh.getIndices();
  58634. for (i = 0; i < newTriangles.length; ++i) {
  58635. t = newTriangles[i]; //now get the new referencing point for each vertex
  58636. [0, 1, 2].forEach(function (idx) {
  58637. var id = originalIndices[t.originalOffset + idx];
  58638. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  58639. if (offset < 0)
  58640. offset = 0;
  58641. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  58642. });
  58643. }
  58644. //overwriting the old vertex buffers and indices.
  58645. this._reconstructedMesh.setIndices(newIndicesArray);
  58646. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  58647. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  58648. if (newUVsData.length > 0)
  58649. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  58650. if (newColorsData.length > 0)
  58651. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  58652. //create submesh
  58653. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  58654. if (submeshIndex > 0) {
  58655. this._reconstructedMesh.subMeshes = [];
  58656. submeshesArray.forEach(function (submesh) {
  58657. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  58658. });
  58659. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  58660. }
  58661. };
  58662. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  58663. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  58664. this._reconstructedMesh.material = this._mesh.material;
  58665. this._reconstructedMesh.parent = this._mesh.parent;
  58666. this._reconstructedMesh.isVisible = false;
  58667. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  58668. };
  58669. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  58670. for (var i = 0; i < vertex1.triangleCount; ++i) {
  58671. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  58672. if (t.deleted)
  58673. continue;
  58674. var s = this.references[vertex1.triangleStart + i].vertexId;
  58675. var v1 = t.vertices[(s + 1) % 3];
  58676. var v2 = t.vertices[(s + 2) % 3];
  58677. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  58678. deletedArray[i] = true;
  58679. delTr.push(t);
  58680. continue;
  58681. }
  58682. var d1 = v1.position.subtract(point);
  58683. d1 = d1.normalize();
  58684. var d2 = v2.position.subtract(point);
  58685. d2 = d2.normalize();
  58686. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  58687. return true;
  58688. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  58689. deletedArray[i] = false;
  58690. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  58691. return true;
  58692. }
  58693. return false;
  58694. };
  58695. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  58696. var newDeleted = deletedTriangles;
  58697. for (var i = 0; i < vertex.triangleCount; ++i) {
  58698. var ref = this.references[vertex.triangleStart + i];
  58699. var t = this.triangles[ref.triangleId];
  58700. if (t.deleted)
  58701. continue;
  58702. if (deletedArray[i] && t.deletePending) {
  58703. t.deleted = true;
  58704. newDeleted++;
  58705. continue;
  58706. }
  58707. t.vertices[ref.vertexId] = origVertex;
  58708. t.isDirty = true;
  58709. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  58710. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  58711. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  58712. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  58713. this.references.push(ref);
  58714. }
  58715. return newDeleted;
  58716. };
  58717. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  58718. for (var i = 0; i < this.vertices.length; ++i) {
  58719. var vCount = [];
  58720. var vId = [];
  58721. var v = this.vertices[i];
  58722. var j;
  58723. for (j = 0; j < v.triangleCount; ++j) {
  58724. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  58725. for (var ii = 0; ii < 3; ii++) {
  58726. var ofs = 0;
  58727. var vv = triangle.vertices[ii];
  58728. while (ofs < vCount.length) {
  58729. if (vId[ofs] === vv.id)
  58730. break;
  58731. ++ofs;
  58732. }
  58733. if (ofs === vCount.length) {
  58734. vCount.push(1);
  58735. vId.push(vv.id);
  58736. }
  58737. else {
  58738. vCount[ofs]++;
  58739. }
  58740. }
  58741. }
  58742. for (j = 0; j < vCount.length; ++j) {
  58743. if (vCount[j] === 1) {
  58744. this.vertices[vId[j]].isBorder = true;
  58745. }
  58746. else {
  58747. this.vertices[vId[j]].isBorder = false;
  58748. }
  58749. }
  58750. }
  58751. };
  58752. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  58753. if (identifyBorders === void 0) { identifyBorders = false; }
  58754. var i;
  58755. if (!identifyBorders) {
  58756. var newTrianglesVector = [];
  58757. for (i = 0; i < this.triangles.length; ++i) {
  58758. if (!this.triangles[i].deleted) {
  58759. newTrianglesVector.push(this.triangles[i]);
  58760. }
  58761. }
  58762. this.triangles = newTrianglesVector;
  58763. }
  58764. for (i = 0; i < this.vertices.length; ++i) {
  58765. this.vertices[i].triangleCount = 0;
  58766. this.vertices[i].triangleStart = 0;
  58767. }
  58768. var t;
  58769. var j;
  58770. var v;
  58771. for (i = 0; i < this.triangles.length; ++i) {
  58772. t = this.triangles[i];
  58773. for (j = 0; j < 3; ++j) {
  58774. v = t.vertices[j];
  58775. v.triangleCount++;
  58776. }
  58777. }
  58778. var tStart = 0;
  58779. for (i = 0; i < this.vertices.length; ++i) {
  58780. this.vertices[i].triangleStart = tStart;
  58781. tStart += this.vertices[i].triangleCount;
  58782. this.vertices[i].triangleCount = 0;
  58783. }
  58784. var newReferences = new Array(this.triangles.length * 3);
  58785. for (i = 0; i < this.triangles.length; ++i) {
  58786. t = this.triangles[i];
  58787. for (j = 0; j < 3; ++j) {
  58788. v = t.vertices[j];
  58789. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  58790. v.triangleCount++;
  58791. }
  58792. }
  58793. this.references = newReferences;
  58794. if (identifyBorders) {
  58795. this.identifyBorder();
  58796. }
  58797. };
  58798. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  58799. var x = point.x;
  58800. var y = point.y;
  58801. var z = point.z;
  58802. 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
  58803. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  58804. };
  58805. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  58806. var q = vertex1.q.add(vertex2.q);
  58807. var border = vertex1.isBorder && vertex2.isBorder;
  58808. var error = 0;
  58809. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  58810. if (qDet !== 0 && !border) {
  58811. if (!pointResult) {
  58812. pointResult = BABYLON.Vector3.Zero();
  58813. }
  58814. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  58815. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  58816. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  58817. error = this.vertexError(q, pointResult);
  58818. }
  58819. else {
  58820. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  58821. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  58822. var error1 = this.vertexError(q, vertex1.position);
  58823. var error2 = this.vertexError(q, vertex2.position);
  58824. var error3 = this.vertexError(q, p3);
  58825. error = Math.min(error1, error2, error3);
  58826. if (error === error1) {
  58827. if (pointResult) {
  58828. pointResult.copyFrom(vertex1.position);
  58829. }
  58830. }
  58831. else if (error === error2) {
  58832. if (pointResult) {
  58833. pointResult.copyFrom(vertex2.position);
  58834. }
  58835. }
  58836. else {
  58837. if (pointResult) {
  58838. pointResult.copyFrom(p3);
  58839. }
  58840. }
  58841. }
  58842. return error;
  58843. };
  58844. return QuadraticErrorSimplification;
  58845. }());
  58846. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  58847. })(BABYLON || (BABYLON = {}));
  58848. //# sourceMappingURL=babylon.meshSimplification.js.map
  58849. var BABYLON;
  58850. (function (BABYLON) {
  58851. var Internals;
  58852. (function (Internals) {
  58853. var MeshLODLevel = (function () {
  58854. function MeshLODLevel(distance, mesh) {
  58855. this.distance = distance;
  58856. this.mesh = mesh;
  58857. }
  58858. return MeshLODLevel;
  58859. }());
  58860. Internals.MeshLODLevel = MeshLODLevel;
  58861. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58862. })(BABYLON || (BABYLON = {}));
  58863. //# sourceMappingURL=babylon.meshLODLevel.js.map
  58864. var BABYLON;
  58865. (function (BABYLON) {
  58866. // Standard optimizations
  58867. var SceneOptimization = (function () {
  58868. function SceneOptimization(priority) {
  58869. if (priority === void 0) { priority = 0; }
  58870. this.priority = priority;
  58871. this.apply = function (scene) {
  58872. return true; // Return true if everything that can be done was applied
  58873. };
  58874. }
  58875. return SceneOptimization;
  58876. }());
  58877. BABYLON.SceneOptimization = SceneOptimization;
  58878. var TextureOptimization = (function (_super) {
  58879. __extends(TextureOptimization, _super);
  58880. function TextureOptimization(priority, maximumSize) {
  58881. if (priority === void 0) { priority = 0; }
  58882. if (maximumSize === void 0) { maximumSize = 1024; }
  58883. var _this = _super.call(this, priority) || this;
  58884. _this.priority = priority;
  58885. _this.maximumSize = maximumSize;
  58886. _this.apply = function (scene) {
  58887. var allDone = true;
  58888. for (var index = 0; index < scene.textures.length; index++) {
  58889. var texture = scene.textures[index];
  58890. if (!texture.canRescale) {
  58891. continue;
  58892. }
  58893. var currentSize = texture.getSize();
  58894. var maxDimension = Math.max(currentSize.width, currentSize.height);
  58895. if (maxDimension > _this.maximumSize) {
  58896. texture.scale(0.5);
  58897. allDone = false;
  58898. }
  58899. }
  58900. return allDone;
  58901. };
  58902. return _this;
  58903. }
  58904. return TextureOptimization;
  58905. }(SceneOptimization));
  58906. BABYLON.TextureOptimization = TextureOptimization;
  58907. var HardwareScalingOptimization = (function (_super) {
  58908. __extends(HardwareScalingOptimization, _super);
  58909. function HardwareScalingOptimization(priority, maximumScale) {
  58910. if (priority === void 0) { priority = 0; }
  58911. if (maximumScale === void 0) { maximumScale = 2; }
  58912. var _this = _super.call(this, priority) || this;
  58913. _this.priority = priority;
  58914. _this.maximumScale = maximumScale;
  58915. _this._currentScale = 1;
  58916. _this.apply = function (scene) {
  58917. _this._currentScale++;
  58918. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  58919. return _this._currentScale >= _this.maximumScale;
  58920. };
  58921. return _this;
  58922. }
  58923. return HardwareScalingOptimization;
  58924. }(SceneOptimization));
  58925. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  58926. var ShadowsOptimization = (function (_super) {
  58927. __extends(ShadowsOptimization, _super);
  58928. function ShadowsOptimization() {
  58929. var _this = _super !== null && _super.apply(this, arguments) || this;
  58930. _this.apply = function (scene) {
  58931. scene.shadowsEnabled = false;
  58932. return true;
  58933. };
  58934. return _this;
  58935. }
  58936. return ShadowsOptimization;
  58937. }(SceneOptimization));
  58938. BABYLON.ShadowsOptimization = ShadowsOptimization;
  58939. var PostProcessesOptimization = (function (_super) {
  58940. __extends(PostProcessesOptimization, _super);
  58941. function PostProcessesOptimization() {
  58942. var _this = _super !== null && _super.apply(this, arguments) || this;
  58943. _this.apply = function (scene) {
  58944. scene.postProcessesEnabled = false;
  58945. return true;
  58946. };
  58947. return _this;
  58948. }
  58949. return PostProcessesOptimization;
  58950. }(SceneOptimization));
  58951. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  58952. var LensFlaresOptimization = (function (_super) {
  58953. __extends(LensFlaresOptimization, _super);
  58954. function LensFlaresOptimization() {
  58955. var _this = _super !== null && _super.apply(this, arguments) || this;
  58956. _this.apply = function (scene) {
  58957. scene.lensFlaresEnabled = false;
  58958. return true;
  58959. };
  58960. return _this;
  58961. }
  58962. return LensFlaresOptimization;
  58963. }(SceneOptimization));
  58964. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  58965. var ParticlesOptimization = (function (_super) {
  58966. __extends(ParticlesOptimization, _super);
  58967. function ParticlesOptimization() {
  58968. var _this = _super !== null && _super.apply(this, arguments) || this;
  58969. _this.apply = function (scene) {
  58970. scene.particlesEnabled = false;
  58971. return true;
  58972. };
  58973. return _this;
  58974. }
  58975. return ParticlesOptimization;
  58976. }(SceneOptimization));
  58977. BABYLON.ParticlesOptimization = ParticlesOptimization;
  58978. var RenderTargetsOptimization = (function (_super) {
  58979. __extends(RenderTargetsOptimization, _super);
  58980. function RenderTargetsOptimization() {
  58981. var _this = _super !== null && _super.apply(this, arguments) || this;
  58982. _this.apply = function (scene) {
  58983. scene.renderTargetsEnabled = false;
  58984. return true;
  58985. };
  58986. return _this;
  58987. }
  58988. return RenderTargetsOptimization;
  58989. }(SceneOptimization));
  58990. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  58991. var MergeMeshesOptimization = (function (_super) {
  58992. __extends(MergeMeshesOptimization, _super);
  58993. function MergeMeshesOptimization() {
  58994. var _this = _super !== null && _super.apply(this, arguments) || this;
  58995. _this._canBeMerged = function (abstractMesh) {
  58996. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  58997. return false;
  58998. }
  58999. var mesh = abstractMesh;
  59000. if (!mesh.isVisible || !mesh.isEnabled()) {
  59001. return false;
  59002. }
  59003. if (mesh.instances.length > 0) {
  59004. return false;
  59005. }
  59006. if (mesh.skeleton || mesh.hasLODLevels) {
  59007. return false;
  59008. }
  59009. if (mesh.parent) {
  59010. return false;
  59011. }
  59012. return true;
  59013. };
  59014. _this.apply = function (scene, updateSelectionTree) {
  59015. var globalPool = scene.meshes.slice(0);
  59016. var globalLength = globalPool.length;
  59017. for (var index = 0; index < globalLength; index++) {
  59018. var currentPool = new Array();
  59019. var current = globalPool[index];
  59020. // Checks
  59021. if (!_this._canBeMerged(current)) {
  59022. continue;
  59023. }
  59024. currentPool.push(current);
  59025. // Find compatible meshes
  59026. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  59027. var otherMesh = globalPool[subIndex];
  59028. if (!_this._canBeMerged(otherMesh)) {
  59029. continue;
  59030. }
  59031. if (otherMesh.material !== current.material) {
  59032. continue;
  59033. }
  59034. if (otherMesh.checkCollisions !== current.checkCollisions) {
  59035. continue;
  59036. }
  59037. currentPool.push(otherMesh);
  59038. globalLength--;
  59039. globalPool.splice(subIndex, 1);
  59040. subIndex--;
  59041. }
  59042. if (currentPool.length < 2) {
  59043. continue;
  59044. }
  59045. // Merge meshes
  59046. BABYLON.Mesh.MergeMeshes(currentPool);
  59047. }
  59048. if (updateSelectionTree != undefined) {
  59049. if (updateSelectionTree) {
  59050. scene.createOrUpdateSelectionOctree();
  59051. }
  59052. }
  59053. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  59054. scene.createOrUpdateSelectionOctree();
  59055. }
  59056. return true;
  59057. };
  59058. return _this;
  59059. }
  59060. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  59061. get: function () {
  59062. return MergeMeshesOptimization._UpdateSelectionTree;
  59063. },
  59064. set: function (value) {
  59065. MergeMeshesOptimization._UpdateSelectionTree = value;
  59066. },
  59067. enumerable: true,
  59068. configurable: true
  59069. });
  59070. return MergeMeshesOptimization;
  59071. }(SceneOptimization));
  59072. MergeMeshesOptimization._UpdateSelectionTree = false;
  59073. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  59074. // Options
  59075. var SceneOptimizerOptions = (function () {
  59076. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  59077. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  59078. if (trackerDuration === void 0) { trackerDuration = 2000; }
  59079. this.targetFrameRate = targetFrameRate;
  59080. this.trackerDuration = trackerDuration;
  59081. this.optimizations = new Array();
  59082. }
  59083. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  59084. var result = new SceneOptimizerOptions(targetFrameRate);
  59085. var priority = 0;
  59086. result.optimizations.push(new MergeMeshesOptimization(priority));
  59087. result.optimizations.push(new ShadowsOptimization(priority));
  59088. result.optimizations.push(new LensFlaresOptimization(priority));
  59089. // Next priority
  59090. priority++;
  59091. result.optimizations.push(new PostProcessesOptimization(priority));
  59092. result.optimizations.push(new ParticlesOptimization(priority));
  59093. // Next priority
  59094. priority++;
  59095. result.optimizations.push(new TextureOptimization(priority, 1024));
  59096. return result;
  59097. };
  59098. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  59099. var result = new SceneOptimizerOptions(targetFrameRate);
  59100. var priority = 0;
  59101. result.optimizations.push(new MergeMeshesOptimization(priority));
  59102. result.optimizations.push(new ShadowsOptimization(priority));
  59103. result.optimizations.push(new LensFlaresOptimization(priority));
  59104. // Next priority
  59105. priority++;
  59106. result.optimizations.push(new PostProcessesOptimization(priority));
  59107. result.optimizations.push(new ParticlesOptimization(priority));
  59108. // Next priority
  59109. priority++;
  59110. result.optimizations.push(new TextureOptimization(priority, 512));
  59111. // Next priority
  59112. priority++;
  59113. result.optimizations.push(new RenderTargetsOptimization(priority));
  59114. // Next priority
  59115. priority++;
  59116. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  59117. return result;
  59118. };
  59119. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  59120. var result = new SceneOptimizerOptions(targetFrameRate);
  59121. var priority = 0;
  59122. result.optimizations.push(new MergeMeshesOptimization(priority));
  59123. result.optimizations.push(new ShadowsOptimization(priority));
  59124. result.optimizations.push(new LensFlaresOptimization(priority));
  59125. // Next priority
  59126. priority++;
  59127. result.optimizations.push(new PostProcessesOptimization(priority));
  59128. result.optimizations.push(new ParticlesOptimization(priority));
  59129. // Next priority
  59130. priority++;
  59131. result.optimizations.push(new TextureOptimization(priority, 256));
  59132. // Next priority
  59133. priority++;
  59134. result.optimizations.push(new RenderTargetsOptimization(priority));
  59135. // Next priority
  59136. priority++;
  59137. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  59138. return result;
  59139. };
  59140. return SceneOptimizerOptions;
  59141. }());
  59142. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  59143. // Scene optimizer tool
  59144. var SceneOptimizer = (function () {
  59145. function SceneOptimizer() {
  59146. }
  59147. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  59148. // TODO: add an epsilon
  59149. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  59150. if (onSuccess) {
  59151. onSuccess();
  59152. }
  59153. return;
  59154. }
  59155. // Apply current level of optimizations
  59156. var allDone = true;
  59157. var noOptimizationApplied = true;
  59158. for (var index = 0; index < options.optimizations.length; index++) {
  59159. var optimization = options.optimizations[index];
  59160. if (optimization.priority === currentPriorityLevel) {
  59161. noOptimizationApplied = false;
  59162. allDone = allDone && optimization.apply(scene);
  59163. }
  59164. }
  59165. // If no optimization was applied, this is a failure :(
  59166. if (noOptimizationApplied) {
  59167. if (onFailure) {
  59168. onFailure();
  59169. }
  59170. return;
  59171. }
  59172. // If all optimizations were done, move to next level
  59173. if (allDone) {
  59174. currentPriorityLevel++;
  59175. }
  59176. // Let's the system running for a specific amount of time before checking FPS
  59177. scene.executeWhenReady(function () {
  59178. setTimeout(function () {
  59179. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  59180. }, options.trackerDuration);
  59181. });
  59182. };
  59183. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  59184. if (!options) {
  59185. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  59186. }
  59187. // Let's the system running for a specific amount of time before checking FPS
  59188. scene.executeWhenReady(function () {
  59189. setTimeout(function () {
  59190. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  59191. }, options.trackerDuration);
  59192. });
  59193. };
  59194. return SceneOptimizer;
  59195. }());
  59196. BABYLON.SceneOptimizer = SceneOptimizer;
  59197. })(BABYLON || (BABYLON = {}));
  59198. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  59199. var BABYLON;
  59200. (function (BABYLON) {
  59201. var OutlineRenderer = (function () {
  59202. function OutlineRenderer(scene) {
  59203. this._scene = scene;
  59204. }
  59205. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  59206. var _this = this;
  59207. if (useOverlay === void 0) { useOverlay = false; }
  59208. var scene = this._scene;
  59209. var engine = this._scene.getEngine();
  59210. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  59211. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  59212. return;
  59213. }
  59214. var mesh = subMesh.getRenderingMesh();
  59215. var material = subMesh.getMaterial();
  59216. engine.enableEffect(this._effect);
  59217. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  59218. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  59219. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59220. // Bones
  59221. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59222. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59223. }
  59224. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  59225. // Alpha test
  59226. if (material && material.needAlphaTesting()) {
  59227. var alphaTexture = material.getAlphaTestTexture();
  59228. this._effect.setTexture("diffuseSampler", alphaTexture);
  59229. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59230. }
  59231. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  59232. };
  59233. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  59234. var defines = [];
  59235. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  59236. var mesh = subMesh.getMesh();
  59237. var material = subMesh.getMaterial();
  59238. // Alpha test
  59239. if (material && material.needAlphaTesting()) {
  59240. defines.push("#define ALPHATEST");
  59241. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59242. attribs.push(BABYLON.VertexBuffer.UVKind);
  59243. defines.push("#define UV1");
  59244. }
  59245. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59246. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59247. defines.push("#define UV2");
  59248. }
  59249. }
  59250. // Bones
  59251. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59252. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59253. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59254. if (mesh.numBoneInfluencers > 4) {
  59255. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59256. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59257. }
  59258. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59259. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59260. }
  59261. else {
  59262. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59263. }
  59264. // Instances
  59265. if (useInstances) {
  59266. defines.push("#define INSTANCES");
  59267. attribs.push("world0");
  59268. attribs.push("world1");
  59269. attribs.push("world2");
  59270. attribs.push("world3");
  59271. }
  59272. // Get correct effect
  59273. var join = defines.join("\n");
  59274. if (this._cachedDefines !== join) {
  59275. this._cachedDefines = join;
  59276. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  59277. }
  59278. return this._effect.isReady();
  59279. };
  59280. return OutlineRenderer;
  59281. }());
  59282. BABYLON.OutlineRenderer = OutlineRenderer;
  59283. })(BABYLON || (BABYLON = {}));
  59284. //# sourceMappingURL=babylon.outlineRenderer.js.map
  59285. var BABYLON;
  59286. (function (BABYLON) {
  59287. var FaceAdjacencies = (function () {
  59288. function FaceAdjacencies() {
  59289. this.edges = new Array();
  59290. this.edgesConnectedCount = 0;
  59291. }
  59292. return FaceAdjacencies;
  59293. }());
  59294. var EdgesRenderer = (function () {
  59295. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  59296. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  59297. if (epsilon === void 0) { epsilon = 0.95; }
  59298. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  59299. this.edgesWidthScalerForOrthographic = 1000.0;
  59300. this.edgesWidthScalerForPerspective = 50.0;
  59301. this._linesPositions = new Array();
  59302. this._linesNormals = new Array();
  59303. this._linesIndices = new Array();
  59304. this._buffers = {};
  59305. this._checkVerticesInsteadOfIndices = false;
  59306. this._source = source;
  59307. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  59308. this._epsilon = epsilon;
  59309. this._prepareRessources();
  59310. this._generateEdgesLines();
  59311. }
  59312. EdgesRenderer.prototype._prepareRessources = function () {
  59313. if (this._lineShader) {
  59314. return;
  59315. }
  59316. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  59317. attributes: ["position", "normal"],
  59318. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  59319. });
  59320. this._lineShader.disableDepthWrite = true;
  59321. this._lineShader.backFaceCulling = false;
  59322. };
  59323. EdgesRenderer.prototype.dispose = function () {
  59324. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  59325. if (buffer) {
  59326. buffer.dispose();
  59327. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  59328. }
  59329. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  59330. if (buffer) {
  59331. buffer.dispose();
  59332. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  59333. }
  59334. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  59335. this._lineShader.dispose();
  59336. };
  59337. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  59338. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  59339. return 0;
  59340. }
  59341. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  59342. return 1;
  59343. }
  59344. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  59345. return 2;
  59346. }
  59347. return -1;
  59348. };
  59349. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  59350. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  59351. return 0;
  59352. }
  59353. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  59354. return 1;
  59355. }
  59356. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  59357. return 2;
  59358. }
  59359. return -1;
  59360. };
  59361. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  59362. var needToCreateLine;
  59363. if (edge === undefined) {
  59364. needToCreateLine = true;
  59365. }
  59366. else {
  59367. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  59368. needToCreateLine = dotProduct < this._epsilon;
  59369. }
  59370. if (needToCreateLine) {
  59371. var offset = this._linesPositions.length / 3;
  59372. var normal = p0.subtract(p1);
  59373. normal.normalize();
  59374. // Positions
  59375. this._linesPositions.push(p0.x);
  59376. this._linesPositions.push(p0.y);
  59377. this._linesPositions.push(p0.z);
  59378. this._linesPositions.push(p0.x);
  59379. this._linesPositions.push(p0.y);
  59380. this._linesPositions.push(p0.z);
  59381. this._linesPositions.push(p1.x);
  59382. this._linesPositions.push(p1.y);
  59383. this._linesPositions.push(p1.z);
  59384. this._linesPositions.push(p1.x);
  59385. this._linesPositions.push(p1.y);
  59386. this._linesPositions.push(p1.z);
  59387. // Normals
  59388. this._linesNormals.push(p1.x);
  59389. this._linesNormals.push(p1.y);
  59390. this._linesNormals.push(p1.z);
  59391. this._linesNormals.push(-1);
  59392. this._linesNormals.push(p1.x);
  59393. this._linesNormals.push(p1.y);
  59394. this._linesNormals.push(p1.z);
  59395. this._linesNormals.push(1);
  59396. this._linesNormals.push(p0.x);
  59397. this._linesNormals.push(p0.y);
  59398. this._linesNormals.push(p0.z);
  59399. this._linesNormals.push(-1);
  59400. this._linesNormals.push(p0.x);
  59401. this._linesNormals.push(p0.y);
  59402. this._linesNormals.push(p0.z);
  59403. this._linesNormals.push(1);
  59404. // Indices
  59405. this._linesIndices.push(offset);
  59406. this._linesIndices.push(offset + 1);
  59407. this._linesIndices.push(offset + 2);
  59408. this._linesIndices.push(offset);
  59409. this._linesIndices.push(offset + 2);
  59410. this._linesIndices.push(offset + 3);
  59411. }
  59412. };
  59413. EdgesRenderer.prototype._generateEdgesLines = function () {
  59414. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59415. var indices = this._source.getIndices();
  59416. // First let's find adjacencies
  59417. var adjacencies = new Array();
  59418. var faceNormals = new Array();
  59419. var index;
  59420. var faceAdjacencies;
  59421. // Prepare faces
  59422. for (index = 0; index < indices.length; index += 3) {
  59423. faceAdjacencies = new FaceAdjacencies();
  59424. var p0Index = indices[index];
  59425. var p1Index = indices[index + 1];
  59426. var p2Index = indices[index + 2];
  59427. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  59428. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  59429. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  59430. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  59431. faceNormal.normalize();
  59432. faceNormals.push(faceNormal);
  59433. adjacencies.push(faceAdjacencies);
  59434. }
  59435. // Scan
  59436. for (index = 0; index < adjacencies.length; index++) {
  59437. faceAdjacencies = adjacencies[index];
  59438. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  59439. var otherFaceAdjacencies = adjacencies[otherIndex];
  59440. if (faceAdjacencies.edgesConnectedCount === 3) {
  59441. break;
  59442. }
  59443. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  59444. continue;
  59445. }
  59446. var otherP0 = indices[otherIndex * 3];
  59447. var otherP1 = indices[otherIndex * 3 + 1];
  59448. var otherP2 = indices[otherIndex * 3 + 2];
  59449. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  59450. var otherEdgeIndex;
  59451. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  59452. continue;
  59453. }
  59454. switch (edgeIndex) {
  59455. case 0:
  59456. if (this._checkVerticesInsteadOfIndices) {
  59457. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  59458. }
  59459. else {
  59460. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  59461. }
  59462. break;
  59463. case 1:
  59464. if (this._checkVerticesInsteadOfIndices) {
  59465. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  59466. }
  59467. else {
  59468. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  59469. }
  59470. break;
  59471. case 2:
  59472. if (this._checkVerticesInsteadOfIndices) {
  59473. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  59474. }
  59475. else {
  59476. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  59477. }
  59478. break;
  59479. }
  59480. if (otherEdgeIndex === -1) {
  59481. continue;
  59482. }
  59483. faceAdjacencies.edges[edgeIndex] = otherIndex;
  59484. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  59485. faceAdjacencies.edgesConnectedCount++;
  59486. otherFaceAdjacencies.edgesConnectedCount++;
  59487. if (faceAdjacencies.edgesConnectedCount === 3) {
  59488. break;
  59489. }
  59490. }
  59491. }
  59492. }
  59493. // Create lines
  59494. for (index = 0; index < adjacencies.length; index++) {
  59495. // 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
  59496. var current = adjacencies[index];
  59497. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  59498. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  59499. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  59500. }
  59501. // Merge into a single mesh
  59502. var engine = this._source.getScene().getEngine();
  59503. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  59504. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  59505. this._ib = engine.createIndexBuffer(this._linesIndices);
  59506. this._indicesCount = this._linesIndices.length;
  59507. };
  59508. EdgesRenderer.prototype.render = function () {
  59509. if (!this._lineShader.isReady()) {
  59510. return;
  59511. }
  59512. var scene = this._source.getScene();
  59513. var engine = scene.getEngine();
  59514. this._lineShader._preBind();
  59515. // VBOs
  59516. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  59517. scene.resetCachedMaterial();
  59518. this._lineShader.setColor4("color", this._source.edgesColor);
  59519. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  59520. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  59521. }
  59522. else {
  59523. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  59524. }
  59525. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  59526. this._lineShader.bind(this._source.getWorldMatrix());
  59527. // Draw order
  59528. engine.draw(true, 0, this._indicesCount);
  59529. this._lineShader.unbind();
  59530. engine.setDepthWrite(true);
  59531. };
  59532. return EdgesRenderer;
  59533. }());
  59534. BABYLON.EdgesRenderer = EdgesRenderer;
  59535. })(BABYLON || (BABYLON = {}));
  59536. //# sourceMappingURL=babylon.edgesRenderer.js.map
  59537. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  59538. /// <reference path="..\Math\babylon.math.ts" />
  59539. var BABYLON;
  59540. (function (BABYLON) {
  59541. /**
  59542. * Special Glow Blur post process only blurring the alpha channel
  59543. * It enforces keeping the most luminous color in the color channel.
  59544. */
  59545. var GlowBlurPostProcess = (function (_super) {
  59546. __extends(GlowBlurPostProcess, _super);
  59547. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  59548. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59549. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  59550. _this.direction = direction;
  59551. _this.blurWidth = blurWidth;
  59552. _this.onApplyObservable.add(function (effect) {
  59553. effect.setFloat2("screenSize", _this.width, _this.height);
  59554. effect.setVector2("direction", _this.direction);
  59555. effect.setFloat("blurWidth", _this.blurWidth);
  59556. });
  59557. return _this;
  59558. }
  59559. return GlowBlurPostProcess;
  59560. }(BABYLON.PostProcess));
  59561. /**
  59562. * The highlight layer Helps adding a glow effect around a mesh.
  59563. *
  59564. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  59565. * glowy meshes to your scene.
  59566. *
  59567. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  59568. */
  59569. var HighlightLayer = (function () {
  59570. /**
  59571. * Instantiates a new highlight Layer and references it to the scene..
  59572. * @param name The name of the layer
  59573. * @param scene The scene to use the layer in
  59574. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  59575. */
  59576. function HighlightLayer(name, scene, options) {
  59577. this.name = name;
  59578. this._vertexBuffers = {};
  59579. this._mainTextureDesiredSize = { width: 0, height: 0 };
  59580. this._meshes = {};
  59581. this._maxSize = 0;
  59582. this._shouldRender = false;
  59583. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  59584. this._excludedMeshes = {};
  59585. /**
  59586. * Specifies whether or not the inner glow is ACTIVE in the layer.
  59587. */
  59588. this.innerGlow = true;
  59589. /**
  59590. * Specifies whether or not the outer glow is ACTIVE in the layer.
  59591. */
  59592. this.outerGlow = true;
  59593. /**
  59594. * Specifies wether the highlight layer is enabled or not.
  59595. */
  59596. this.isEnabled = true;
  59597. /**
  59598. * An event triggered when the highlight layer has been disposed.
  59599. * @type {BABYLON.Observable}
  59600. */
  59601. this.onDisposeObservable = new BABYLON.Observable();
  59602. /**
  59603. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  59604. * @type {BABYLON.Observable}
  59605. */
  59606. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  59607. /**
  59608. * An event triggered when the highlight layer is being blurred.
  59609. * @type {BABYLON.Observable}
  59610. */
  59611. this.onBeforeBlurObservable = new BABYLON.Observable();
  59612. /**
  59613. * An event triggered when the highlight layer has been blurred.
  59614. * @type {BABYLON.Observable}
  59615. */
  59616. this.onAfterBlurObservable = new BABYLON.Observable();
  59617. /**
  59618. * An event triggered when the glowing blurred texture is being merged in the scene.
  59619. * @type {BABYLON.Observable}
  59620. */
  59621. this.onBeforeComposeObservable = new BABYLON.Observable();
  59622. /**
  59623. * An event triggered when the glowing blurred texture has been merged in the scene.
  59624. * @type {BABYLON.Observable}
  59625. */
  59626. this.onAfterComposeObservable = new BABYLON.Observable();
  59627. /**
  59628. * An event triggered when the highlight layer changes its size.
  59629. * @type {BABYLON.Observable}
  59630. */
  59631. this.onSizeChangedObservable = new BABYLON.Observable();
  59632. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59633. var engine = scene.getEngine();
  59634. this._engine = engine;
  59635. this._maxSize = this._engine.getCaps().maxTextureSize;
  59636. this._scene.highlightLayers.push(this);
  59637. // Warn on stencil.
  59638. if (!this._engine.isStencilEnable) {
  59639. 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 }");
  59640. }
  59641. // Adapt options
  59642. this._options = options || {
  59643. mainTextureRatio: 0.25,
  59644. blurTextureSizeRatio: 0.5,
  59645. blurHorizontalSize: 1,
  59646. blurVerticalSize: 1,
  59647. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  59648. };
  59649. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  59650. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  59651. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  59652. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  59653. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  59654. // VBO
  59655. var vertices = [];
  59656. vertices.push(1, 1);
  59657. vertices.push(-1, 1);
  59658. vertices.push(-1, -1);
  59659. vertices.push(1, -1);
  59660. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  59661. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  59662. // Indices
  59663. var indices = [];
  59664. indices.push(0);
  59665. indices.push(1);
  59666. indices.push(2);
  59667. indices.push(0);
  59668. indices.push(2);
  59669. indices.push(3);
  59670. this._indexBuffer = engine.createIndexBuffer(indices);
  59671. // Effect
  59672. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  59673. // Render target
  59674. this.setMainTextureSize();
  59675. // Create Textures and post processes
  59676. this.createTextureAndPostProcesses();
  59677. }
  59678. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  59679. /**
  59680. * Gets the horizontal size of the blur.
  59681. */
  59682. get: function () {
  59683. return this._horizontalBlurPostprocess.blurWidth;
  59684. },
  59685. /**
  59686. * Specifies the horizontal size of the blur.
  59687. */
  59688. set: function (value) {
  59689. this._horizontalBlurPostprocess.blurWidth = value;
  59690. },
  59691. enumerable: true,
  59692. configurable: true
  59693. });
  59694. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  59695. /**
  59696. * Gets the vertical size of the blur.
  59697. */
  59698. get: function () {
  59699. return this._verticalBlurPostprocess.blurWidth;
  59700. },
  59701. /**
  59702. * Specifies the vertical size of the blur.
  59703. */
  59704. set: function (value) {
  59705. this._verticalBlurPostprocess.blurWidth = value;
  59706. },
  59707. enumerable: true,
  59708. configurable: true
  59709. });
  59710. Object.defineProperty(HighlightLayer.prototype, "camera", {
  59711. /**
  59712. * Gets the camera attached to the layer.
  59713. */
  59714. get: function () {
  59715. return this._options.camera;
  59716. },
  59717. enumerable: true,
  59718. configurable: true
  59719. });
  59720. /**
  59721. * Creates the render target textures and post processes used in the highlight layer.
  59722. */
  59723. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  59724. var _this = this;
  59725. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  59726. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  59727. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  59728. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  59729. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  59730. width: this._mainTextureDesiredSize.width,
  59731. height: this._mainTextureDesiredSize.height
  59732. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59733. this._mainTexture.activeCamera = this._options.camera;
  59734. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59735. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59736. this._mainTexture.anisotropicFilteringLevel = 1;
  59737. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59738. this._mainTexture.renderParticles = false;
  59739. this._mainTexture.renderList = null;
  59740. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  59741. width: blurTextureWidth,
  59742. height: blurTextureHeight
  59743. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59744. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59745. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59746. this._blurTexture.anisotropicFilteringLevel = 16;
  59747. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59748. this._blurTexture.renderParticles = false;
  59749. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  59750. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  59751. effect.setTexture("textureSampler", _this._mainTexture);
  59752. });
  59753. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  59754. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  59755. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  59756. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  59757. });
  59758. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  59759. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  59760. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  59761. });
  59762. }
  59763. else {
  59764. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  59765. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  59766. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  59767. });
  59768. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  59769. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  59770. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  59771. });
  59772. }
  59773. this._mainTexture.onAfterUnbindObservable.add(function () {
  59774. _this.onBeforeBlurObservable.notifyObservers(_this);
  59775. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  59776. _this.onAfterBlurObservable.notifyObservers(_this);
  59777. });
  59778. // Custom render function
  59779. var renderSubMesh = function (subMesh) {
  59780. var mesh = subMesh.getRenderingMesh();
  59781. var scene = _this._scene;
  59782. var engine = scene.getEngine();
  59783. // Culling
  59784. engine.setState(subMesh.getMaterial().backFaceCulling);
  59785. // Managing instances
  59786. var batch = mesh._getInstancesRenderList(subMesh._id);
  59787. if (batch.mustReturn) {
  59788. return;
  59789. }
  59790. // Excluded Mesh
  59791. if (_this._excludedMeshes[mesh.uniqueId]) {
  59792. return;
  59793. }
  59794. ;
  59795. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  59796. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  59797. var material = subMesh.getMaterial();
  59798. var emissiveTexture = null;
  59799. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  59800. emissiveTexture = material.emissiveTexture;
  59801. }
  59802. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  59803. engine.enableEffect(_this._glowMapGenerationEffect);
  59804. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  59805. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  59806. if (highlightLayerMesh) {
  59807. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  59808. }
  59809. else {
  59810. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  59811. }
  59812. // Alpha test
  59813. if (material && material.needAlphaTesting()) {
  59814. var alphaTexture = material.getAlphaTestTexture();
  59815. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  59816. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59817. }
  59818. // Glow emissive only
  59819. if (emissiveTexture) {
  59820. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  59821. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  59822. }
  59823. // Bones
  59824. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59825. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59826. }
  59827. // Draw
  59828. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  59829. }
  59830. else {
  59831. // Need to reset refresh rate of the shadowMap
  59832. _this._mainTexture.resetRefreshCounter();
  59833. }
  59834. };
  59835. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  59836. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  59837. var index;
  59838. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59839. renderSubMesh(opaqueSubMeshes.data[index]);
  59840. }
  59841. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59842. renderSubMesh(alphaTestSubMeshes.data[index]);
  59843. }
  59844. for (index = 0; index < transparentSubMeshes.length; index++) {
  59845. renderSubMesh(transparentSubMeshes.data[index]);
  59846. }
  59847. };
  59848. this._mainTexture.onClearObservable.add(function (engine) {
  59849. engine.clear(HighlightLayer.neutralColor, true, true, true);
  59850. });
  59851. };
  59852. /**
  59853. * Checks for the readiness of the element composing the layer.
  59854. * @param subMesh the mesh to check for
  59855. * @param useInstances specify wether or not to use instances to render the mesh
  59856. * @param emissiveTexture the associated emissive texture used to generate the glow
  59857. * @return true if ready otherwise, false
  59858. */
  59859. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  59860. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  59861. return false;
  59862. }
  59863. var defines = [];
  59864. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59865. var mesh = subMesh.getMesh();
  59866. var material = subMesh.getMaterial();
  59867. var uv1 = false;
  59868. var uv2 = false;
  59869. // Alpha test
  59870. if (material && material.needAlphaTesting()) {
  59871. var alphaTexture = material.getAlphaTestTexture();
  59872. if (alphaTexture) {
  59873. defines.push("#define ALPHATEST");
  59874. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  59875. alphaTexture.coordinatesIndex === 1) {
  59876. defines.push("#define DIFFUSEUV2");
  59877. uv2 = true;
  59878. }
  59879. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59880. defines.push("#define DIFFUSEUV1");
  59881. uv1 = true;
  59882. }
  59883. }
  59884. }
  59885. // Emissive
  59886. if (emissiveTexture) {
  59887. defines.push("#define EMISSIVE");
  59888. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  59889. emissiveTexture.coordinatesIndex === 1) {
  59890. defines.push("#define EMISSIVEUV2");
  59891. uv2 = true;
  59892. }
  59893. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59894. defines.push("#define EMISSIVEUV1");
  59895. uv1 = true;
  59896. }
  59897. }
  59898. if (uv1) {
  59899. attribs.push(BABYLON.VertexBuffer.UVKind);
  59900. defines.push("#define UV1");
  59901. }
  59902. if (uv2) {
  59903. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59904. defines.push("#define UV2");
  59905. }
  59906. // Bones
  59907. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59908. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59909. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59910. if (mesh.numBoneInfluencers > 4) {
  59911. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59912. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59913. }
  59914. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59915. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59916. }
  59917. else {
  59918. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59919. }
  59920. // Instances
  59921. if (useInstances) {
  59922. defines.push("#define INSTANCES");
  59923. attribs.push("world0");
  59924. attribs.push("world1");
  59925. attribs.push("world2");
  59926. attribs.push("world3");
  59927. }
  59928. // Get correct effect
  59929. var join = defines.join("\n");
  59930. if (this._cachedDefines !== join) {
  59931. this._cachedDefines = join;
  59932. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  59933. }
  59934. return this._glowMapGenerationEffect.isReady();
  59935. };
  59936. /**
  59937. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  59938. */
  59939. HighlightLayer.prototype.render = function () {
  59940. var currentEffect = this._glowMapMergeEffect;
  59941. // Check
  59942. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  59943. return;
  59944. var engine = this._scene.getEngine();
  59945. this.onBeforeComposeObservable.notifyObservers(this);
  59946. // Render
  59947. engine.enableEffect(currentEffect);
  59948. engine.setState(false);
  59949. // Cache
  59950. var previousStencilBuffer = engine.getStencilBuffer();
  59951. var previousStencilFunction = engine.getStencilFunction();
  59952. var previousStencilMask = engine.getStencilMask();
  59953. var previousAlphaMode = engine.getAlphaMode();
  59954. // Texture
  59955. currentEffect.setTexture("textureSampler", this._blurTexture);
  59956. // VBOs
  59957. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  59958. // Draw order
  59959. engine.setAlphaMode(this._options.alphaBlendingMode);
  59960. engine.setStencilMask(0x00);
  59961. engine.setStencilBuffer(true);
  59962. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  59963. if (this.outerGlow) {
  59964. currentEffect.setFloat("offset", 0);
  59965. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  59966. engine.draw(true, 0, 6);
  59967. }
  59968. if (this.innerGlow) {
  59969. currentEffect.setFloat("offset", 1);
  59970. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  59971. engine.draw(true, 0, 6);
  59972. }
  59973. // Restore Cache
  59974. engine.setStencilFunction(previousStencilFunction);
  59975. engine.setStencilMask(previousStencilMask);
  59976. engine.setAlphaMode(previousAlphaMode);
  59977. engine.setStencilBuffer(previousStencilBuffer);
  59978. this.onAfterComposeObservable.notifyObservers(this);
  59979. // Handle size changes.
  59980. var size = this._mainTexture.getSize();
  59981. this.setMainTextureSize();
  59982. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  59983. // Recreate RTT and post processes on size change.
  59984. this.onSizeChangedObservable.notifyObservers(this);
  59985. this.disposeTextureAndPostProcesses();
  59986. this.createTextureAndPostProcesses();
  59987. }
  59988. };
  59989. /**
  59990. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  59991. * @param mesh The mesh to exclude from the highlight layer
  59992. */
  59993. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  59994. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  59995. if (!meshExcluded) {
  59996. this._excludedMeshes[mesh.uniqueId] = {
  59997. mesh: mesh,
  59998. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  59999. mesh.getEngine().setStencilBuffer(false);
  60000. }),
  60001. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  60002. mesh.getEngine().setStencilBuffer(true);
  60003. }),
  60004. };
  60005. }
  60006. };
  60007. /**
  60008. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  60009. * @param mesh The mesh to highlight
  60010. */
  60011. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  60012. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  60013. if (meshExcluded) {
  60014. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  60015. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  60016. }
  60017. this._excludedMeshes[mesh.uniqueId] = undefined;
  60018. };
  60019. /**
  60020. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  60021. * @param mesh The mesh to highlight
  60022. * @param color The color of the highlight
  60023. * @param glowEmissiveOnly Extract the glow from the emissive texture
  60024. */
  60025. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  60026. var _this = this;
  60027. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  60028. var meshHighlight = this._meshes[mesh.uniqueId];
  60029. if (meshHighlight) {
  60030. meshHighlight.color = color;
  60031. }
  60032. else {
  60033. this._meshes[mesh.uniqueId] = {
  60034. mesh: mesh,
  60035. color: color,
  60036. // Lambda required for capture due to Observable this context
  60037. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  60038. if (_this._excludedMeshes[mesh.uniqueId]) {
  60039. _this.defaultStencilReference(mesh);
  60040. }
  60041. else {
  60042. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  60043. }
  60044. }),
  60045. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  60046. glowEmissiveOnly: glowEmissiveOnly
  60047. };
  60048. }
  60049. this._shouldRender = true;
  60050. };
  60051. /**
  60052. * Remove a mesh from the highlight layer in order to make it stop glowing.
  60053. * @param mesh The mesh to highlight
  60054. */
  60055. HighlightLayer.prototype.removeMesh = function (mesh) {
  60056. var meshHighlight = this._meshes[mesh.uniqueId];
  60057. if (meshHighlight) {
  60058. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  60059. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  60060. }
  60061. this._meshes[mesh.uniqueId] = undefined;
  60062. this._shouldRender = false;
  60063. for (var meshHighlightToCheck in this._meshes) {
  60064. if (meshHighlightToCheck) {
  60065. this._shouldRender = true;
  60066. break;
  60067. }
  60068. }
  60069. };
  60070. /**
  60071. * Returns true if the layer contains information to display, otherwise false.
  60072. */
  60073. HighlightLayer.prototype.shouldRender = function () {
  60074. return this.isEnabled && this._shouldRender;
  60075. };
  60076. /**
  60077. * Sets the main texture desired size which is the closest power of two
  60078. * of the engine canvas size.
  60079. */
  60080. HighlightLayer.prototype.setMainTextureSize = function () {
  60081. if (this._options.mainTextureFixedSize) {
  60082. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  60083. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  60084. }
  60085. else {
  60086. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  60087. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  60088. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  60089. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  60090. }
  60091. };
  60092. /**
  60093. * Force the stencil to the normal expected value for none glowing parts
  60094. */
  60095. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  60096. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  60097. };
  60098. /**
  60099. * Dispose only the render target textures and post process.
  60100. */
  60101. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  60102. this._blurTexture.dispose();
  60103. this._mainTexture.dispose();
  60104. this._downSamplePostprocess.dispose();
  60105. this._horizontalBlurPostprocess.dispose();
  60106. this._verticalBlurPostprocess.dispose();
  60107. };
  60108. /**
  60109. * Dispose the highlight layer and free resources.
  60110. */
  60111. HighlightLayer.prototype.dispose = function () {
  60112. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60113. if (vertexBuffer) {
  60114. vertexBuffer.dispose();
  60115. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60116. }
  60117. if (this._indexBuffer) {
  60118. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  60119. this._indexBuffer = null;
  60120. }
  60121. // Clean textures and post processes
  60122. this.disposeTextureAndPostProcesses();
  60123. // Clean mesh references
  60124. for (var id in this._meshes) {
  60125. var meshHighlight = this._meshes[id];
  60126. if (meshHighlight && meshHighlight.mesh) {
  60127. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  60128. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  60129. }
  60130. }
  60131. this._meshes = null;
  60132. for (var id in this._excludedMeshes) {
  60133. var meshHighlight = this._excludedMeshes[id];
  60134. if (meshHighlight) {
  60135. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  60136. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  60137. }
  60138. }
  60139. this._excludedMeshes = null;
  60140. // Remove from scene
  60141. var index = this._scene.highlightLayers.indexOf(this, 0);
  60142. if (index > -1) {
  60143. this._scene.highlightLayers.splice(index, 1);
  60144. }
  60145. // Callback
  60146. this.onDisposeObservable.notifyObservers(this);
  60147. this.onDisposeObservable.clear();
  60148. this.onBeforeRenderMainTextureObservable.clear();
  60149. this.onBeforeBlurObservable.clear();
  60150. this.onBeforeComposeObservable.clear();
  60151. this.onAfterComposeObservable.clear();
  60152. this.onSizeChangedObservable.clear();
  60153. };
  60154. return HighlightLayer;
  60155. }());
  60156. /**
  60157. * The neutral color used during the preparation of the glow effect.
  60158. * This is black by default as the blend operation is a blend operation.
  60159. */
  60160. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  60161. /**
  60162. * Stencil value used for glowing meshes.
  60163. */
  60164. HighlightLayer.glowingMeshStencilReference = 0x02;
  60165. /**
  60166. * Stencil value used for the other meshes in the scene.
  60167. */
  60168. HighlightLayer.normalMeshStencilReference = 0x01;
  60169. BABYLON.HighlightLayer = HighlightLayer;
  60170. })(BABYLON || (BABYLON = {}));
  60171. //# sourceMappingURL=babylon.highlightlayer.js.map
  60172. var BABYLON;
  60173. (function (BABYLON) {
  60174. var MeshAssetTask = (function () {
  60175. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  60176. this.name = name;
  60177. this.meshesNames = meshesNames;
  60178. this.rootUrl = rootUrl;
  60179. this.sceneFilename = sceneFilename;
  60180. this.isCompleted = false;
  60181. }
  60182. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  60183. var _this = this;
  60184. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60185. _this.loadedMeshes = meshes;
  60186. _this.loadedParticleSystems = particleSystems;
  60187. _this.loadedSkeletons = skeletons;
  60188. _this.isCompleted = true;
  60189. if (_this.onSuccess) {
  60190. _this.onSuccess(_this);
  60191. }
  60192. onSuccess();
  60193. }, null, function () {
  60194. if (_this.onError) {
  60195. _this.onError(_this);
  60196. }
  60197. onError();
  60198. });
  60199. };
  60200. return MeshAssetTask;
  60201. }());
  60202. BABYLON.MeshAssetTask = MeshAssetTask;
  60203. var TextFileAssetTask = (function () {
  60204. function TextFileAssetTask(name, url) {
  60205. this.name = name;
  60206. this.url = url;
  60207. this.isCompleted = false;
  60208. }
  60209. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  60210. var _this = this;
  60211. BABYLON.Tools.LoadFile(this.url, function (data) {
  60212. _this.text = data;
  60213. _this.isCompleted = true;
  60214. if (_this.onSuccess) {
  60215. _this.onSuccess(_this);
  60216. }
  60217. onSuccess();
  60218. }, null, scene.database, false, function () {
  60219. if (_this.onError) {
  60220. _this.onError(_this);
  60221. }
  60222. onError();
  60223. });
  60224. };
  60225. return TextFileAssetTask;
  60226. }());
  60227. BABYLON.TextFileAssetTask = TextFileAssetTask;
  60228. var BinaryFileAssetTask = (function () {
  60229. function BinaryFileAssetTask(name, url) {
  60230. this.name = name;
  60231. this.url = url;
  60232. this.isCompleted = false;
  60233. }
  60234. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  60235. var _this = this;
  60236. BABYLON.Tools.LoadFile(this.url, function (data) {
  60237. _this.data = data;
  60238. _this.isCompleted = true;
  60239. if (_this.onSuccess) {
  60240. _this.onSuccess(_this);
  60241. }
  60242. onSuccess();
  60243. }, null, scene.database, true, function () {
  60244. if (_this.onError) {
  60245. _this.onError(_this);
  60246. }
  60247. onError();
  60248. });
  60249. };
  60250. return BinaryFileAssetTask;
  60251. }());
  60252. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  60253. var ImageAssetTask = (function () {
  60254. function ImageAssetTask(name, url) {
  60255. this.name = name;
  60256. this.url = url;
  60257. this.isCompleted = false;
  60258. }
  60259. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  60260. var _this = this;
  60261. var img = new Image();
  60262. BABYLON.Tools.SetCorsBehavior(this.url, img);
  60263. img.onload = function () {
  60264. _this.image = img;
  60265. _this.isCompleted = true;
  60266. if (_this.onSuccess) {
  60267. _this.onSuccess(_this);
  60268. }
  60269. onSuccess();
  60270. };
  60271. img.onerror = function () {
  60272. if (_this.onError) {
  60273. _this.onError(_this);
  60274. }
  60275. onError();
  60276. };
  60277. img.src = this.url;
  60278. };
  60279. return ImageAssetTask;
  60280. }());
  60281. BABYLON.ImageAssetTask = ImageAssetTask;
  60282. var TextureAssetTask = (function () {
  60283. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  60284. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60285. this.name = name;
  60286. this.url = url;
  60287. this.noMipmap = noMipmap;
  60288. this.invertY = invertY;
  60289. this.samplingMode = samplingMode;
  60290. this.isCompleted = false;
  60291. }
  60292. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  60293. var _this = this;
  60294. var onload = function () {
  60295. _this.isCompleted = true;
  60296. if (_this.onSuccess) {
  60297. _this.onSuccess(_this);
  60298. }
  60299. onSuccess();
  60300. };
  60301. var onerror = function () {
  60302. if (_this.onError) {
  60303. _this.onError(_this);
  60304. }
  60305. onError();
  60306. };
  60307. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  60308. };
  60309. return TextureAssetTask;
  60310. }());
  60311. BABYLON.TextureAssetTask = TextureAssetTask;
  60312. var CubeTextureAssetTask = (function () {
  60313. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  60314. this.name = name;
  60315. this.url = url;
  60316. this.extensions = extensions;
  60317. this.noMipmap = noMipmap;
  60318. this.files = files;
  60319. this.isCompleted = false;
  60320. }
  60321. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  60322. var _this = this;
  60323. var onload = function () {
  60324. _this.isCompleted = true;
  60325. if (_this.onSuccess) {
  60326. _this.onSuccess(_this);
  60327. }
  60328. onSuccess();
  60329. };
  60330. var onerror = function () {
  60331. if (_this.onError) {
  60332. _this.onError(_this);
  60333. }
  60334. onError();
  60335. };
  60336. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  60337. };
  60338. return CubeTextureAssetTask;
  60339. }());
  60340. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  60341. var HDRCubeTextureAssetTask = (function () {
  60342. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  60343. if (noMipmap === void 0) { noMipmap = false; }
  60344. if (generateHarmonics === void 0) { generateHarmonics = true; }
  60345. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  60346. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  60347. this.name = name;
  60348. this.url = url;
  60349. this.size = size;
  60350. this.noMipmap = noMipmap;
  60351. this.generateHarmonics = generateHarmonics;
  60352. this.useInGammaSpace = useInGammaSpace;
  60353. this.usePMREMGenerator = usePMREMGenerator;
  60354. this.isCompleted = false;
  60355. }
  60356. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  60357. var _this = this;
  60358. var onload = function () {
  60359. _this.isCompleted = true;
  60360. if (_this.onSuccess) {
  60361. _this.onSuccess(_this);
  60362. }
  60363. onSuccess();
  60364. };
  60365. var onerror = function () {
  60366. if (_this.onError) {
  60367. _this.onError(_this);
  60368. }
  60369. onError();
  60370. };
  60371. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  60372. };
  60373. return HDRCubeTextureAssetTask;
  60374. }());
  60375. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  60376. var AssetsManager = (function () {
  60377. function AssetsManager(scene) {
  60378. this.tasks = new Array();
  60379. this.waitingTasksCount = 0;
  60380. this.useDefaultLoadingScreen = true;
  60381. this._scene = scene;
  60382. }
  60383. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  60384. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  60385. this.tasks.push(task);
  60386. return task;
  60387. };
  60388. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  60389. var task = new TextFileAssetTask(taskName, url);
  60390. this.tasks.push(task);
  60391. return task;
  60392. };
  60393. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  60394. var task = new BinaryFileAssetTask(taskName, url);
  60395. this.tasks.push(task);
  60396. return task;
  60397. };
  60398. AssetsManager.prototype.addImageTask = function (taskName, url) {
  60399. var task = new ImageAssetTask(taskName, url);
  60400. this.tasks.push(task);
  60401. return task;
  60402. };
  60403. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  60404. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60405. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  60406. this.tasks.push(task);
  60407. return task;
  60408. };
  60409. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  60410. this.waitingTasksCount--;
  60411. if (this.waitingTasksCount === 0) {
  60412. if (this.onFinish) {
  60413. this.onFinish(this.tasks);
  60414. }
  60415. this._scene.getEngine().hideLoadingUI();
  60416. }
  60417. };
  60418. AssetsManager.prototype._runTask = function (task) {
  60419. var _this = this;
  60420. task.run(this._scene, function () {
  60421. if (_this.onTaskSuccess) {
  60422. _this.onTaskSuccess(task);
  60423. }
  60424. _this._decreaseWaitingTasksCount();
  60425. }, function () {
  60426. if (_this.onTaskError) {
  60427. _this.onTaskError(task);
  60428. }
  60429. _this._decreaseWaitingTasksCount();
  60430. });
  60431. };
  60432. AssetsManager.prototype.reset = function () {
  60433. this.tasks = new Array();
  60434. return this;
  60435. };
  60436. AssetsManager.prototype.load = function () {
  60437. this.waitingTasksCount = this.tasks.length;
  60438. if (this.waitingTasksCount === 0) {
  60439. if (this.onFinish) {
  60440. this.onFinish(this.tasks);
  60441. }
  60442. return this;
  60443. }
  60444. if (this.useDefaultLoadingScreen) {
  60445. this._scene.getEngine().displayLoadingUI();
  60446. }
  60447. for (var index = 0; index < this.tasks.length; index++) {
  60448. var task = this.tasks[index];
  60449. this._runTask(task);
  60450. }
  60451. return this;
  60452. };
  60453. return AssetsManager;
  60454. }());
  60455. BABYLON.AssetsManager = AssetsManager;
  60456. })(BABYLON || (BABYLON = {}));
  60457. //# sourceMappingURL=babylon.assetsManager.js.map
  60458. var BABYLON;
  60459. (function (BABYLON) {
  60460. var MapTexture = (function (_super) {
  60461. __extends(MapTexture, _super);
  60462. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  60463. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60464. if (useMipMap === void 0) { useMipMap = false; }
  60465. if (margin === void 0) { margin = 0; }
  60466. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  60467. _this.name = name;
  60468. _this._size = size;
  60469. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60470. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60471. // Create the rectPackMap that will allocate portion of the texture
  60472. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  60473. // Create the texture that will store the content
  60474. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  60475. return _this;
  60476. }
  60477. /**
  60478. * Allocate a rectangle of a given size in the texture map
  60479. * @param size the size of the rectangle to allocation
  60480. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  60481. */
  60482. MapTexture.prototype.allocateRect = function (size) {
  60483. return this._rectPackingMap.addRect(size);
  60484. };
  60485. /**
  60486. * Free a given rectangle from the texture map
  60487. * @param rectInfo the instance corresponding to the rect to free.
  60488. */
  60489. MapTexture.prototype.freeRect = function (rectInfo) {
  60490. if (rectInfo) {
  60491. rectInfo.freeContent();
  60492. }
  60493. };
  60494. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  60495. /**
  60496. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  60497. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  60498. * @returns {}
  60499. */
  60500. get: function () {
  60501. return this._rectPackingMap.freeSpace;
  60502. },
  60503. enumerable: true,
  60504. configurable: true
  60505. });
  60506. /**
  60507. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  60508. * 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.
  60509. * Don't forget to call unbindTexture when you're done rendering
  60510. * @param rect the zone to render to
  60511. * @param clear true to clear the portion's color/depth data
  60512. */
  60513. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  60514. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  60515. };
  60516. /**
  60517. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  60518. * 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.
  60519. * Don't forget to call unbindTexture when you're done rendering
  60520. * @param pos the position into the texture
  60521. * @param size the portion to fit the clip space to
  60522. * @param clear true to clear the portion's color/depth data
  60523. */
  60524. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  60525. var engine = this.getScene().getEngine();
  60526. engine.bindFramebuffer(this._texture);
  60527. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  60528. if (clear) {
  60529. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  60530. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  60531. }
  60532. };
  60533. /**
  60534. * Unbind the texture map from the rendering engine.
  60535. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  60536. * @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.
  60537. */
  60538. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  60539. // Dump ?
  60540. if (dumpForDebug) {
  60541. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  60542. }
  60543. var engine = this.getScene().getEngine();
  60544. if (this._replacedViewport) {
  60545. engine.setViewport(this._replacedViewport);
  60546. this._replacedViewport = null;
  60547. }
  60548. engine.unBindFramebuffer(this._texture);
  60549. };
  60550. Object.defineProperty(MapTexture.prototype, "canRescale", {
  60551. get: function () {
  60552. return false;
  60553. },
  60554. enumerable: true,
  60555. configurable: true
  60556. });
  60557. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  60558. // Anyway, there's not much point to use this method for this kind of texture I guess
  60559. MapTexture.prototype.clone = function () {
  60560. return null;
  60561. };
  60562. return MapTexture;
  60563. }(BABYLON.Texture));
  60564. BABYLON.MapTexture = MapTexture;
  60565. })(BABYLON || (BABYLON = {}));
  60566. //# sourceMappingURL=babylon.mapTexture.js.map
  60567. var BABYLON;
  60568. (function (BABYLON) {
  60569. /**
  60570. * This class describe a rectangle that were added to the map.
  60571. * You have access to its coordinates either in pixel or normalized (UV)
  60572. */
  60573. var PackedRect = (function () {
  60574. function PackedRect(root, parent, pos, size) {
  60575. this._pos = pos;
  60576. this._size = size;
  60577. this._root = root;
  60578. this._parent = parent;
  60579. this._contentSize = null;
  60580. this._bottomNode = null;
  60581. this._leftNode = null;
  60582. this._initialSize = null;
  60583. this._rightNode = null;
  60584. }
  60585. Object.defineProperty(PackedRect.prototype, "pos", {
  60586. /**
  60587. * @returns the position of this node into the map
  60588. */
  60589. get: function () {
  60590. return this._pos;
  60591. },
  60592. enumerable: true,
  60593. configurable: true
  60594. });
  60595. Object.defineProperty(PackedRect.prototype, "contentSize", {
  60596. /**
  60597. * @returns the size of the rectangle this node handles
  60598. */
  60599. get: function () {
  60600. return this._contentSize;
  60601. },
  60602. enumerable: true,
  60603. configurable: true
  60604. });
  60605. /**
  60606. * Retrieve the inner position (considering the margin) and stores it into the res object
  60607. * @param res must be a valid Vector2 that will contain the inner position after this call
  60608. */
  60609. PackedRect.prototype.getInnerPosToRef = function (res) {
  60610. var m = this._root._margin;
  60611. res.x = this._pos.x + m;
  60612. res.y = this._pos.y + m;
  60613. };
  60614. /**
  60615. * Retrieve the inner size (considering the margin) and stores it into the res object
  60616. * @param res must be a valid Size that will contain the inner size after this call
  60617. */
  60618. PackedRect.prototype.getInnerSizeToRef = function (res) {
  60619. var m = this._root._margin;
  60620. res.width = this._contentSize.width - (m * 2);
  60621. res.height = this._contentSize.height - (m * 2);
  60622. };
  60623. Object.defineProperty(PackedRect.prototype, "UVs", {
  60624. /**
  60625. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  60626. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  60627. */
  60628. get: function () {
  60629. if (!this._contentSize) {
  60630. throw new Error("Can't compute UVs for this object because it's nor allocated");
  60631. }
  60632. return this.getUVsForCustomSize(this._contentSize);
  60633. },
  60634. enumerable: true,
  60635. configurable: true
  60636. });
  60637. /**
  60638. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  60639. * and then using only a part of the PackRect.
  60640. * This method will return the UVs for this part by given the custom size of what you really use
  60641. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  60642. */
  60643. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  60644. var mainWidth = this._root._size.width;
  60645. var mainHeight = this._root._size.height;
  60646. var margin = this._root._margin;
  60647. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  60648. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  60649. var uvs = new Array();
  60650. uvs.push(topLeft);
  60651. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  60652. uvs.push(rightBottom);
  60653. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  60654. return uvs;
  60655. };
  60656. /**
  60657. * Free this rectangle from the map.
  60658. * Call this method when you no longer need the rectangle to be in the map.
  60659. */
  60660. PackedRect.prototype.freeContent = function () {
  60661. if (!this.contentSize) {
  60662. return;
  60663. }
  60664. this._contentSize = null;
  60665. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  60666. this.attemptDefrag();
  60667. };
  60668. Object.defineProperty(PackedRect.prototype, "isUsed", {
  60669. get: function () {
  60670. return this._contentSize != null || this._leftNode != null;
  60671. },
  60672. enumerable: true,
  60673. configurable: true
  60674. });
  60675. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  60676. var node = this.findNode(contentSize);
  60677. // Not enough space...
  60678. if (!node) {
  60679. return null;
  60680. }
  60681. node.splitNode(contentSize);
  60682. return node;
  60683. };
  60684. PackedRect.prototype.findNode = function (size) {
  60685. var resNode = null;
  60686. var margin = this._root._margin * 2;
  60687. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  60688. if (this.isUsed) {
  60689. if (this._leftNode) {
  60690. resNode = this._leftNode.findNode(size);
  60691. }
  60692. if (!resNode && this._rightNode) {
  60693. resNode = this._rightNode.findNode(size);
  60694. }
  60695. if (!resNode && this._bottomNode) {
  60696. resNode = this._bottomNode.findNode(size);
  60697. }
  60698. }
  60699. else if (this._initialSize) {
  60700. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  60701. resNode = this;
  60702. }
  60703. else {
  60704. return null;
  60705. }
  60706. }
  60707. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  60708. resNode = this;
  60709. }
  60710. return resNode;
  60711. };
  60712. PackedRect.prototype.splitNode = function (contentSize) {
  60713. var cs = PackedRect.TpsSize;
  60714. var margin = this._root._margin * 2;
  60715. cs.copyFrom(contentSize);
  60716. cs.width += margin;
  60717. cs.height += margin;
  60718. // 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)
  60719. if (!this._contentSize && this._initialSize) {
  60720. this._contentSize = cs.clone();
  60721. 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));
  60722. return this._leftNode.splitNode(contentSize);
  60723. }
  60724. else {
  60725. this._contentSize = cs.clone();
  60726. this._initialSize = cs.clone();
  60727. if (cs.width !== this._size.width) {
  60728. 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));
  60729. }
  60730. if (cs.height !== this._size.height) {
  60731. 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));
  60732. }
  60733. return this;
  60734. }
  60735. };
  60736. PackedRect.prototype.attemptDefrag = function () {
  60737. if (!this.isUsed && this.isRecursiveFree) {
  60738. this.clearNode();
  60739. if (this._parent) {
  60740. this._parent.attemptDefrag();
  60741. }
  60742. }
  60743. };
  60744. PackedRect.prototype.clearNode = function () {
  60745. this._initialSize = null;
  60746. this._rightNode = null;
  60747. this._bottomNode = null;
  60748. };
  60749. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  60750. get: function () {
  60751. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  60752. },
  60753. enumerable: true,
  60754. configurable: true
  60755. });
  60756. PackedRect.prototype.evalFreeSize = function (size) {
  60757. var levelSize = 0;
  60758. if (!this.isUsed) {
  60759. var margin = this._root._margin;
  60760. var is = this._initialSize;
  60761. if (is) {
  60762. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  60763. }
  60764. else {
  60765. var size_1 = this._size;
  60766. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  60767. }
  60768. }
  60769. if (this._rightNode) {
  60770. levelSize += this._rightNode.evalFreeSize(0);
  60771. }
  60772. if (this._bottomNode) {
  60773. levelSize += this._bottomNode.evalFreeSize(0);
  60774. }
  60775. return levelSize + size;
  60776. };
  60777. return PackedRect;
  60778. }());
  60779. PackedRect.TpsSize = BABYLON.Size.Zero();
  60780. BABYLON.PackedRect = PackedRect;
  60781. /**
  60782. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  60783. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  60784. * 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.
  60785. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  60786. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  60787. */
  60788. var RectPackingMap = (function (_super) {
  60789. __extends(RectPackingMap, _super);
  60790. /**
  60791. * Create an instance of the object with a dimension using the given size
  60792. * @param size The dimension of the rectangle that will contain all the sub ones.
  60793. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  60794. */
  60795. function RectPackingMap(size, margin) {
  60796. if (margin === void 0) { margin = 0; }
  60797. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  60798. _this._margin = margin;
  60799. _this._root = _this;
  60800. return _this;
  60801. }
  60802. /**
  60803. * Add a rectangle, finding the best location to store it into the map
  60804. * @param size the dimension of the rectangle to store
  60805. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  60806. */
  60807. RectPackingMap.prototype.addRect = function (size) {
  60808. var node = this.findAndSplitNode(size);
  60809. return node;
  60810. };
  60811. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  60812. /**
  60813. * Return the current space free normalized between [0;1]
  60814. * @returns {}
  60815. */
  60816. get: function () {
  60817. var freeSize = 0;
  60818. freeSize = this.evalFreeSize(freeSize);
  60819. return freeSize / (this._size.width * this._size.height);
  60820. },
  60821. enumerable: true,
  60822. configurable: true
  60823. });
  60824. return RectPackingMap;
  60825. }(PackedRect));
  60826. BABYLON.RectPackingMap = RectPackingMap;
  60827. })(BABYLON || (BABYLON = {}));
  60828. //# sourceMappingURL=babylon.rectPackingMap.js.map
  60829. var BABYLON;
  60830. (function (BABYLON) {
  60831. var DynamicFloatArrayElementInfo = (function () {
  60832. function DynamicFloatArrayElementInfo() {
  60833. }
  60834. return DynamicFloatArrayElementInfo;
  60835. }());
  60836. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  60837. /**
  60838. * 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.
  60839. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  60840. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  60841. * 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.
  60842. * 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.
  60843. * 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".
  60844. */
  60845. var DynamicFloatArray = (function () {
  60846. /**
  60847. * Construct an instance of the dynamic float array
  60848. * @param stride size of one element in float (i.e. not bytes!)
  60849. * @param initialElementCount the number of available entries at construction
  60850. */
  60851. function DynamicFloatArray(stride, initialElementCount) {
  60852. this.compareValueOffset = null;
  60853. this.sortingAscending = true;
  60854. this._stride = stride;
  60855. this.buffer = new Float32Array(stride * initialElementCount);
  60856. this._lastUsed = 0;
  60857. this._firstFree = 0;
  60858. this._allEntries = new Array(initialElementCount);
  60859. this._freeEntries = new Array(initialElementCount);
  60860. for (var i = 0; i < initialElementCount; i++) {
  60861. var element = new DynamicFloatArrayElementInfo();
  60862. element.offset = i * stride;
  60863. this._allEntries[i] = element;
  60864. this._freeEntries[initialElementCount - i - 1] = element;
  60865. }
  60866. }
  60867. /**
  60868. * Allocate an element in the array.
  60869. * @return the element info instance that contains the offset into the main buffer of the element's location.
  60870. * Beware, this offset may change when you call pack()
  60871. */
  60872. DynamicFloatArray.prototype.allocElement = function () {
  60873. if (this._freeEntries.length === 0) {
  60874. this._growBuffer();
  60875. }
  60876. var el = this._freeEntries.pop();
  60877. this._lastUsed = Math.max(el.offset, this._lastUsed);
  60878. if (el.offset === this._firstFree) {
  60879. if (this._freeEntries.length > 0) {
  60880. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  60881. }
  60882. else {
  60883. this._firstFree += this._stride;
  60884. }
  60885. }
  60886. return el;
  60887. };
  60888. /**
  60889. * Free the element corresponding to the given element info
  60890. * @param elInfo the element that describe the allocated element
  60891. */
  60892. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  60893. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  60894. this._freeEntries.push(elInfo);
  60895. };
  60896. /**
  60897. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  60898. * 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().
  60899. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  60900. */
  60901. DynamicFloatArray.prototype.pack = function () {
  60902. // no free slot? no need to pack
  60903. if (this._freeEntries.length === 0) {
  60904. return this.buffer;
  60905. }
  60906. // If the buffer is already packed the last used will always be lower than the first free
  60907. // 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.
  60908. if (this._lastUsed < this._firstFree) {
  60909. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  60910. return elementsBuffer_1;
  60911. }
  60912. var s = this._stride;
  60913. // 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
  60914. var lastFree = new DynamicFloatArrayElementInfo();
  60915. lastFree.offset = this.totalElementCount * s;
  60916. this._freeEntries.push(lastFree);
  60917. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  60918. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  60919. var firstFreeSlotOffset = sortedFree[0].offset;
  60920. var freeZoneSize = 1;
  60921. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  60922. var prevOffset = sortedFree[0].offset;
  60923. for (var i = 1; i < sortedFree.length; i++) {
  60924. // 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
  60925. if (firstFreeSlotOffset >= occupiedZoneSize) {
  60926. break;
  60927. }
  60928. var curFree = sortedFree[i];
  60929. var curOffset = curFree.offset;
  60930. // Compute the distance between this offset and the previous
  60931. var distance = curOffset - prevOffset;
  60932. // If the distance is the stride size, they are adjacent, it good, move to the next
  60933. if (distance === s) {
  60934. // Free zone is one element bigger
  60935. ++freeZoneSize;
  60936. // as we're about to iterate to the next, the cur becomes the previous...
  60937. prevOffset = curOffset;
  60938. continue;
  60939. }
  60940. // Distance is bigger, which means there's x element between the previous free and this one
  60941. var usedRange = (distance / s) - 1;
  60942. // Two cases the free zone is smaller than the data to move or bigger
  60943. // Copy what can fit in the free zone
  60944. var curMoveOffset = curOffset - s;
  60945. var copyCount = Math.min(freeZoneSize, usedRange);
  60946. for (var j = 0; j < copyCount; j++) {
  60947. var freeI = firstFreeSlotOffset / s;
  60948. var curI = curMoveOffset / s;
  60949. var moveEl = sortedAll[curI];
  60950. this._moveElement(moveEl, firstFreeSlotOffset);
  60951. var replacedEl = sortedAll[freeI];
  60952. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  60953. replacedEl.offset = curMoveOffset;
  60954. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  60955. sortedAll[freeI] = moveEl;
  60956. sortedAll[curI] = replacedEl;
  60957. curMoveOffset -= s;
  60958. firstFreeSlotOffset += s;
  60959. }
  60960. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  60961. if (freeZoneSize <= usedRange) {
  60962. firstFreeSlotOffset = curMoveOffset + s;
  60963. freeZoneSize = 1 + copyCount;
  60964. }
  60965. else {
  60966. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  60967. }
  60968. // as we're about to iterate to the next, the cur becomes the previous...
  60969. prevOffset = curOffset;
  60970. }
  60971. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  60972. this._lastUsed = firstFreeSlotOffset - s;
  60973. this._firstFree = firstFreeSlotOffset;
  60974. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  60975. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  60976. this._allEntries = sortedAll;
  60977. return elementsBuffer;
  60978. };
  60979. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  60980. for (var i = 0; i < this._stride; i++) {
  60981. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  60982. }
  60983. element.offset = destOffset;
  60984. };
  60985. DynamicFloatArray.prototype._growBuffer = function () {
  60986. // Allocate the new buffer with 50% more entries, copy the content of the current one
  60987. var newElCount = Math.floor(this.totalElementCount * 1.5);
  60988. var newBuffer = new Float32Array(newElCount * this._stride);
  60989. newBuffer.set(this.buffer);
  60990. var curCount = this.totalElementCount;
  60991. var addedCount = newElCount - this.totalElementCount;
  60992. for (var i = 0; i < addedCount; i++) {
  60993. var element = new DynamicFloatArrayElementInfo();
  60994. element.offset = (curCount + i) * this.stride;
  60995. this._allEntries.push(element);
  60996. this._freeEntries[addedCount - i - 1] = element;
  60997. }
  60998. this._firstFree = curCount * this.stride;
  60999. this.buffer = newBuffer;
  61000. };
  61001. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  61002. /**
  61003. * Get the total count of entries that can fit in the current buffer
  61004. * @returns the elements count
  61005. */
  61006. get: function () {
  61007. return this._allEntries.length;
  61008. },
  61009. enumerable: true,
  61010. configurable: true
  61011. });
  61012. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  61013. /**
  61014. * Get the count of free entries that can still be allocated without resizing the buffer
  61015. * @returns the free elements count
  61016. */
  61017. get: function () {
  61018. return this._freeEntries.length;
  61019. },
  61020. enumerable: true,
  61021. configurable: true
  61022. });
  61023. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  61024. /**
  61025. * Get the count of allocated elements
  61026. * @returns the allocated elements count
  61027. */
  61028. get: function () {
  61029. return this._allEntries.length - this._freeEntries.length;
  61030. },
  61031. enumerable: true,
  61032. configurable: true
  61033. });
  61034. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  61035. /**
  61036. * Return the size of one element in float
  61037. * @returns the size in float
  61038. */
  61039. get: function () {
  61040. return this._stride;
  61041. },
  61042. enumerable: true,
  61043. configurable: true
  61044. });
  61045. DynamicFloatArray.prototype.sort = function () {
  61046. var _this = this;
  61047. if (!this.compareValueOffset) {
  61048. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  61049. }
  61050. var count = this.usedElementCount;
  61051. // Do we have to (re)create the sort table?
  61052. if (!this._sortTable || this._sortTable.length < count) {
  61053. // 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...
  61054. var newCount = Math.min(this.totalElementCount, count * 2);
  61055. this._sortTable = new Array(newCount);
  61056. }
  61057. if (!this._sortedTable || this._sortedTable.length !== count) {
  61058. this._sortedTable = new Array(count);
  61059. }
  61060. // Because, you know...
  61061. this.pack();
  61062. //let stride = this.stride;
  61063. //for (let i = 0; i < count; i++) {
  61064. // let si = this._sortTable[i];
  61065. // if (!si) {
  61066. // si = new SortInfo();
  61067. // this._sortTable[i] = si;
  61068. // }
  61069. // si.entry = this._allEntries[i];
  61070. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  61071. // si.swapedOffset = null;
  61072. // this._sortedTable[i] = si;
  61073. //}
  61074. var curOffset = 0;
  61075. var stride = this.stride;
  61076. for (var i = 0; i < count; i++, curOffset += stride) {
  61077. var si = this._sortTable[i];
  61078. if (!si) {
  61079. si = new SortInfo();
  61080. this._sortTable[i] = si;
  61081. }
  61082. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  61083. si.offset = curOffset;
  61084. si.swapedOffset = null;
  61085. this._sortedTable[i] = si;
  61086. }
  61087. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  61088. if (this.sortingAscending) {
  61089. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  61090. }
  61091. else {
  61092. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  61093. }
  61094. var swapElements = function (src, dst) {
  61095. for (var i = 0; i < stride; i++) {
  61096. var tps = _this.buffer[dst + i];
  61097. _this.buffer[dst + i] = _this.buffer[src + i];
  61098. _this.buffer[src + i] = tps;
  61099. }
  61100. };
  61101. // 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:
  61102. // 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),
  61103. // and I still want something with a good algorithm complexity.
  61104. // 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,
  61105. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  61106. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  61107. // 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
  61108. // until we find a SortInfo object without a swapedOffset which means we got the right location
  61109. // 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
  61110. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  61111. for (var i = 0; i < count; i++) {
  61112. // Get the element to move
  61113. var sourceSI = this._sortedTable[i];
  61114. var destSI = this._sortTable[i];
  61115. var sourceOff = sourceSI.offset;
  61116. // If the source changed location, find the new one
  61117. if (sourceSI.swapedOffset) {
  61118. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  61119. var curSI = sourceSI;
  61120. while (curSI.swapedOffset) {
  61121. curSI = this._sortTable[curSI.swapedOffset / stride];
  61122. }
  61123. // Finally get the right location
  61124. sourceOff = curSI.offset;
  61125. }
  61126. // Tag the element being replaced with its new location
  61127. destSI.swapedOffset = sourceOff;
  61128. // Swap elements (only if needed)
  61129. if (sourceOff !== destSI.offset) {
  61130. swapElements(sourceOff, destSI.offset);
  61131. }
  61132. // Update the offset in the corresponding DFAE
  61133. //sourceSI.entry.offset = destSI.entry.offset;
  61134. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  61135. }
  61136. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  61137. return true;
  61138. };
  61139. return DynamicFloatArray;
  61140. }());
  61141. BABYLON.DynamicFloatArray = DynamicFloatArray;
  61142. var SortInfo = (function () {
  61143. function SortInfo() {
  61144. this.compareData = this.offset = this.swapedOffset = null;
  61145. }
  61146. return SortInfo;
  61147. }());
  61148. })(BABYLON || (BABYLON = {}));
  61149. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  61150. var BABYLON;
  61151. (function (BABYLON) {
  61152. var serializedGeometries = [];
  61153. var serializeGeometry = function (geometry, serializationGeometries) {
  61154. if (serializedGeometries[geometry.id]) {
  61155. return;
  61156. }
  61157. if (geometry.doNotSerialize) {
  61158. return;
  61159. }
  61160. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  61161. serializationGeometries.boxes.push(geometry.serialize());
  61162. }
  61163. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  61164. serializationGeometries.spheres.push(geometry.serialize());
  61165. }
  61166. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  61167. serializationGeometries.cylinders.push(geometry.serialize());
  61168. }
  61169. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  61170. serializationGeometries.toruses.push(geometry.serialize());
  61171. }
  61172. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  61173. serializationGeometries.grounds.push(geometry.serialize());
  61174. }
  61175. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  61176. serializationGeometries.planes.push(geometry.serialize());
  61177. }
  61178. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  61179. serializationGeometries.torusKnots.push(geometry.serialize());
  61180. }
  61181. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  61182. throw new Error("Unknown primitive type");
  61183. }
  61184. else {
  61185. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  61186. }
  61187. serializedGeometries[geometry.id] = true;
  61188. };
  61189. var serializeMesh = function (mesh, serializationScene) {
  61190. var serializationObject = {};
  61191. // Geometry
  61192. var geometry = mesh._geometry;
  61193. if (geometry) {
  61194. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  61195. // 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
  61196. serializeGeometry(geometry, serializationScene.geometries);
  61197. }
  61198. }
  61199. // Custom
  61200. if (mesh.serialize) {
  61201. mesh.serialize(serializationObject);
  61202. }
  61203. return serializationObject;
  61204. };
  61205. var finalizeSingleMesh = function (mesh, serializationObject) {
  61206. //only works if the mesh is already loaded
  61207. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  61208. //serialize material
  61209. if (mesh.material) {
  61210. if (mesh.material instanceof BABYLON.StandardMaterial) {
  61211. serializationObject.materials = serializationObject.materials || [];
  61212. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  61213. serializationObject.materials.push(mesh.material.serialize());
  61214. }
  61215. }
  61216. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  61217. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  61218. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  61219. serializationObject.multiMaterials.push(mesh.material.serialize());
  61220. }
  61221. }
  61222. }
  61223. //serialize geometry
  61224. var geometry = mesh._geometry;
  61225. if (geometry) {
  61226. if (!serializationObject.geometries) {
  61227. serializationObject.geometries = {};
  61228. serializationObject.geometries.boxes = [];
  61229. serializationObject.geometries.spheres = [];
  61230. serializationObject.geometries.cylinders = [];
  61231. serializationObject.geometries.toruses = [];
  61232. serializationObject.geometries.grounds = [];
  61233. serializationObject.geometries.planes = [];
  61234. serializationObject.geometries.torusKnots = [];
  61235. serializationObject.geometries.vertexData = [];
  61236. }
  61237. serializeGeometry(geometry, serializationObject.geometries);
  61238. }
  61239. // Skeletons
  61240. if (mesh.skeleton) {
  61241. serializationObject.skeletons = serializationObject.skeletons || [];
  61242. serializationObject.skeletons.push(mesh.skeleton.serialize());
  61243. }
  61244. //serialize the actual mesh
  61245. serializationObject.meshes = serializationObject.meshes || [];
  61246. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  61247. }
  61248. };
  61249. var SceneSerializer = (function () {
  61250. function SceneSerializer() {
  61251. }
  61252. SceneSerializer.ClearCache = function () {
  61253. serializedGeometries = [];
  61254. };
  61255. SceneSerializer.Serialize = function (scene) {
  61256. var serializationObject = {};
  61257. SceneSerializer.ClearCache();
  61258. // Scene
  61259. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  61260. serializationObject.autoClear = scene.autoClear;
  61261. serializationObject.clearColor = scene.clearColor.asArray();
  61262. serializationObject.ambientColor = scene.ambientColor.asArray();
  61263. serializationObject.gravity = scene.gravity.asArray();
  61264. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  61265. serializationObject.workerCollisions = scene.workerCollisions;
  61266. // Fog
  61267. if (scene.fogMode && scene.fogMode !== 0) {
  61268. serializationObject.fogMode = scene.fogMode;
  61269. serializationObject.fogColor = scene.fogColor.asArray();
  61270. serializationObject.fogStart = scene.fogStart;
  61271. serializationObject.fogEnd = scene.fogEnd;
  61272. serializationObject.fogDensity = scene.fogDensity;
  61273. }
  61274. //Physics
  61275. if (scene.isPhysicsEnabled()) {
  61276. serializationObject.physicsEnabled = true;
  61277. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  61278. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  61279. }
  61280. // Metadata
  61281. if (scene.metadata) {
  61282. serializationObject.metadata = scene.metadata;
  61283. }
  61284. // Morph targets
  61285. serializationObject.morphTargetManagers = [];
  61286. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  61287. var abstractMesh = _a[_i];
  61288. var manager = abstractMesh.morphTargetManager;
  61289. if (manager) {
  61290. serializationObject.morphTargetManagers.push(manager.serialize());
  61291. }
  61292. }
  61293. // Lights
  61294. serializationObject.lights = [];
  61295. var index;
  61296. var light;
  61297. for (index = 0; index < scene.lights.length; index++) {
  61298. light = scene.lights[index];
  61299. if (!light.doNotSerialize) {
  61300. serializationObject.lights.push(light.serialize());
  61301. }
  61302. }
  61303. // Cameras
  61304. serializationObject.cameras = [];
  61305. for (index = 0; index < scene.cameras.length; index++) {
  61306. var camera = scene.cameras[index];
  61307. if (!camera.doNotSerialize) {
  61308. serializationObject.cameras.push(camera.serialize());
  61309. }
  61310. }
  61311. if (scene.activeCamera) {
  61312. serializationObject.activeCameraID = scene.activeCamera.id;
  61313. }
  61314. // Animations
  61315. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  61316. // Materials
  61317. serializationObject.materials = [];
  61318. serializationObject.multiMaterials = [];
  61319. var material;
  61320. for (index = 0; index < scene.materials.length; index++) {
  61321. material = scene.materials[index];
  61322. if (!material.doNotSerialize) {
  61323. serializationObject.materials.push(material.serialize());
  61324. }
  61325. }
  61326. // MultiMaterials
  61327. serializationObject.multiMaterials = [];
  61328. for (index = 0; index < scene.multiMaterials.length; index++) {
  61329. var multiMaterial = scene.multiMaterials[index];
  61330. serializationObject.multiMaterials.push(multiMaterial.serialize());
  61331. }
  61332. // Skeletons
  61333. serializationObject.skeletons = [];
  61334. for (index = 0; index < scene.skeletons.length; index++) {
  61335. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  61336. }
  61337. // Geometries
  61338. serializationObject.geometries = {};
  61339. serializationObject.geometries.boxes = [];
  61340. serializationObject.geometries.spheres = [];
  61341. serializationObject.geometries.cylinders = [];
  61342. serializationObject.geometries.toruses = [];
  61343. serializationObject.geometries.grounds = [];
  61344. serializationObject.geometries.planes = [];
  61345. serializationObject.geometries.torusKnots = [];
  61346. serializationObject.geometries.vertexData = [];
  61347. serializedGeometries = [];
  61348. var geometries = scene.getGeometries();
  61349. for (index = 0; index < geometries.length; index++) {
  61350. var geometry = geometries[index];
  61351. if (geometry.isReady()) {
  61352. serializeGeometry(geometry, serializationObject.geometries);
  61353. }
  61354. }
  61355. // Meshes
  61356. serializationObject.meshes = [];
  61357. for (index = 0; index < scene.meshes.length; index++) {
  61358. var abstractMesh = scene.meshes[index];
  61359. if (abstractMesh instanceof BABYLON.Mesh) {
  61360. var mesh = abstractMesh;
  61361. if (!mesh.doNotSerialize) {
  61362. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  61363. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  61364. }
  61365. }
  61366. }
  61367. }
  61368. // Particles Systems
  61369. serializationObject.particleSystems = [];
  61370. for (index = 0; index < scene.particleSystems.length; index++) {
  61371. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  61372. }
  61373. // Lens flares
  61374. serializationObject.lensFlareSystems = [];
  61375. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  61376. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  61377. }
  61378. // Shadows
  61379. serializationObject.shadowGenerators = [];
  61380. for (index = 0; index < scene.lights.length; index++) {
  61381. light = scene.lights[index];
  61382. var shadowGenerator = light.getShadowGenerator();
  61383. // Only support serialization for official generator so far.
  61384. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  61385. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  61386. }
  61387. }
  61388. // Action Manager
  61389. if (scene.actionManager) {
  61390. serializationObject.actions = scene.actionManager.serialize("scene");
  61391. }
  61392. // Audio
  61393. serializationObject.sounds = [];
  61394. for (index = 0; index < scene.soundTracks.length; index++) {
  61395. var soundtrack = scene.soundTracks[index];
  61396. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  61397. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  61398. }
  61399. }
  61400. return serializationObject;
  61401. };
  61402. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  61403. if (withParents === void 0) { withParents = false; }
  61404. if (withChildren === void 0) { withChildren = false; }
  61405. var serializationObject = {};
  61406. SceneSerializer.ClearCache();
  61407. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  61408. if (withParents || withChildren) {
  61409. //deliberate for loop! not for each, appended should be processed as well.
  61410. for (var i = 0; i < toSerialize.length; ++i) {
  61411. if (withChildren) {
  61412. toSerialize[i].getDescendants().forEach(function (node) {
  61413. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  61414. toSerialize.push(node);
  61415. }
  61416. });
  61417. }
  61418. //make sure the array doesn't contain the object already
  61419. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  61420. toSerialize.push(toSerialize[i].parent);
  61421. }
  61422. }
  61423. }
  61424. toSerialize.forEach(function (mesh) {
  61425. finalizeSingleMesh(mesh, serializationObject);
  61426. });
  61427. return serializationObject;
  61428. };
  61429. return SceneSerializer;
  61430. }());
  61431. BABYLON.SceneSerializer = SceneSerializer;
  61432. })(BABYLON || (BABYLON = {}));
  61433. //# sourceMappingURL=babylon.sceneSerializer.js.map
  61434. var BABYLON;
  61435. (function (BABYLON) {
  61436. var ReflectionProbe = (function () {
  61437. function ReflectionProbe(name, size, scene, generateMipMaps) {
  61438. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61439. var _this = this;
  61440. this.name = name;
  61441. this._viewMatrix = BABYLON.Matrix.Identity();
  61442. this._target = BABYLON.Vector3.Zero();
  61443. this._add = BABYLON.Vector3.Zero();
  61444. this.invertYAxis = false;
  61445. this.position = BABYLON.Vector3.Zero();
  61446. this._scene = scene;
  61447. this._scene.reflectionProbes.push(this);
  61448. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  61449. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  61450. switch (faceIndex) {
  61451. case 0:
  61452. _this._add.copyFromFloats(1, 0, 0);
  61453. break;
  61454. case 1:
  61455. _this._add.copyFromFloats(-1, 0, 0);
  61456. break;
  61457. case 2:
  61458. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  61459. break;
  61460. case 3:
  61461. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  61462. break;
  61463. case 4:
  61464. _this._add.copyFromFloats(0, 0, 1);
  61465. break;
  61466. case 5:
  61467. _this._add.copyFromFloats(0, 0, -1);
  61468. break;
  61469. }
  61470. if (_this._attachedMesh) {
  61471. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  61472. }
  61473. _this.position.addToRef(_this._add, _this._target);
  61474. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  61475. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  61476. });
  61477. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  61478. scene.updateTransformMatrix(true);
  61479. });
  61480. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  61481. }
  61482. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  61483. get: function () {
  61484. return this._renderTargetTexture.samples;
  61485. },
  61486. set: function (value) {
  61487. this._renderTargetTexture.samples = value;
  61488. },
  61489. enumerable: true,
  61490. configurable: true
  61491. });
  61492. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  61493. get: function () {
  61494. return this._renderTargetTexture.refreshRate;
  61495. },
  61496. set: function (value) {
  61497. this._renderTargetTexture.refreshRate = value;
  61498. },
  61499. enumerable: true,
  61500. configurable: true
  61501. });
  61502. ReflectionProbe.prototype.getScene = function () {
  61503. return this._scene;
  61504. };
  61505. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  61506. get: function () {
  61507. return this._renderTargetTexture;
  61508. },
  61509. enumerable: true,
  61510. configurable: true
  61511. });
  61512. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  61513. get: function () {
  61514. return this._renderTargetTexture.renderList;
  61515. },
  61516. enumerable: true,
  61517. configurable: true
  61518. });
  61519. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  61520. this._attachedMesh = mesh;
  61521. };
  61522. ReflectionProbe.prototype.dispose = function () {
  61523. var index = this._scene.reflectionProbes.indexOf(this);
  61524. if (index !== -1) {
  61525. // Remove from the scene if found
  61526. this._scene.reflectionProbes.splice(index, 1);
  61527. }
  61528. if (this._renderTargetTexture) {
  61529. this._renderTargetTexture.dispose();
  61530. this._renderTargetTexture = null;
  61531. }
  61532. };
  61533. return ReflectionProbe;
  61534. }());
  61535. BABYLON.ReflectionProbe = ReflectionProbe;
  61536. })(BABYLON || (BABYLON = {}));
  61537. //# sourceMappingURL=babylon.reflectionProbe.js.map
  61538. var BABYLON;
  61539. (function (BABYLON) {
  61540. var Layer = (function () {
  61541. function Layer(name, imgUrl, scene, isBackground, color) {
  61542. this.name = name;
  61543. this.scale = new BABYLON.Vector2(1, 1);
  61544. this.offset = new BABYLON.Vector2(0, 0);
  61545. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  61546. this._vertexBuffers = {};
  61547. // Events
  61548. /**
  61549. * An event triggered when the layer is disposed.
  61550. * @type {BABYLON.Observable}
  61551. */
  61552. this.onDisposeObservable = new BABYLON.Observable();
  61553. /**
  61554. * An event triggered before rendering the scene
  61555. * @type {BABYLON.Observable}
  61556. */
  61557. this.onBeforeRenderObservable = new BABYLON.Observable();
  61558. /**
  61559. * An event triggered after rendering the scene
  61560. * @type {BABYLON.Observable}
  61561. */
  61562. this.onAfterRenderObservable = new BABYLON.Observable();
  61563. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  61564. this.isBackground = isBackground === undefined ? true : isBackground;
  61565. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  61566. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61567. this._scene.layers.push(this);
  61568. var engine = scene.getEngine();
  61569. // VBO
  61570. var vertices = [];
  61571. vertices.push(1, 1);
  61572. vertices.push(-1, 1);
  61573. vertices.push(-1, -1);
  61574. vertices.push(1, -1);
  61575. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  61576. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  61577. // Indices
  61578. var indices = [];
  61579. indices.push(0);
  61580. indices.push(1);
  61581. indices.push(2);
  61582. indices.push(0);
  61583. indices.push(2);
  61584. indices.push(3);
  61585. this._indexBuffer = engine.createIndexBuffer(indices);
  61586. // Effects
  61587. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  61588. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  61589. }
  61590. Object.defineProperty(Layer.prototype, "onDispose", {
  61591. set: function (callback) {
  61592. if (this._onDisposeObserver) {
  61593. this.onDisposeObservable.remove(this._onDisposeObserver);
  61594. }
  61595. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  61596. },
  61597. enumerable: true,
  61598. configurable: true
  61599. });
  61600. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  61601. set: function (callback) {
  61602. if (this._onBeforeRenderObserver) {
  61603. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  61604. }
  61605. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  61606. },
  61607. enumerable: true,
  61608. configurable: true
  61609. });
  61610. Object.defineProperty(Layer.prototype, "onAfterRender", {
  61611. set: function (callback) {
  61612. if (this._onAfterRenderObserver) {
  61613. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  61614. }
  61615. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  61616. },
  61617. enumerable: true,
  61618. configurable: true
  61619. });
  61620. Layer.prototype.render = function () {
  61621. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  61622. // Check
  61623. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  61624. return;
  61625. var engine = this._scene.getEngine();
  61626. this.onBeforeRenderObservable.notifyObservers(this);
  61627. // Render
  61628. engine.enableEffect(currentEffect);
  61629. engine.setState(false);
  61630. // Texture
  61631. currentEffect.setTexture("textureSampler", this.texture);
  61632. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  61633. // Color
  61634. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  61635. // Scale / offset
  61636. currentEffect.setVector2("offset", this.offset);
  61637. currentEffect.setVector2("scale", this.scale);
  61638. // VBOs
  61639. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  61640. // Draw order
  61641. if (!this.alphaTest) {
  61642. engine.setAlphaMode(this.alphaBlendingMode);
  61643. engine.draw(true, 0, 6);
  61644. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61645. }
  61646. else {
  61647. engine.draw(true, 0, 6);
  61648. }
  61649. this.onAfterRenderObservable.notifyObservers(this);
  61650. };
  61651. Layer.prototype.dispose = function () {
  61652. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61653. if (vertexBuffer) {
  61654. vertexBuffer.dispose();
  61655. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61656. }
  61657. if (this._indexBuffer) {
  61658. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61659. this._indexBuffer = null;
  61660. }
  61661. if (this.texture) {
  61662. this.texture.dispose();
  61663. this.texture = null;
  61664. }
  61665. // Remove from scene
  61666. var index = this._scene.layers.indexOf(this);
  61667. this._scene.layers.splice(index, 1);
  61668. // Callback
  61669. this.onDisposeObservable.notifyObservers(this);
  61670. this.onDisposeObservable.clear();
  61671. this.onAfterRenderObservable.clear();
  61672. this.onBeforeRenderObservable.clear();
  61673. };
  61674. return Layer;
  61675. }());
  61676. BABYLON.Layer = Layer;
  61677. })(BABYLON || (BABYLON = {}));
  61678. //# sourceMappingURL=babylon.layer.js.map
  61679. BABYLON.Effect.ShadersStore={"defaultVertexShader":"\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>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\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#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":"#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;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\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<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\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_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#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\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\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>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\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#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":"#ifdef BUMP\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;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec3 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#include<fresnelFunction>\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\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\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#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\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=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\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#ifdef OVERLOADEDVALUES\nambientOcclusionColor.rgb=mix(ambientOcclusionColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a*vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#else\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#endif\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.rgb;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo.rgb=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#else\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface=microSurfaceTexel.r;\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\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\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\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#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=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\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\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=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=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 OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\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\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=lightDiffuseContribution*surfaceAlbedoContribution;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=(lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=(shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution;\n#endif\n#else\nvec3 finalDiffuse=lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor;\n#endif\n#endif\n#endif\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution+=vAmbientColor;\nshadowedOnlyLightDiffuseContribution*=surfaceAlbedo.rgb;\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution,0.0);\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\nfinalDiffuse=(finalDiffuse*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance)*ambientOcclusionColor;\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\nvec4 finalColor=vec4(finalDiffuse+finalSpecular*vLightingIntensity.x+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\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\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\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\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 FULLFLOAT\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#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\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","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(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","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\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]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\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(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\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() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\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(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\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(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\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{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\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;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,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}","fxaaPixelShader":"varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\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 sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nvec2 sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nvec2 sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nvec2 sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nvec2 sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nvec2 sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nvec2 sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nvec2 sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\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}","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}","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,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\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}"};
  61680. 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(SPOTLIGHT{X}) || defined(DIRLIGHT{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#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#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(normal,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangent.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangent.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(SPOTLIGHT{X}) || defined(DIRLIGHT{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#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube 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};\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));\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));\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\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;\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","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\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 SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\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 SHADOWFULLFLOAT\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\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\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 SHADOWFULLFLOAT\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.); \n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,esm,vOverloadedShadowIntensity.x);\n#else\nreturn esm;\n#endif\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 SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\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 SHADOWFULLFLOAT\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\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,min(1.0,visibility+darkness),vOverloadedShadowIntensity.x);\n#else\nreturn min(1.0,visibility+darkness);\n#endif\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 SHADOWFULLFLOAT\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\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,esm,vOverloadedShadowIntensity.x);\n#else\nreturn esm;\n#endif\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 vec3 vBumpInfos;\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\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#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,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#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithESMCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if 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","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}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithESMCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif"};
  61681. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  61682. module.exports = BABYLON;
  61683. };