babylon.max.js 3.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636
  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. return this;
  2467. };
  2468. /**
  2469. * Updates the current Quaternion from the passed rotation matrix values.
  2470. * Returns the updated Quaternion.
  2471. */
  2472. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2473. Quaternion.FromRotationMatrixToRef(matrix, this);
  2474. return this;
  2475. };
  2476. // Statics
  2477. /**
  2478. * Returns a new Quaternion set from the passed rotation matrix values.
  2479. */
  2480. Quaternion.FromRotationMatrix = function (matrix) {
  2481. var result = new Quaternion();
  2482. Quaternion.FromRotationMatrixToRef(matrix, result);
  2483. return result;
  2484. };
  2485. /**
  2486. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2487. */
  2488. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2489. var data = matrix.m;
  2490. var m11 = data[0], m12 = data[4], m13 = data[8];
  2491. var m21 = data[1], m22 = data[5], m23 = data[9];
  2492. var m31 = data[2], m32 = data[6], m33 = data[10];
  2493. var trace = m11 + m22 + m33;
  2494. var s;
  2495. if (trace > 0) {
  2496. s = 0.5 / Math.sqrt(trace + 1.0);
  2497. result.w = 0.25 / s;
  2498. result.x = (m32 - m23) * s;
  2499. result.y = (m13 - m31) * s;
  2500. result.z = (m21 - m12) * s;
  2501. }
  2502. else if (m11 > m22 && m11 > m33) {
  2503. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2504. result.w = (m32 - m23) / s;
  2505. result.x = 0.25 * s;
  2506. result.y = (m12 + m21) / s;
  2507. result.z = (m13 + m31) / s;
  2508. }
  2509. else if (m22 > m33) {
  2510. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2511. result.w = (m13 - m31) / s;
  2512. result.x = (m12 + m21) / s;
  2513. result.y = 0.25 * s;
  2514. result.z = (m23 + m32) / s;
  2515. }
  2516. else {
  2517. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2518. result.w = (m21 - m12) / s;
  2519. result.x = (m13 + m31) / s;
  2520. result.y = (m23 + m32) / s;
  2521. result.z = 0.25 * s;
  2522. }
  2523. };
  2524. /**
  2525. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2526. */
  2527. Quaternion.Zero = function () {
  2528. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2529. };
  2530. /**
  2531. * Returns a new Quaternion as the inverted current Quaternion.
  2532. */
  2533. Quaternion.Inverse = function (q) {
  2534. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2535. };
  2536. /**
  2537. * Returns the identity Quaternion.
  2538. */
  2539. Quaternion.Identity = function () {
  2540. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2541. };
  2542. Quaternion.IsIdentity = function (quaternion) {
  2543. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2544. };
  2545. /**
  2546. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2547. */
  2548. Quaternion.RotationAxis = function (axis, angle) {
  2549. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2550. };
  2551. /**
  2552. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2553. */
  2554. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2555. var sin = Math.sin(angle / 2);
  2556. axis.normalize();
  2557. result.w = Math.cos(angle / 2);
  2558. result.x = axis.x * sin;
  2559. result.y = axis.y * sin;
  2560. result.z = axis.z * sin;
  2561. return result;
  2562. };
  2563. /**
  2564. * Retuns a new Quaternion set from the starting index of the passed array.
  2565. */
  2566. Quaternion.FromArray = function (array, offset) {
  2567. if (!offset) {
  2568. offset = 0;
  2569. }
  2570. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2571. };
  2572. /**
  2573. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2574. */
  2575. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2576. var q = new Quaternion();
  2577. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2578. return q;
  2579. };
  2580. /**
  2581. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2582. */
  2583. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2584. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2585. var halfRoll = roll * 0.5;
  2586. var halfPitch = pitch * 0.5;
  2587. var halfYaw = yaw * 0.5;
  2588. var sinRoll = Math.sin(halfRoll);
  2589. var cosRoll = Math.cos(halfRoll);
  2590. var sinPitch = Math.sin(halfPitch);
  2591. var cosPitch = Math.cos(halfPitch);
  2592. var sinYaw = Math.sin(halfYaw);
  2593. var cosYaw = Math.cos(halfYaw);
  2594. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2595. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2596. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2597. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2598. };
  2599. /**
  2600. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2601. */
  2602. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2603. var result = new Quaternion();
  2604. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2605. return result;
  2606. };
  2607. /**
  2608. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2609. */
  2610. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2611. // Produces a quaternion from Euler angles in the z-x-z orientation
  2612. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2613. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2614. var halfBeta = beta * 0.5;
  2615. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2616. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2617. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2618. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2619. };
  2620. /**
  2621. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2622. * cf to Vector3.RotationFromAxis() documentation.
  2623. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2624. */
  2625. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2626. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2627. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2628. return quat;
  2629. };
  2630. /**
  2631. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2632. * cf to Vector3.RotationFromAxis() documentation.
  2633. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2634. */
  2635. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2636. var rotMat = MathTmp.Matrix[0];
  2637. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2638. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2639. };
  2640. Quaternion.Slerp = function (left, right, amount) {
  2641. var result = Quaternion.Identity();
  2642. Quaternion.SlerpToRef(left, right, amount, result);
  2643. return result;
  2644. };
  2645. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2646. var num2;
  2647. var num3;
  2648. var num = amount;
  2649. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2650. var flag = false;
  2651. if (num4 < 0) {
  2652. flag = true;
  2653. num4 = -num4;
  2654. }
  2655. if (num4 > 0.999999) {
  2656. num3 = 1 - num;
  2657. num2 = flag ? -num : num;
  2658. }
  2659. else {
  2660. var num5 = Math.acos(num4);
  2661. var num6 = (1.0 / Math.sin(num5));
  2662. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2663. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2664. }
  2665. result.x = (num3 * left.x) + (num2 * right.x);
  2666. result.y = (num3 * left.y) + (num2 * right.y);
  2667. result.z = (num3 * left.z) + (num2 * right.z);
  2668. result.w = (num3 * left.w) + (num2 * right.w);
  2669. };
  2670. return Quaternion;
  2671. }());
  2672. BABYLON.Quaternion = Quaternion;
  2673. var Matrix = (function () {
  2674. function Matrix() {
  2675. this.m = new Float32Array(16);
  2676. }
  2677. // Properties
  2678. /**
  2679. * Boolean : True is the matrix is the identity matrix
  2680. */
  2681. Matrix.prototype.isIdentity = function () {
  2682. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2683. return false;
  2684. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2685. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2686. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2687. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2688. return false;
  2689. return true;
  2690. };
  2691. /**
  2692. * Returns the matrix determinant (float).
  2693. */
  2694. Matrix.prototype.determinant = function () {
  2695. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2696. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2697. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2698. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2699. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2700. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2701. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2702. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2703. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2704. };
  2705. // Methods
  2706. /**
  2707. * Returns the matrix underlying array.
  2708. */
  2709. Matrix.prototype.toArray = function () {
  2710. return this.m;
  2711. };
  2712. /**
  2713. * Returns the matrix underlying array.
  2714. */
  2715. Matrix.prototype.asArray = function () {
  2716. return this.toArray();
  2717. };
  2718. /**
  2719. * Inverts in place the Matrix.
  2720. * Returns the Matrix inverted.
  2721. */
  2722. Matrix.prototype.invert = function () {
  2723. this.invertToRef(this);
  2724. return this;
  2725. };
  2726. /**
  2727. * Sets all the matrix elements to zero.
  2728. * Returns the Matrix.
  2729. */
  2730. Matrix.prototype.reset = function () {
  2731. for (var index = 0; index < 16; index++) {
  2732. this.m[index] = 0.0;
  2733. }
  2734. return this;
  2735. };
  2736. /**
  2737. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2738. */
  2739. Matrix.prototype.add = function (other) {
  2740. var result = new Matrix();
  2741. this.addToRef(other, result);
  2742. return result;
  2743. };
  2744. /**
  2745. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2746. * Returns the Matrix.
  2747. */
  2748. Matrix.prototype.addToRef = function (other, result) {
  2749. for (var index = 0; index < 16; index++) {
  2750. result.m[index] = this.m[index] + other.m[index];
  2751. }
  2752. return this;
  2753. };
  2754. /**
  2755. * Adds in place the passed matrix to the current Matrix.
  2756. * Returns the updated Matrix.
  2757. */
  2758. Matrix.prototype.addToSelf = function (other) {
  2759. for (var index = 0; index < 16; index++) {
  2760. this.m[index] += other.m[index];
  2761. }
  2762. return this;
  2763. };
  2764. /**
  2765. * Sets the passed matrix with the current inverted Matrix.
  2766. * Returns the unmodified current Matrix.
  2767. */
  2768. Matrix.prototype.invertToRef = function (other) {
  2769. var l1 = this.m[0];
  2770. var l2 = this.m[1];
  2771. var l3 = this.m[2];
  2772. var l4 = this.m[3];
  2773. var l5 = this.m[4];
  2774. var l6 = this.m[5];
  2775. var l7 = this.m[6];
  2776. var l8 = this.m[7];
  2777. var l9 = this.m[8];
  2778. var l10 = this.m[9];
  2779. var l11 = this.m[10];
  2780. var l12 = this.m[11];
  2781. var l13 = this.m[12];
  2782. var l14 = this.m[13];
  2783. var l15 = this.m[14];
  2784. var l16 = this.m[15];
  2785. var l17 = (l11 * l16) - (l12 * l15);
  2786. var l18 = (l10 * l16) - (l12 * l14);
  2787. var l19 = (l10 * l15) - (l11 * l14);
  2788. var l20 = (l9 * l16) - (l12 * l13);
  2789. var l21 = (l9 * l15) - (l11 * l13);
  2790. var l22 = (l9 * l14) - (l10 * l13);
  2791. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2792. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2793. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2794. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2795. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2796. var l28 = (l7 * l16) - (l8 * l15);
  2797. var l29 = (l6 * l16) - (l8 * l14);
  2798. var l30 = (l6 * l15) - (l7 * l14);
  2799. var l31 = (l5 * l16) - (l8 * l13);
  2800. var l32 = (l5 * l15) - (l7 * l13);
  2801. var l33 = (l5 * l14) - (l6 * l13);
  2802. var l34 = (l7 * l12) - (l8 * l11);
  2803. var l35 = (l6 * l12) - (l8 * l10);
  2804. var l36 = (l6 * l11) - (l7 * l10);
  2805. var l37 = (l5 * l12) - (l8 * l9);
  2806. var l38 = (l5 * l11) - (l7 * l9);
  2807. var l39 = (l5 * l10) - (l6 * l9);
  2808. other.m[0] = l23 * l27;
  2809. other.m[4] = l24 * l27;
  2810. other.m[8] = l25 * l27;
  2811. other.m[12] = l26 * l27;
  2812. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2813. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2814. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2815. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2816. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2817. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2818. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2819. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2820. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2821. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2822. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2823. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2824. return this;
  2825. };
  2826. /**
  2827. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2828. * Returns the updated Matrix.
  2829. */
  2830. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2831. this.m[12] = x;
  2832. this.m[13] = y;
  2833. this.m[14] = z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Inserts the translation vector in the current Matrix.
  2838. * Returns the updated Matrix.
  2839. */
  2840. Matrix.prototype.setTranslation = function (vector3) {
  2841. this.m[12] = vector3.x;
  2842. this.m[13] = vector3.y;
  2843. this.m[14] = vector3.z;
  2844. return this;
  2845. };
  2846. /**
  2847. * Returns a new Vector3 as the extracted translation from the Matrix.
  2848. */
  2849. Matrix.prototype.getTranslation = function () {
  2850. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2851. };
  2852. /**
  2853. * Fill a Vector3 with the extracted translation from the Matrix.
  2854. */
  2855. Matrix.prototype.getTranslationToRef = function (result) {
  2856. result.x = this.m[12];
  2857. result.y = this.m[13];
  2858. result.z = this.m[14];
  2859. return this;
  2860. };
  2861. /**
  2862. * Remove rotation and scaling part from the Matrix.
  2863. * Returns the updated Matrix.
  2864. */
  2865. Matrix.prototype.removeRotationAndScaling = function () {
  2866. this.setRowFromFloats(0, 1, 0, 0, 0);
  2867. this.setRowFromFloats(1, 0, 1, 0, 0);
  2868. this.setRowFromFloats(2, 0, 0, 1, 0);
  2869. return this;
  2870. };
  2871. /**
  2872. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2873. */
  2874. Matrix.prototype.multiply = function (other) {
  2875. var result = new Matrix();
  2876. this.multiplyToRef(other, result);
  2877. return result;
  2878. };
  2879. /**
  2880. * Updates the current Matrix from the passed one values.
  2881. * Returns the updated Matrix.
  2882. */
  2883. Matrix.prototype.copyFrom = function (other) {
  2884. for (var index = 0; index < 16; index++) {
  2885. this.m[index] = other.m[index];
  2886. }
  2887. return this;
  2888. };
  2889. /**
  2890. * Populates the passed array from the starting index with the Matrix values.
  2891. * Returns the Matrix.
  2892. */
  2893. Matrix.prototype.copyToArray = function (array, offset) {
  2894. if (offset === void 0) { offset = 0; }
  2895. for (var index = 0; index < 16; index++) {
  2896. array[offset + index] = this.m[index];
  2897. }
  2898. return this;
  2899. };
  2900. /**
  2901. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2902. */
  2903. Matrix.prototype.multiplyToRef = function (other, result) {
  2904. this.multiplyToArray(other, result.m, 0);
  2905. return this;
  2906. };
  2907. /**
  2908. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2909. */
  2910. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2911. var tm0 = this.m[0];
  2912. var tm1 = this.m[1];
  2913. var tm2 = this.m[2];
  2914. var tm3 = this.m[3];
  2915. var tm4 = this.m[4];
  2916. var tm5 = this.m[5];
  2917. var tm6 = this.m[6];
  2918. var tm7 = this.m[7];
  2919. var tm8 = this.m[8];
  2920. var tm9 = this.m[9];
  2921. var tm10 = this.m[10];
  2922. var tm11 = this.m[11];
  2923. var tm12 = this.m[12];
  2924. var tm13 = this.m[13];
  2925. var tm14 = this.m[14];
  2926. var tm15 = this.m[15];
  2927. var om0 = other.m[0];
  2928. var om1 = other.m[1];
  2929. var om2 = other.m[2];
  2930. var om3 = other.m[3];
  2931. var om4 = other.m[4];
  2932. var om5 = other.m[5];
  2933. var om6 = other.m[6];
  2934. var om7 = other.m[7];
  2935. var om8 = other.m[8];
  2936. var om9 = other.m[9];
  2937. var om10 = other.m[10];
  2938. var om11 = other.m[11];
  2939. var om12 = other.m[12];
  2940. var om13 = other.m[13];
  2941. var om14 = other.m[14];
  2942. var om15 = other.m[15];
  2943. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2944. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2945. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2946. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2947. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2948. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2949. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2950. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2951. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2952. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2953. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  2954. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  2955. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  2956. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  2957. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  2958. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  2959. return this;
  2960. };
  2961. /**
  2962. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  2963. */
  2964. Matrix.prototype.equals = function (value) {
  2965. return value &&
  2966. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  2967. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  2968. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  2969. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  2970. };
  2971. /**
  2972. * Returns a new Matrix from the current Matrix.
  2973. */
  2974. Matrix.prototype.clone = function () {
  2975. 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]);
  2976. };
  2977. /**
  2978. * Returns the string "Matrix"
  2979. */
  2980. Matrix.prototype.getClassName = function () {
  2981. return "Matrix";
  2982. };
  2983. /**
  2984. * Returns the Matrix hash code.
  2985. */
  2986. Matrix.prototype.getHashCode = function () {
  2987. var hash = this.m[0] || 0;
  2988. for (var i = 1; i < 16; i++) {
  2989. hash = (hash * 397) ^ (this.m[i] || 0);
  2990. }
  2991. return hash;
  2992. };
  2993. /**
  2994. * Decomposes the current Matrix into :
  2995. * - a scale vector3 passed as a reference to update,
  2996. * - a rotation quaternion passed as a reference to update,
  2997. * - a translation vector3 passed as a reference to update.
  2998. * Returns the boolean `true`.
  2999. */
  3000. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3001. translation.x = this.m[12];
  3002. translation.y = this.m[13];
  3003. translation.z = this.m[14];
  3004. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3005. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3006. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3007. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3008. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3009. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3010. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3011. rotation.x = 0;
  3012. rotation.y = 0;
  3013. rotation.z = 0;
  3014. rotation.w = 1;
  3015. return false;
  3016. }
  3017. 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]);
  3018. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3019. return true;
  3020. };
  3021. /**
  3022. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3023. */
  3024. Matrix.prototype.getRotationMatrix = function () {
  3025. var result = Matrix.Identity();
  3026. this.getRotationMatrixToRef(result);
  3027. return result;
  3028. };
  3029. /**
  3030. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3031. * Returns the current Matrix.
  3032. */
  3033. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3034. var m = this.m;
  3035. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3036. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3037. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3038. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3039. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3040. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3041. 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);
  3042. return this;
  3043. };
  3044. // Statics
  3045. /**
  3046. * Returns a new Matrix set from the starting index of the passed array.
  3047. */
  3048. Matrix.FromArray = function (array, offset) {
  3049. var result = new Matrix();
  3050. if (!offset) {
  3051. offset = 0;
  3052. }
  3053. Matrix.FromArrayToRef(array, offset, result);
  3054. return result;
  3055. };
  3056. /**
  3057. * Sets the passed "result" matrix from the starting index of the passed array.
  3058. */
  3059. Matrix.FromArrayToRef = function (array, offset, result) {
  3060. for (var index = 0; index < 16; index++) {
  3061. result.m[index] = array[index + offset];
  3062. }
  3063. };
  3064. /**
  3065. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3066. */
  3067. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3068. for (var index = 0; index < 16; index++) {
  3069. result.m[index] = array[index + offset] * scale;
  3070. }
  3071. };
  3072. /**
  3073. * Sets the passed matrix "result" with the 16 passed floats.
  3074. */
  3075. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3076. result.m[0] = initialM11;
  3077. result.m[1] = initialM12;
  3078. result.m[2] = initialM13;
  3079. result.m[3] = initialM14;
  3080. result.m[4] = initialM21;
  3081. result.m[5] = initialM22;
  3082. result.m[6] = initialM23;
  3083. result.m[7] = initialM24;
  3084. result.m[8] = initialM31;
  3085. result.m[9] = initialM32;
  3086. result.m[10] = initialM33;
  3087. result.m[11] = initialM34;
  3088. result.m[12] = initialM41;
  3089. result.m[13] = initialM42;
  3090. result.m[14] = initialM43;
  3091. result.m[15] = initialM44;
  3092. };
  3093. /**
  3094. * Returns the index-th row of the current matrix as a new Vector4.
  3095. */
  3096. Matrix.prototype.getRow = function (index) {
  3097. if (index < 0 || index > 3) {
  3098. return null;
  3099. }
  3100. var i = index * 4;
  3101. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3102. };
  3103. /**
  3104. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3105. * Returns the updated Matrix.
  3106. */
  3107. Matrix.prototype.setRow = function (index, row) {
  3108. if (index < 0 || index > 3) {
  3109. return this;
  3110. }
  3111. var i = index * 4;
  3112. this.m[i + 0] = row.x;
  3113. this.m[i + 1] = row.y;
  3114. this.m[i + 2] = row.z;
  3115. this.m[i + 3] = row.w;
  3116. return this;
  3117. };
  3118. /**
  3119. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3120. * Returns the updated Matrix.
  3121. */
  3122. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3123. if (index < 0 || index > 3) {
  3124. return this;
  3125. }
  3126. var i = index * 4;
  3127. this.m[i + 0] = x;
  3128. this.m[i + 1] = y;
  3129. this.m[i + 2] = z;
  3130. this.m[i + 3] = w;
  3131. return this;
  3132. };
  3133. /**
  3134. * Returns a new Matrix set from the 16 passed floats.
  3135. */
  3136. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3137. var result = new Matrix();
  3138. result.m[0] = initialM11;
  3139. result.m[1] = initialM12;
  3140. result.m[2] = initialM13;
  3141. result.m[3] = initialM14;
  3142. result.m[4] = initialM21;
  3143. result.m[5] = initialM22;
  3144. result.m[6] = initialM23;
  3145. result.m[7] = initialM24;
  3146. result.m[8] = initialM31;
  3147. result.m[9] = initialM32;
  3148. result.m[10] = initialM33;
  3149. result.m[11] = initialM34;
  3150. result.m[12] = initialM41;
  3151. result.m[13] = initialM42;
  3152. result.m[14] = initialM43;
  3153. result.m[15] = initialM44;
  3154. return result;
  3155. };
  3156. /**
  3157. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3158. */
  3159. Matrix.Compose = function (scale, rotation, translation) {
  3160. var result = Matrix.Identity();
  3161. Matrix.ComposeToRef(scale, rotation, translation, result);
  3162. return result;
  3163. };
  3164. /**
  3165. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3166. */
  3167. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3168. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3169. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3170. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3171. result.setTranslation(translation);
  3172. };
  3173. /**
  3174. * Returns a new indentity Matrix.
  3175. */
  3176. Matrix.Identity = function () {
  3177. 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);
  3178. };
  3179. /**
  3180. * Sets the passed "result" as an identity matrix.
  3181. */
  3182. Matrix.IdentityToRef = function (result) {
  3183. 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);
  3184. };
  3185. /**
  3186. * Returns a new zero Matrix.
  3187. */
  3188. Matrix.Zero = function () {
  3189. 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);
  3190. };
  3191. /**
  3192. * Returns a new rotation matrix for "angle" radians around the X axis.
  3193. */
  3194. Matrix.RotationX = function (angle) {
  3195. var result = new Matrix();
  3196. Matrix.RotationXToRef(angle, result);
  3197. return result;
  3198. };
  3199. /**
  3200. * Returns a new Matrix as the passed inverted one.
  3201. */
  3202. Matrix.Invert = function (source) {
  3203. var result = new Matrix();
  3204. source.invertToRef(result);
  3205. return result;
  3206. };
  3207. /**
  3208. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3209. */
  3210. Matrix.RotationXToRef = function (angle, result) {
  3211. var s = Math.sin(angle);
  3212. var c = Math.cos(angle);
  3213. result.m[0] = 1.0;
  3214. result.m[15] = 1.0;
  3215. result.m[5] = c;
  3216. result.m[10] = c;
  3217. result.m[9] = -s;
  3218. result.m[6] = s;
  3219. result.m[1] = 0.0;
  3220. result.m[2] = 0.0;
  3221. result.m[3] = 0.0;
  3222. result.m[4] = 0.0;
  3223. result.m[7] = 0.0;
  3224. result.m[8] = 0.0;
  3225. result.m[11] = 0.0;
  3226. result.m[12] = 0.0;
  3227. result.m[13] = 0.0;
  3228. result.m[14] = 0.0;
  3229. };
  3230. /**
  3231. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3232. */
  3233. Matrix.RotationY = function (angle) {
  3234. var result = new Matrix();
  3235. Matrix.RotationYToRef(angle, result);
  3236. return result;
  3237. };
  3238. /**
  3239. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3240. */
  3241. Matrix.RotationYToRef = function (angle, result) {
  3242. var s = Math.sin(angle);
  3243. var c = Math.cos(angle);
  3244. result.m[5] = 1.0;
  3245. result.m[15] = 1.0;
  3246. result.m[0] = c;
  3247. result.m[2] = -s;
  3248. result.m[8] = s;
  3249. result.m[10] = c;
  3250. result.m[1] = 0.0;
  3251. result.m[3] = 0.0;
  3252. result.m[4] = 0.0;
  3253. result.m[6] = 0.0;
  3254. result.m[7] = 0.0;
  3255. result.m[9] = 0.0;
  3256. result.m[11] = 0.0;
  3257. result.m[12] = 0.0;
  3258. result.m[13] = 0.0;
  3259. result.m[14] = 0.0;
  3260. };
  3261. /**
  3262. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3263. */
  3264. Matrix.RotationZ = function (angle) {
  3265. var result = new Matrix();
  3266. Matrix.RotationZToRef(angle, result);
  3267. return result;
  3268. };
  3269. /**
  3270. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3271. */
  3272. Matrix.RotationZToRef = function (angle, result) {
  3273. var s = Math.sin(angle);
  3274. var c = Math.cos(angle);
  3275. result.m[10] = 1.0;
  3276. result.m[15] = 1.0;
  3277. result.m[0] = c;
  3278. result.m[1] = s;
  3279. result.m[4] = -s;
  3280. result.m[5] = c;
  3281. result.m[2] = 0.0;
  3282. result.m[3] = 0.0;
  3283. result.m[6] = 0.0;
  3284. result.m[7] = 0.0;
  3285. result.m[8] = 0.0;
  3286. result.m[9] = 0.0;
  3287. result.m[11] = 0.0;
  3288. result.m[12] = 0.0;
  3289. result.m[13] = 0.0;
  3290. result.m[14] = 0.0;
  3291. };
  3292. /**
  3293. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3294. */
  3295. Matrix.RotationAxis = function (axis, angle) {
  3296. var result = Matrix.Zero();
  3297. Matrix.RotationAxisToRef(axis, angle, result);
  3298. return result;
  3299. };
  3300. /**
  3301. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3302. */
  3303. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3304. var s = Math.sin(-angle);
  3305. var c = Math.cos(-angle);
  3306. var c1 = 1 - c;
  3307. axis.normalize();
  3308. result.m[0] = (axis.x * axis.x) * c1 + c;
  3309. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3310. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3311. result.m[3] = 0.0;
  3312. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3313. result.m[5] = (axis.y * axis.y) * c1 + c;
  3314. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3315. result.m[7] = 0.0;
  3316. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3317. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3318. result.m[10] = (axis.z * axis.z) * c1 + c;
  3319. result.m[11] = 0.0;
  3320. result.m[15] = 1.0;
  3321. };
  3322. /**
  3323. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3324. */
  3325. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3326. var result = new Matrix();
  3327. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3328. return result;
  3329. };
  3330. /**
  3331. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3332. */
  3333. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3334. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3335. this._tempQuaternion.toRotationMatrix(result);
  3336. };
  3337. /**
  3338. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3339. */
  3340. Matrix.Scaling = function (x, y, z) {
  3341. var result = Matrix.Zero();
  3342. Matrix.ScalingToRef(x, y, z, result);
  3343. return result;
  3344. };
  3345. /**
  3346. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3347. */
  3348. Matrix.ScalingToRef = function (x, y, z, result) {
  3349. result.m[0] = x;
  3350. result.m[1] = 0.0;
  3351. result.m[2] = 0.0;
  3352. result.m[3] = 0.0;
  3353. result.m[4] = 0.0;
  3354. result.m[5] = y;
  3355. result.m[6] = 0.0;
  3356. result.m[7] = 0.0;
  3357. result.m[8] = 0.0;
  3358. result.m[9] = 0.0;
  3359. result.m[10] = z;
  3360. result.m[11] = 0.0;
  3361. result.m[12] = 0.0;
  3362. result.m[13] = 0.0;
  3363. result.m[14] = 0.0;
  3364. result.m[15] = 1.0;
  3365. };
  3366. /**
  3367. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3368. */
  3369. Matrix.Translation = function (x, y, z) {
  3370. var result = Matrix.Identity();
  3371. Matrix.TranslationToRef(x, y, z, result);
  3372. return result;
  3373. };
  3374. /**
  3375. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3376. */
  3377. Matrix.TranslationToRef = function (x, y, z, result) {
  3378. 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);
  3379. };
  3380. /**
  3381. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3382. */
  3383. Matrix.Lerp = function (startValue, endValue, gradient) {
  3384. var result = Matrix.Zero();
  3385. for (var index = 0; index < 16; index++) {
  3386. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3387. }
  3388. return result;
  3389. };
  3390. /**
  3391. * Returns a new Matrix whose values are computed by :
  3392. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3393. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3394. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3395. */
  3396. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3397. var startScale = new Vector3(0, 0, 0);
  3398. var startRotation = new Quaternion();
  3399. var startTranslation = new Vector3(0, 0, 0);
  3400. startValue.decompose(startScale, startRotation, startTranslation);
  3401. var endScale = new Vector3(0, 0, 0);
  3402. var endRotation = new Quaternion();
  3403. var endTranslation = new Vector3(0, 0, 0);
  3404. endValue.decompose(endScale, endRotation, endTranslation);
  3405. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3406. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3407. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3408. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3409. };
  3410. /**
  3411. * 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".
  3412. * This methods works for a Left-Handed system.
  3413. */
  3414. Matrix.LookAtLH = function (eye, target, up) {
  3415. var result = Matrix.Zero();
  3416. Matrix.LookAtLHToRef(eye, target, up, result);
  3417. return result;
  3418. };
  3419. /**
  3420. * 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".
  3421. * This methods works for a Left-Handed system.
  3422. */
  3423. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3424. // Z axis
  3425. target.subtractToRef(eye, this._zAxis);
  3426. this._zAxis.normalize();
  3427. // X axis
  3428. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3429. if (this._xAxis.lengthSquared() === 0) {
  3430. this._xAxis.x = 1.0;
  3431. }
  3432. else {
  3433. this._xAxis.normalize();
  3434. }
  3435. // Y axis
  3436. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3437. this._yAxis.normalize();
  3438. // Eye angles
  3439. var ex = -Vector3.Dot(this._xAxis, eye);
  3440. var ey = -Vector3.Dot(this._yAxis, eye);
  3441. var ez = -Vector3.Dot(this._zAxis, eye);
  3442. 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);
  3443. };
  3444. /**
  3445. * 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".
  3446. * This methods works for a Right-Handed system.
  3447. */
  3448. Matrix.LookAtRH = function (eye, target, up) {
  3449. var result = Matrix.Zero();
  3450. Matrix.LookAtRHToRef(eye, target, up, result);
  3451. return result;
  3452. };
  3453. /**
  3454. * 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".
  3455. * This methods works for a Left-Handed system.
  3456. */
  3457. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3458. // Z axis
  3459. eye.subtractToRef(target, this._zAxis);
  3460. this._zAxis.normalize();
  3461. // X axis
  3462. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3463. if (this._xAxis.lengthSquared() === 0) {
  3464. this._xAxis.x = 1.0;
  3465. }
  3466. else {
  3467. this._xAxis.normalize();
  3468. }
  3469. // Y axis
  3470. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3471. this._yAxis.normalize();
  3472. // Eye angles
  3473. var ex = -Vector3.Dot(this._xAxis, eye);
  3474. var ey = -Vector3.Dot(this._yAxis, eye);
  3475. var ez = -Vector3.Dot(this._zAxis, eye);
  3476. 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);
  3477. };
  3478. /**
  3479. * 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.
  3480. */
  3481. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3482. var matrix = Matrix.Zero();
  3483. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3484. return matrix;
  3485. };
  3486. /**
  3487. * 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.
  3488. */
  3489. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3490. var n = znear;
  3491. var f = zfar;
  3492. var a = 2.0 / width;
  3493. var b = 2.0 / height;
  3494. var c = 2.0 / (f - n);
  3495. var d = -(f + n) / (f - n);
  3496. 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);
  3497. };
  3498. /**
  3499. * 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.
  3500. */
  3501. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3502. var matrix = Matrix.Zero();
  3503. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3504. return matrix;
  3505. };
  3506. /**
  3507. * 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.
  3508. */
  3509. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3510. var n = znear;
  3511. var f = zfar;
  3512. var a = 2.0 / (right - left);
  3513. var b = 2.0 / (top - bottom);
  3514. var c = 2.0 / (f - n);
  3515. var d = -(f + n) / (f - n);
  3516. var i0 = (left + right) / (left - right);
  3517. var i1 = (top + bottom) / (bottom - top);
  3518. 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);
  3519. };
  3520. /**
  3521. * 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.
  3522. */
  3523. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3524. var matrix = Matrix.Zero();
  3525. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3526. return matrix;
  3527. };
  3528. /**
  3529. * 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.
  3530. */
  3531. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3532. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3533. result.m[10] *= -1.0;
  3534. };
  3535. /**
  3536. * 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.
  3537. */
  3538. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3539. var matrix = Matrix.Zero();
  3540. var n = znear;
  3541. var f = zfar;
  3542. var a = 2.0 * n / width;
  3543. var b = 2.0 * n / height;
  3544. var c = (f + n) / (f - n);
  3545. var d = -2.0 * f * n / (f - n);
  3546. 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);
  3547. return matrix;
  3548. };
  3549. /**
  3550. * 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.
  3551. */
  3552. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3553. var matrix = Matrix.Zero();
  3554. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3555. return matrix;
  3556. };
  3557. /**
  3558. * 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.
  3559. */
  3560. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3561. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3562. var n = znear;
  3563. var f = zfar;
  3564. var t = 1.0 / (Math.tan(fov * 0.5));
  3565. var a = isVerticalFovFixed ? (t / aspect) : t;
  3566. var b = isVerticalFovFixed ? t : (t * aspect);
  3567. var c = (f + n) / (f - n);
  3568. var d = -2.0 * f * n / (f - n);
  3569. 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);
  3570. };
  3571. /**
  3572. * 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.
  3573. */
  3574. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3575. var matrix = Matrix.Zero();
  3576. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3577. return matrix;
  3578. };
  3579. /**
  3580. * 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.
  3581. */
  3582. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3583. //alternatively this could be expressed as:
  3584. // m = PerspectiveFovLHToRef
  3585. // m[10] *= -1.0;
  3586. // m[11] *= -1.0;
  3587. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3588. var n = znear;
  3589. var f = zfar;
  3590. var t = 1.0 / (Math.tan(fov * 0.5));
  3591. var a = isVerticalFovFixed ? (t / aspect) : t;
  3592. var b = isVerticalFovFixed ? t : (t * aspect);
  3593. var c = -(f + n) / (f - n);
  3594. var d = -2 * f * n / (f - n);
  3595. 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);
  3596. };
  3597. /**
  3598. * 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.
  3599. */
  3600. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3601. if (rightHanded === void 0) { rightHanded = false; }
  3602. var rightHandedFactor = rightHanded ? -1 : 1;
  3603. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3604. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3605. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3606. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3607. var xScale = 2.0 / (leftTan + rightTan);
  3608. var yScale = 2.0 / (upTan + downTan);
  3609. result.m[0] = xScale;
  3610. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3611. result.m[5] = yScale;
  3612. result.m[6] = result.m[7] = 0.0;
  3613. result.m[8] = ((leftTan - rightTan) * xScale * 0.5) * rightHandedFactor;
  3614. result.m[9] = -((upTan - downTan) * yScale * 0.5) * rightHandedFactor;
  3615. result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3616. // result.m[10] = -zfar / (znear - zfar);
  3617. result.m[11] = 1.0 * rightHandedFactor;
  3618. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3619. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3620. // result.m[14] = (znear * zfar) / (znear - zfar);
  3621. };
  3622. /**
  3623. * Returns the final transformation matrix : world * view * projection * viewport
  3624. */
  3625. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3626. var cw = viewport.width;
  3627. var ch = viewport.height;
  3628. var cx = viewport.x;
  3629. var cy = viewport.y;
  3630. 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);
  3631. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3632. };
  3633. /**
  3634. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3635. */
  3636. Matrix.GetAsMatrix2x2 = function (matrix) {
  3637. return new Float32Array([
  3638. matrix.m[0], matrix.m[1],
  3639. matrix.m[4], matrix.m[5]
  3640. ]);
  3641. };
  3642. /**
  3643. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3644. */
  3645. Matrix.GetAsMatrix3x3 = function (matrix) {
  3646. return new Float32Array([
  3647. matrix.m[0], matrix.m[1], matrix.m[2],
  3648. matrix.m[4], matrix.m[5], matrix.m[6],
  3649. matrix.m[8], matrix.m[9], matrix.m[10]
  3650. ]);
  3651. };
  3652. /**
  3653. * Compute the transpose of the passed Matrix.
  3654. * Returns a new Matrix.
  3655. */
  3656. Matrix.Transpose = function (matrix) {
  3657. var result = new Matrix();
  3658. result.m[0] = matrix.m[0];
  3659. result.m[1] = matrix.m[4];
  3660. result.m[2] = matrix.m[8];
  3661. result.m[3] = matrix.m[12];
  3662. result.m[4] = matrix.m[1];
  3663. result.m[5] = matrix.m[5];
  3664. result.m[6] = matrix.m[9];
  3665. result.m[7] = matrix.m[13];
  3666. result.m[8] = matrix.m[2];
  3667. result.m[9] = matrix.m[6];
  3668. result.m[10] = matrix.m[10];
  3669. result.m[11] = matrix.m[14];
  3670. result.m[12] = matrix.m[3];
  3671. result.m[13] = matrix.m[7];
  3672. result.m[14] = matrix.m[11];
  3673. result.m[15] = matrix.m[15];
  3674. return result;
  3675. };
  3676. /**
  3677. * Returns a new Matrix as the reflection matrix across the passed plane.
  3678. */
  3679. Matrix.Reflection = function (plane) {
  3680. var matrix = new Matrix();
  3681. Matrix.ReflectionToRef(plane, matrix);
  3682. return matrix;
  3683. };
  3684. /**
  3685. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3686. */
  3687. Matrix.ReflectionToRef = function (plane, result) {
  3688. plane.normalize();
  3689. var x = plane.normal.x;
  3690. var y = plane.normal.y;
  3691. var z = plane.normal.z;
  3692. var temp = -2 * x;
  3693. var temp2 = -2 * y;
  3694. var temp3 = -2 * z;
  3695. result.m[0] = (temp * x) + 1;
  3696. result.m[1] = temp2 * x;
  3697. result.m[2] = temp3 * x;
  3698. result.m[3] = 0.0;
  3699. result.m[4] = temp * y;
  3700. result.m[5] = (temp2 * y) + 1;
  3701. result.m[6] = temp3 * y;
  3702. result.m[7] = 0.0;
  3703. result.m[8] = temp * z;
  3704. result.m[9] = temp2 * z;
  3705. result.m[10] = (temp3 * z) + 1;
  3706. result.m[11] = 0.0;
  3707. result.m[12] = temp * plane.d;
  3708. result.m[13] = temp2 * plane.d;
  3709. result.m[14] = temp3 * plane.d;
  3710. result.m[15] = 1.0;
  3711. };
  3712. /**
  3713. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3714. */
  3715. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  3716. mat.m[0] = xaxis.x;
  3717. mat.m[1] = xaxis.y;
  3718. mat.m[2] = xaxis.z;
  3719. mat.m[3] = 0.0;
  3720. mat.m[4] = yaxis.x;
  3721. mat.m[5] = yaxis.y;
  3722. mat.m[6] = yaxis.z;
  3723. mat.m[7] = 0.0;
  3724. mat.m[8] = zaxis.x;
  3725. mat.m[9] = zaxis.y;
  3726. mat.m[10] = zaxis.z;
  3727. mat.m[11] = 0.0;
  3728. mat.m[12] = 0.0;
  3729. mat.m[13] = 0.0;
  3730. mat.m[14] = 0.0;
  3731. mat.m[15] = 1.0;
  3732. };
  3733. /**
  3734. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3735. */
  3736. Matrix.FromQuaternionToRef = function (quat, result) {
  3737. var xx = quat.x * quat.x;
  3738. var yy = quat.y * quat.y;
  3739. var zz = quat.z * quat.z;
  3740. var xy = quat.x * quat.y;
  3741. var zw = quat.z * quat.w;
  3742. var zx = quat.z * quat.x;
  3743. var yw = quat.y * quat.w;
  3744. var yz = quat.y * quat.z;
  3745. var xw = quat.x * quat.w;
  3746. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3747. result.m[1] = 2.0 * (xy + zw);
  3748. result.m[2] = 2.0 * (zx - yw);
  3749. result.m[3] = 0.0;
  3750. result.m[4] = 2.0 * (xy - zw);
  3751. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3752. result.m[6] = 2.0 * (yz + xw);
  3753. result.m[7] = 0.0;
  3754. result.m[8] = 2.0 * (zx + yw);
  3755. result.m[9] = 2.0 * (yz - xw);
  3756. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3757. result.m[11] = 0.0;
  3758. result.m[12] = 0.0;
  3759. result.m[13] = 0.0;
  3760. result.m[14] = 0.0;
  3761. result.m[15] = 1.0;
  3762. };
  3763. return Matrix;
  3764. }());
  3765. Matrix._tempQuaternion = new Quaternion();
  3766. Matrix._xAxis = Vector3.Zero();
  3767. Matrix._yAxis = Vector3.Zero();
  3768. Matrix._zAxis = Vector3.Zero();
  3769. BABYLON.Matrix = Matrix;
  3770. var Plane = (function () {
  3771. /**
  3772. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3773. */
  3774. function Plane(a, b, c, d) {
  3775. this.normal = new Vector3(a, b, c);
  3776. this.d = d;
  3777. }
  3778. /**
  3779. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3780. */
  3781. Plane.prototype.asArray = function () {
  3782. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3783. };
  3784. // Methods
  3785. /**
  3786. * Returns a new plane copied from the current Plane.
  3787. */
  3788. Plane.prototype.clone = function () {
  3789. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3790. };
  3791. /**
  3792. * Returns the string "Plane".
  3793. */
  3794. Plane.prototype.getClassName = function () {
  3795. return "Plane";
  3796. };
  3797. /**
  3798. * Returns the Plane hash code.
  3799. */
  3800. Plane.prototype.getHashCode = function () {
  3801. var hash = this.normal.getHashCode();
  3802. hash = (hash * 397) ^ (this.d || 0);
  3803. return hash;
  3804. };
  3805. /**
  3806. * Normalize the current Plane in place.
  3807. * Returns the updated Plane.
  3808. */
  3809. Plane.prototype.normalize = function () {
  3810. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3811. var magnitude = 0.0;
  3812. if (norm !== 0) {
  3813. magnitude = 1.0 / norm;
  3814. }
  3815. this.normal.x *= magnitude;
  3816. this.normal.y *= magnitude;
  3817. this.normal.z *= magnitude;
  3818. this.d *= magnitude;
  3819. return this;
  3820. };
  3821. /**
  3822. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3823. */
  3824. Plane.prototype.transform = function (transformation) {
  3825. var transposedMatrix = Matrix.Transpose(transformation);
  3826. var x = this.normal.x;
  3827. var y = this.normal.y;
  3828. var z = this.normal.z;
  3829. var d = this.d;
  3830. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3831. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3832. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3833. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3834. return new Plane(normalX, normalY, normalZ, finalD);
  3835. };
  3836. /**
  3837. * Returns the dot product (float) of the point coordinates and the plane normal.
  3838. */
  3839. Plane.prototype.dotCoordinate = function (point) {
  3840. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3841. };
  3842. /**
  3843. * Updates the current Plane from the plane defined by the three passed points.
  3844. * Returns the updated Plane.
  3845. */
  3846. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3847. var x1 = point2.x - point1.x;
  3848. var y1 = point2.y - point1.y;
  3849. var z1 = point2.z - point1.z;
  3850. var x2 = point3.x - point1.x;
  3851. var y2 = point3.y - point1.y;
  3852. var z2 = point3.z - point1.z;
  3853. var yz = (y1 * z2) - (z1 * y2);
  3854. var xz = (z1 * x2) - (x1 * z2);
  3855. var xy = (x1 * y2) - (y1 * x2);
  3856. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3857. var invPyth;
  3858. if (pyth !== 0) {
  3859. invPyth = 1.0 / pyth;
  3860. }
  3861. else {
  3862. invPyth = 0.0;
  3863. }
  3864. this.normal.x = yz * invPyth;
  3865. this.normal.y = xz * invPyth;
  3866. this.normal.z = xy * invPyth;
  3867. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3868. return this;
  3869. };
  3870. /**
  3871. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3872. */
  3873. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3874. var dot = Vector3.Dot(this.normal, direction);
  3875. return (dot <= epsilon);
  3876. };
  3877. /**
  3878. * Returns the signed distance (float) from the passed point to the Plane.
  3879. */
  3880. Plane.prototype.signedDistanceTo = function (point) {
  3881. return Vector3.Dot(point, this.normal) + this.d;
  3882. };
  3883. // Statics
  3884. /**
  3885. * Returns a new Plane from the passed array.
  3886. */
  3887. Plane.FromArray = function (array) {
  3888. return new Plane(array[0], array[1], array[2], array[3]);
  3889. };
  3890. /**
  3891. * Returns a new Plane defined by the three passed points.
  3892. */
  3893. Plane.FromPoints = function (point1, point2, point3) {
  3894. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3895. result.copyFromPoints(point1, point2, point3);
  3896. return result;
  3897. };
  3898. /**
  3899. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3900. * Note : the vector "normal" is updated because normalized.
  3901. */
  3902. Plane.FromPositionAndNormal = function (origin, normal) {
  3903. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3904. normal.normalize();
  3905. result.normal = normal;
  3906. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3907. return result;
  3908. };
  3909. /**
  3910. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3911. */
  3912. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3913. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3914. return Vector3.Dot(point, normal) + d;
  3915. };
  3916. return Plane;
  3917. }());
  3918. BABYLON.Plane = Plane;
  3919. var Viewport = (function () {
  3920. /**
  3921. * Creates a Viewport object located at (x, y) and sized (width, height).
  3922. */
  3923. function Viewport(x, y, width, height) {
  3924. this.x = x;
  3925. this.y = y;
  3926. this.width = width;
  3927. this.height = height;
  3928. }
  3929. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3930. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3931. };
  3932. /**
  3933. * Returns a new Viewport copied from the current one.
  3934. */
  3935. Viewport.prototype.clone = function () {
  3936. return new Viewport(this.x, this.y, this.width, this.height);
  3937. };
  3938. return Viewport;
  3939. }());
  3940. BABYLON.Viewport = Viewport;
  3941. var Frustum = (function () {
  3942. function Frustum() {
  3943. }
  3944. /**
  3945. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  3946. */
  3947. Frustum.GetPlanes = function (transform) {
  3948. var frustumPlanes = [];
  3949. for (var index = 0; index < 6; index++) {
  3950. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  3951. }
  3952. Frustum.GetPlanesToRef(transform, frustumPlanes);
  3953. return frustumPlanes;
  3954. };
  3955. /**
  3956. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  3957. */
  3958. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  3959. // Near
  3960. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  3961. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  3962. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  3963. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  3964. frustumPlanes[0].normalize();
  3965. // Far
  3966. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  3967. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  3968. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  3969. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  3970. frustumPlanes[1].normalize();
  3971. // Left
  3972. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  3973. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  3974. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  3975. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  3976. frustumPlanes[2].normalize();
  3977. // Right
  3978. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  3979. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  3980. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  3981. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  3982. frustumPlanes[3].normalize();
  3983. // Top
  3984. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  3985. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  3986. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  3987. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  3988. frustumPlanes[4].normalize();
  3989. // Bottom
  3990. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  3991. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  3992. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  3993. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  3994. frustumPlanes[5].normalize();
  3995. };
  3996. return Frustum;
  3997. }());
  3998. BABYLON.Frustum = Frustum;
  3999. var Space;
  4000. (function (Space) {
  4001. Space[Space["LOCAL"] = 0] = "LOCAL";
  4002. Space[Space["WORLD"] = 1] = "WORLD";
  4003. Space[Space["BONE"] = 2] = "BONE";
  4004. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4005. var Axis = (function () {
  4006. function Axis() {
  4007. }
  4008. return Axis;
  4009. }());
  4010. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4011. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4012. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4013. BABYLON.Axis = Axis;
  4014. ;
  4015. var BezierCurve = (function () {
  4016. function BezierCurve() {
  4017. }
  4018. /**
  4019. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4020. */
  4021. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4022. // Extract X (which is equal to time here)
  4023. var f0 = 1 - 3 * x2 + 3 * x1;
  4024. var f1 = 3 * x2 - 6 * x1;
  4025. var f2 = 3 * x1;
  4026. var refinedT = t;
  4027. for (var i = 0; i < 5; i++) {
  4028. var refinedT2 = refinedT * refinedT;
  4029. var refinedT3 = refinedT2 * refinedT;
  4030. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4031. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4032. refinedT -= (x - t) * slope;
  4033. refinedT = Math.min(1, Math.max(0, refinedT));
  4034. }
  4035. // Resolve cubic bezier for the given x
  4036. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4037. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4038. Math.pow(refinedT, 3);
  4039. };
  4040. return BezierCurve;
  4041. }());
  4042. BABYLON.BezierCurve = BezierCurve;
  4043. var Orientation;
  4044. (function (Orientation) {
  4045. Orientation[Orientation["CW"] = 0] = "CW";
  4046. Orientation[Orientation["CCW"] = 1] = "CCW";
  4047. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4048. var Angle = (function () {
  4049. /**
  4050. * Creates an Angle object of "radians" radians (float).
  4051. */
  4052. function Angle(radians) {
  4053. var _this = this;
  4054. /**
  4055. * Returns the Angle value in degrees (float).
  4056. */
  4057. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4058. /**
  4059. * Returns the Angle value in radians (float).
  4060. */
  4061. this.radians = function () { return _this._radians; };
  4062. this._radians = radians;
  4063. if (this._radians < 0.0)
  4064. this._radians += (2.0 * Math.PI);
  4065. }
  4066. /**
  4067. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4068. */
  4069. Angle.BetweenTwoPoints = function (a, b) {
  4070. var delta = b.subtract(a);
  4071. var theta = Math.atan2(delta.y, delta.x);
  4072. return new Angle(theta);
  4073. };
  4074. /**
  4075. * Returns a new Angle object from the passed float in radians.
  4076. */
  4077. Angle.FromRadians = function (radians) {
  4078. return new Angle(radians);
  4079. };
  4080. /**
  4081. * Returns a new Angle object from the passed float in degrees.
  4082. */
  4083. Angle.FromDegrees = function (degrees) {
  4084. return new Angle(degrees * Math.PI / 180.0);
  4085. };
  4086. return Angle;
  4087. }());
  4088. BABYLON.Angle = Angle;
  4089. var Arc2 = (function () {
  4090. /**
  4091. * Creates an Arc object from the three passed points : start, middle and end.
  4092. */
  4093. function Arc2(startPoint, midPoint, endPoint) {
  4094. this.startPoint = startPoint;
  4095. this.midPoint = midPoint;
  4096. this.endPoint = endPoint;
  4097. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4098. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4099. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4100. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4101. 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);
  4102. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4103. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4104. var a1 = this.startAngle.degrees();
  4105. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4106. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4107. // angles correction
  4108. if (a2 - a1 > +180.0)
  4109. a2 -= 360.0;
  4110. if (a2 - a1 < -180.0)
  4111. a2 += 360.0;
  4112. if (a3 - a2 > +180.0)
  4113. a3 -= 360.0;
  4114. if (a3 - a2 < -180.0)
  4115. a3 += 360.0;
  4116. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4117. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4118. }
  4119. return Arc2;
  4120. }());
  4121. BABYLON.Arc2 = Arc2;
  4122. var Path2 = (function () {
  4123. /**
  4124. * Creates a Path2 object from the starting 2D coordinates x and y.
  4125. */
  4126. function Path2(x, y) {
  4127. this._points = new Array();
  4128. this._length = 0.0;
  4129. this.closed = false;
  4130. this._points.push(new Vector2(x, y));
  4131. }
  4132. /**
  4133. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4134. * Returns the updated Path2.
  4135. */
  4136. Path2.prototype.addLineTo = function (x, y) {
  4137. if (closed) {
  4138. //Tools.Error("cannot add lines to closed paths");
  4139. return this;
  4140. }
  4141. var newPoint = new Vector2(x, y);
  4142. var previousPoint = this._points[this._points.length - 1];
  4143. this._points.push(newPoint);
  4144. this._length += newPoint.subtract(previousPoint).length();
  4145. return this;
  4146. };
  4147. /**
  4148. * 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.
  4149. * Returns the updated Path2.
  4150. */
  4151. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4152. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4153. if (closed) {
  4154. //Tools.Error("cannot add arcs to closed paths");
  4155. return this;
  4156. }
  4157. var startPoint = this._points[this._points.length - 1];
  4158. var midPoint = new Vector2(midX, midY);
  4159. var endPoint = new Vector2(endX, endY);
  4160. var arc = new Arc2(startPoint, midPoint, endPoint);
  4161. var increment = arc.angle.radians() / numberOfSegments;
  4162. if (arc.orientation === Orientation.CW)
  4163. increment *= -1;
  4164. var currentAngle = arc.startAngle.radians() + increment;
  4165. for (var i = 0; i < numberOfSegments; i++) {
  4166. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4167. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4168. this.addLineTo(x, y);
  4169. currentAngle += increment;
  4170. }
  4171. return this;
  4172. };
  4173. /**
  4174. * Closes the Path2.
  4175. * Returns the Path2.
  4176. */
  4177. Path2.prototype.close = function () {
  4178. this.closed = true;
  4179. return this;
  4180. };
  4181. /**
  4182. * Returns the Path2 total length (float).
  4183. */
  4184. Path2.prototype.length = function () {
  4185. var result = this._length;
  4186. if (!this.closed) {
  4187. var lastPoint = this._points[this._points.length - 1];
  4188. var firstPoint = this._points[0];
  4189. result += (firstPoint.subtract(lastPoint).length());
  4190. }
  4191. return result;
  4192. };
  4193. /**
  4194. * Returns the Path2 internal array of points.
  4195. */
  4196. Path2.prototype.getPoints = function () {
  4197. return this._points;
  4198. };
  4199. /**
  4200. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4201. */
  4202. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4203. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4204. //Tools.Error("normalized length position should be between 0 and 1.");
  4205. return Vector2.Zero();
  4206. }
  4207. var lengthPosition = normalizedLengthPosition * this.length();
  4208. var previousOffset = 0;
  4209. for (var i = 0; i < this._points.length; i++) {
  4210. var j = (i + 1) % this._points.length;
  4211. var a = this._points[i];
  4212. var b = this._points[j];
  4213. var bToA = b.subtract(a);
  4214. var nextOffset = (bToA.length() + previousOffset);
  4215. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4216. var dir = bToA.normalize();
  4217. var localOffset = lengthPosition - previousOffset;
  4218. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4219. }
  4220. previousOffset = nextOffset;
  4221. }
  4222. //Tools.Error("internal error");
  4223. return Vector2.Zero();
  4224. };
  4225. /**
  4226. * Returns a new Path2 starting at the coordinates (x, y).
  4227. */
  4228. Path2.StartingAt = function (x, y) {
  4229. return new Path2(x, y);
  4230. };
  4231. return Path2;
  4232. }());
  4233. BABYLON.Path2 = Path2;
  4234. var Path3D = (function () {
  4235. /**
  4236. * new Path3D(path, normal, raw)
  4237. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4238. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4239. * path : an array of Vector3, the curve axis of the Path3D
  4240. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4241. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4242. */
  4243. function Path3D(path, firstNormal, raw) {
  4244. this.path = path;
  4245. this._curve = new Array();
  4246. this._distances = new Array();
  4247. this._tangents = new Array();
  4248. this._normals = new Array();
  4249. this._binormals = new Array();
  4250. for (var p = 0; p < path.length; p++) {
  4251. this._curve[p] = path[p].clone(); // hard copy
  4252. }
  4253. this._raw = raw || false;
  4254. this._compute(firstNormal);
  4255. }
  4256. /**
  4257. * Returns the Path3D array of successive Vector3 designing its curve.
  4258. */
  4259. Path3D.prototype.getCurve = function () {
  4260. return this._curve;
  4261. };
  4262. /**
  4263. * Returns an array populated with tangent vectors on each Path3D curve point.
  4264. */
  4265. Path3D.prototype.getTangents = function () {
  4266. return this._tangents;
  4267. };
  4268. /**
  4269. * Returns an array populated with normal vectors on each Path3D curve point.
  4270. */
  4271. Path3D.prototype.getNormals = function () {
  4272. return this._normals;
  4273. };
  4274. /**
  4275. * Returns an array populated with binormal vectors on each Path3D curve point.
  4276. */
  4277. Path3D.prototype.getBinormals = function () {
  4278. return this._binormals;
  4279. };
  4280. /**
  4281. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4282. */
  4283. Path3D.prototype.getDistances = function () {
  4284. return this._distances;
  4285. };
  4286. /**
  4287. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4288. * Returns the same object updated.
  4289. */
  4290. Path3D.prototype.update = function (path, firstNormal) {
  4291. for (var p = 0; p < path.length; p++) {
  4292. this._curve[p].x = path[p].x;
  4293. this._curve[p].y = path[p].y;
  4294. this._curve[p].z = path[p].z;
  4295. }
  4296. this._compute(firstNormal);
  4297. return this;
  4298. };
  4299. // private function compute() : computes tangents, normals and binormals
  4300. Path3D.prototype._compute = function (firstNormal) {
  4301. var l = this._curve.length;
  4302. // first and last tangents
  4303. this._tangents[0] = this._getFirstNonNullVector(0);
  4304. if (!this._raw) {
  4305. this._tangents[0].normalize();
  4306. }
  4307. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4308. if (!this._raw) {
  4309. this._tangents[l - 1].normalize();
  4310. }
  4311. // normals and binormals at first point : arbitrary vector with _normalVector()
  4312. var tg0 = this._tangents[0];
  4313. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4314. this._normals[0] = pp0;
  4315. if (!this._raw) {
  4316. this._normals[0].normalize();
  4317. }
  4318. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4319. if (!this._raw) {
  4320. this._binormals[0].normalize();
  4321. }
  4322. this._distances[0] = 0.0;
  4323. // normals and binormals : next points
  4324. var prev; // previous vector (segment)
  4325. var cur; // current vector (segment)
  4326. var curTang; // current tangent
  4327. // previous normal
  4328. var prevBinor; // previous binormal
  4329. for (var i = 1; i < l; i++) {
  4330. // tangents
  4331. prev = this._getLastNonNullVector(i);
  4332. if (i < l - 1) {
  4333. cur = this._getFirstNonNullVector(i);
  4334. this._tangents[i] = prev.add(cur);
  4335. this._tangents[i].normalize();
  4336. }
  4337. this._distances[i] = this._distances[i - 1] + prev.length();
  4338. // normals and binormals
  4339. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4340. curTang = this._tangents[i];
  4341. prevBinor = this._binormals[i - 1];
  4342. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4343. if (!this._raw) {
  4344. this._normals[i].normalize();
  4345. }
  4346. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4347. if (!this._raw) {
  4348. this._binormals[i].normalize();
  4349. }
  4350. }
  4351. };
  4352. // private function getFirstNonNullVector(index)
  4353. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4354. Path3D.prototype._getFirstNonNullVector = function (index) {
  4355. var i = 1;
  4356. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4357. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4358. i++;
  4359. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4360. }
  4361. return nNVector;
  4362. };
  4363. // private function getLastNonNullVector(index)
  4364. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4365. Path3D.prototype._getLastNonNullVector = function (index) {
  4366. var i = 1;
  4367. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4368. while (nLVector.length() === 0 && index > i + 1) {
  4369. i++;
  4370. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4371. }
  4372. return nLVector;
  4373. };
  4374. // private function normalVector(v0, vt, va) :
  4375. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4376. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4377. Path3D.prototype._normalVector = function (v0, vt, va) {
  4378. var normal0;
  4379. var tgl = vt.length();
  4380. if (tgl === 0.0) {
  4381. tgl = 1.0;
  4382. }
  4383. if (va === undefined || va === null) {
  4384. var point;
  4385. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4386. point = new Vector3(0.0, -1.0, 0.0);
  4387. }
  4388. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4389. point = new Vector3(1.0, 0.0, 0.0);
  4390. }
  4391. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4392. point = new Vector3(0.0, 0.0, 1.0);
  4393. }
  4394. normal0 = Vector3.Cross(vt, point);
  4395. }
  4396. else {
  4397. normal0 = Vector3.Cross(vt, va);
  4398. Vector3.CrossToRef(normal0, vt, normal0);
  4399. }
  4400. normal0.normalize();
  4401. return normal0;
  4402. };
  4403. return Path3D;
  4404. }());
  4405. BABYLON.Path3D = Path3D;
  4406. var Curve3 = (function () {
  4407. /**
  4408. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4409. * A Curve3 is designed from a series of successive Vector3.
  4410. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4411. */
  4412. function Curve3(points) {
  4413. this._length = 0.0;
  4414. this._points = points;
  4415. this._length = this._computeLength(points);
  4416. }
  4417. /**
  4418. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4419. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4420. * @param v1 (Vector3) the control point
  4421. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4422. * @param nbPoints (integer) the wanted number of points in the curve
  4423. */
  4424. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4425. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4426. var bez = new Array();
  4427. var equation = function (t, val0, val1, val2) {
  4428. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4429. return res;
  4430. };
  4431. for (var i = 0; i <= nbPoints; i++) {
  4432. 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)));
  4433. }
  4434. return new Curve3(bez);
  4435. };
  4436. /**
  4437. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4438. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4439. * @param v1 (Vector3) the first control point
  4440. * @param v2 (Vector3) the second control point
  4441. * @param v3 (Vector3) the end point of the Cubic Bezier
  4442. * @param nbPoints (integer) the wanted number of points in the curve
  4443. */
  4444. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4445. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4446. var bez = new Array();
  4447. var equation = function (t, val0, val1, val2, val3) {
  4448. 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;
  4449. return res;
  4450. };
  4451. for (var i = 0; i <= nbPoints; i++) {
  4452. 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)));
  4453. }
  4454. return new Curve3(bez);
  4455. };
  4456. /**
  4457. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4458. * @param p1 (Vector3) the origin point of the Hermite Spline
  4459. * @param t1 (Vector3) the tangent vector at the origin point
  4460. * @param p2 (Vector3) the end point of the Hermite Spline
  4461. * @param t2 (Vector3) the tangent vector at the end point
  4462. * @param nbPoints (integer) the wanted number of points in the curve
  4463. */
  4464. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4465. var hermite = new Array();
  4466. var step = 1.0 / nbPoints;
  4467. for (var i = 0; i <= nbPoints; i++) {
  4468. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4469. }
  4470. return new Curve3(hermite);
  4471. };
  4472. /**
  4473. * Returns a Curve3 object along a CatmullRom Spline curve :
  4474. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4475. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4476. */
  4477. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4478. var totalPoints = new Array();
  4479. totalPoints.push(points[0].clone());
  4480. Array.prototype.push.apply(totalPoints, points);
  4481. totalPoints.push(points[points.length - 1].clone());
  4482. var catmullRom = new Array();
  4483. var step = 1.0 / nbPoints;
  4484. for (var i = 0; i < totalPoints.length - 3; i++) {
  4485. var amount = 0.0;
  4486. for (var c = 0; c < nbPoints; c++) {
  4487. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4488. amount += step;
  4489. }
  4490. }
  4491. i--;
  4492. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4493. return new Curve3(catmullRom);
  4494. };
  4495. /**
  4496. * Returns the Curve3 stored array of successive Vector3
  4497. */
  4498. Curve3.prototype.getPoints = function () {
  4499. return this._points;
  4500. };
  4501. /**
  4502. * Returns the computed length (float) of the curve.
  4503. */
  4504. Curve3.prototype.length = function () {
  4505. return this._length;
  4506. };
  4507. /**
  4508. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4509. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4510. * curveA and curveB keep unchanged.
  4511. */
  4512. Curve3.prototype.continue = function (curve) {
  4513. var lastPoint = this._points[this._points.length - 1];
  4514. var continuedPoints = this._points.slice();
  4515. var curvePoints = curve.getPoints();
  4516. for (var i = 1; i < curvePoints.length; i++) {
  4517. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4518. }
  4519. var continuedCurve = new Curve3(continuedPoints);
  4520. return continuedCurve;
  4521. };
  4522. Curve3.prototype._computeLength = function (path) {
  4523. var l = 0;
  4524. for (var i = 1; i < path.length; i++) {
  4525. l += (path[i].subtract(path[i - 1])).length();
  4526. }
  4527. return l;
  4528. };
  4529. return Curve3;
  4530. }());
  4531. BABYLON.Curve3 = Curve3;
  4532. // SphericalHarmonics
  4533. var SphericalHarmonics = (function () {
  4534. function SphericalHarmonics() {
  4535. this.L00 = Vector3.Zero();
  4536. this.L1_1 = Vector3.Zero();
  4537. this.L10 = Vector3.Zero();
  4538. this.L11 = Vector3.Zero();
  4539. this.L2_2 = Vector3.Zero();
  4540. this.L2_1 = Vector3.Zero();
  4541. this.L20 = Vector3.Zero();
  4542. this.L21 = Vector3.Zero();
  4543. this.L22 = Vector3.Zero();
  4544. }
  4545. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4546. var colorVector = new Vector3(color.r, color.g, color.b);
  4547. var c = colorVector.scale(deltaSolidAngle);
  4548. this.L00 = this.L00.add(c.scale(0.282095));
  4549. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4550. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4551. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4552. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4553. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4554. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4555. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4556. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4557. };
  4558. SphericalHarmonics.prototype.scale = function (scale) {
  4559. this.L00 = this.L00.scale(scale);
  4560. this.L1_1 = this.L1_1.scale(scale);
  4561. this.L10 = this.L10.scale(scale);
  4562. this.L11 = this.L11.scale(scale);
  4563. this.L2_2 = this.L2_2.scale(scale);
  4564. this.L2_1 = this.L2_1.scale(scale);
  4565. this.L20 = this.L20.scale(scale);
  4566. this.L21 = this.L21.scale(scale);
  4567. this.L22 = this.L22.scale(scale);
  4568. };
  4569. return SphericalHarmonics;
  4570. }());
  4571. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4572. // SphericalPolynomial
  4573. var SphericalPolynomial = (function () {
  4574. function SphericalPolynomial() {
  4575. this.x = Vector3.Zero();
  4576. this.y = Vector3.Zero();
  4577. this.z = Vector3.Zero();
  4578. this.xx = Vector3.Zero();
  4579. this.yy = Vector3.Zero();
  4580. this.zz = Vector3.Zero();
  4581. this.xy = Vector3.Zero();
  4582. this.yz = Vector3.Zero();
  4583. this.zx = Vector3.Zero();
  4584. }
  4585. SphericalPolynomial.prototype.addAmbient = function (color) {
  4586. var colorVector = new Vector3(color.r, color.g, color.b);
  4587. this.xx = this.xx.add(colorVector);
  4588. this.yy = this.yy.add(colorVector);
  4589. this.zz = this.zz.add(colorVector);
  4590. };
  4591. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4592. var result = new SphericalPolynomial();
  4593. result.x = harmonics.L11.scale(1.02333);
  4594. result.y = harmonics.L1_1.scale(1.02333);
  4595. result.z = harmonics.L10.scale(1.02333);
  4596. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4597. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4598. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4599. result.yz = harmonics.L2_1.scale(0.858086);
  4600. result.zx = harmonics.L21.scale(0.858086);
  4601. result.xy = harmonics.L2_2.scale(0.858086);
  4602. return result;
  4603. };
  4604. return SphericalPolynomial;
  4605. }());
  4606. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4607. // Vertex formats
  4608. var PositionNormalVertex = (function () {
  4609. function PositionNormalVertex(position, normal) {
  4610. if (position === void 0) { position = Vector3.Zero(); }
  4611. if (normal === void 0) { normal = Vector3.Up(); }
  4612. this.position = position;
  4613. this.normal = normal;
  4614. }
  4615. PositionNormalVertex.prototype.clone = function () {
  4616. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4617. };
  4618. return PositionNormalVertex;
  4619. }());
  4620. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4621. var PositionNormalTextureVertex = (function () {
  4622. function PositionNormalTextureVertex(position, normal, uv) {
  4623. if (position === void 0) { position = Vector3.Zero(); }
  4624. if (normal === void 0) { normal = Vector3.Up(); }
  4625. if (uv === void 0) { uv = Vector2.Zero(); }
  4626. this.position = position;
  4627. this.normal = normal;
  4628. this.uv = uv;
  4629. }
  4630. PositionNormalTextureVertex.prototype.clone = function () {
  4631. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4632. };
  4633. return PositionNormalTextureVertex;
  4634. }());
  4635. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4636. // Temporary pre-allocated objects for engine internal use
  4637. // usage in any internal function :
  4638. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4639. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4640. var Tmp = (function () {
  4641. function Tmp() {
  4642. }
  4643. return Tmp;
  4644. }());
  4645. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4646. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4647. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4648. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4649. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4650. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4651. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4652. Matrix.Zero(), Matrix.Zero(),
  4653. Matrix.Zero(), Matrix.Zero(),
  4654. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4655. BABYLON.Tmp = Tmp;
  4656. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4657. var MathTmp = (function () {
  4658. function MathTmp() {
  4659. }
  4660. return MathTmp;
  4661. }());
  4662. MathTmp.Vector3 = [Vector3.Zero()];
  4663. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4664. MathTmp.Quaternion = [Quaternion.Zero()];
  4665. })(BABYLON || (BABYLON = {}));
  4666. //# sourceMappingURL=babylon.math.js.map
  4667. //# sourceMappingURL=babylon.mixins.js.map
  4668. var BABYLON;
  4669. (function (BABYLON) {
  4670. function generateSerializableMember(type, sourceName) {
  4671. return function (target, propertyKey) {
  4672. if (!target.__serializableMembers) {
  4673. target.__serializableMembers = {};
  4674. }
  4675. if (!target.__serializableMembers[propertyKey]) {
  4676. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4677. }
  4678. };
  4679. }
  4680. function serialize(sourceName) {
  4681. return generateSerializableMember(0, sourceName); // value member
  4682. }
  4683. BABYLON.serialize = serialize;
  4684. function serializeAsTexture(sourceName) {
  4685. return generateSerializableMember(1, sourceName); // texture member
  4686. }
  4687. BABYLON.serializeAsTexture = serializeAsTexture;
  4688. function serializeAsColor3(sourceName) {
  4689. return generateSerializableMember(2, sourceName); // color3 member
  4690. }
  4691. BABYLON.serializeAsColor3 = serializeAsColor3;
  4692. function serializeAsFresnelParameters(sourceName) {
  4693. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4694. }
  4695. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4696. function serializeAsVector2(sourceName) {
  4697. return generateSerializableMember(4, sourceName); // vector2 member
  4698. }
  4699. BABYLON.serializeAsVector2 = serializeAsVector2;
  4700. function serializeAsVector3(sourceName) {
  4701. return generateSerializableMember(5, sourceName); // vector3 member
  4702. }
  4703. BABYLON.serializeAsVector3 = serializeAsVector3;
  4704. function serializeAsMeshReference(sourceName) {
  4705. return generateSerializableMember(6, sourceName); // mesh reference member
  4706. }
  4707. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4708. function serializeAsColorCurves(sourceName) {
  4709. return generateSerializableMember(7, sourceName); // color curves
  4710. }
  4711. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4712. var SerializationHelper = (function () {
  4713. function SerializationHelper() {
  4714. }
  4715. SerializationHelper.Serialize = function (entity, serializationObject) {
  4716. if (!serializationObject) {
  4717. serializationObject = {};
  4718. }
  4719. // Tags
  4720. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4721. // Properties
  4722. for (var property in entity.__serializableMembers) {
  4723. var propertyDescriptor = entity.__serializableMembers[property];
  4724. var targetPropertyName = propertyDescriptor.sourceName || property;
  4725. var propertyType = propertyDescriptor.type;
  4726. var sourceProperty = entity[property];
  4727. if (sourceProperty !== undefined && sourceProperty !== null) {
  4728. switch (propertyType) {
  4729. case 0:
  4730. serializationObject[targetPropertyName] = sourceProperty;
  4731. break;
  4732. case 1:
  4733. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4734. break;
  4735. case 2:
  4736. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4737. break;
  4738. case 3:
  4739. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4740. break;
  4741. case 4:
  4742. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4743. break;
  4744. case 5:
  4745. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4746. break;
  4747. case 6:
  4748. serializationObject[targetPropertyName] = sourceProperty.id;
  4749. break;
  4750. case 7:
  4751. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4752. break;
  4753. }
  4754. }
  4755. }
  4756. return serializationObject;
  4757. };
  4758. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4759. var destination = creationFunction();
  4760. // Tags
  4761. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4762. // Properties
  4763. for (var property in destination.__serializableMembers) {
  4764. var propertyDescriptor = destination.__serializableMembers[property];
  4765. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4766. var propertyType = propertyDescriptor.type;
  4767. if (sourceProperty !== undefined && sourceProperty !== null) {
  4768. switch (propertyType) {
  4769. case 0:
  4770. destination[property] = sourceProperty;
  4771. break;
  4772. case 1:
  4773. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4774. break;
  4775. case 2:
  4776. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4777. break;
  4778. case 3:
  4779. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4780. break;
  4781. case 4:
  4782. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4783. break;
  4784. case 5:
  4785. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4786. break;
  4787. case 6:
  4788. destination[property] = scene.getLastMeshByID(sourceProperty);
  4789. break;
  4790. case 7:
  4791. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4792. break;
  4793. }
  4794. }
  4795. }
  4796. return destination;
  4797. };
  4798. SerializationHelper.Clone = function (creationFunction, source) {
  4799. var destination = creationFunction();
  4800. // Tags
  4801. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4802. // Properties
  4803. for (var property in destination.__serializableMembers) {
  4804. var propertyDescriptor = destination.__serializableMembers[property];
  4805. var sourceProperty = source[property];
  4806. var propertyType = propertyDescriptor.type;
  4807. if (sourceProperty !== undefined && sourceProperty !== null) {
  4808. switch (propertyType) {
  4809. case 0: // Value
  4810. case 6:
  4811. destination[property] = sourceProperty;
  4812. break;
  4813. case 1: // Texture
  4814. case 2: // Color3
  4815. case 3: // FresnelParameters
  4816. case 4: // Vector2
  4817. case 5: // Vector3
  4818. case 7:
  4819. destination[property] = sourceProperty.clone();
  4820. break;
  4821. }
  4822. }
  4823. }
  4824. return destination;
  4825. };
  4826. return SerializationHelper;
  4827. }());
  4828. BABYLON.SerializationHelper = SerializationHelper;
  4829. })(BABYLON || (BABYLON = {}));
  4830. //# sourceMappingURL=babylon.decorators.js.map
  4831. var BABYLON;
  4832. (function (BABYLON) {
  4833. /**
  4834. * A class serves as a medium between the observable and its observers
  4835. */
  4836. var EventState = (function () {
  4837. /**
  4838. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4839. */
  4840. function EventState(mask, skipNextObservers) {
  4841. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4842. this.initalize(mask, skipNextObservers);
  4843. }
  4844. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4845. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4846. this.mask = mask;
  4847. this.skipNextObservers = skipNextObservers;
  4848. return this;
  4849. };
  4850. return EventState;
  4851. }());
  4852. BABYLON.EventState = EventState;
  4853. /**
  4854. * Represent an Observer registered to a given Observable object.
  4855. */
  4856. var Observer = (function () {
  4857. function Observer(callback, mask) {
  4858. this.callback = callback;
  4859. this.mask = mask;
  4860. }
  4861. return Observer;
  4862. }());
  4863. BABYLON.Observer = Observer;
  4864. /**
  4865. * The Observable class is a simple implementation of the Observable pattern.
  4866. * 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.
  4867. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4868. * 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).
  4869. * 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.
  4870. */
  4871. var Observable = (function () {
  4872. function Observable() {
  4873. this._observers = new Array();
  4874. this._eventState = new EventState(0);
  4875. }
  4876. /**
  4877. * Create a new Observer with the specified callback
  4878. * @param callback the callback that will be executed for that Observer
  4879. * @param mask the mask used to filter observers
  4880. * @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.
  4881. */
  4882. Observable.prototype.add = function (callback, mask, insertFirst) {
  4883. if (mask === void 0) { mask = -1; }
  4884. if (insertFirst === void 0) { insertFirst = false; }
  4885. if (!callback) {
  4886. return null;
  4887. }
  4888. var observer = new Observer(callback, mask);
  4889. if (insertFirst) {
  4890. this._observers.unshift(observer);
  4891. }
  4892. else {
  4893. this._observers.push(observer);
  4894. }
  4895. return observer;
  4896. };
  4897. /**
  4898. * Remove an Observer from the Observable object
  4899. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4900. */
  4901. Observable.prototype.remove = function (observer) {
  4902. var index = this._observers.indexOf(observer);
  4903. if (index !== -1) {
  4904. this._observers.splice(index, 1);
  4905. return true;
  4906. }
  4907. return false;
  4908. };
  4909. /**
  4910. * Remove a callback from the Observable object
  4911. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4912. */
  4913. Observable.prototype.removeCallback = function (callback) {
  4914. for (var index = 0; index < this._observers.length; index++) {
  4915. if (this._observers[index].callback === callback) {
  4916. this._observers.splice(index, 1);
  4917. return true;
  4918. }
  4919. }
  4920. return false;
  4921. };
  4922. /**
  4923. * Notify all Observers by calling their respective callback with the given data
  4924. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  4925. * @param eventData
  4926. * @param mask
  4927. */
  4928. Observable.prototype.notifyObservers = function (eventData, mask) {
  4929. if (mask === void 0) { mask = -1; }
  4930. var state = this._eventState;
  4931. state.mask = mask;
  4932. state.skipNextObservers = false;
  4933. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4934. var obs = _a[_i];
  4935. if (obs.mask & mask) {
  4936. obs.callback(eventData, state);
  4937. }
  4938. if (state.skipNextObservers) {
  4939. return false;
  4940. }
  4941. }
  4942. return true;
  4943. };
  4944. /**
  4945. * return true is the Observable has at least one Observer registered
  4946. */
  4947. Observable.prototype.hasObservers = function () {
  4948. return this._observers.length > 0;
  4949. };
  4950. /**
  4951. * Clear the list of observers
  4952. */
  4953. Observable.prototype.clear = function () {
  4954. this._observers = new Array();
  4955. };
  4956. /**
  4957. * Clone the current observable
  4958. */
  4959. Observable.prototype.clone = function () {
  4960. var result = new Observable();
  4961. result._observers = this._observers.slice(0);
  4962. return result;
  4963. };
  4964. /**
  4965. * Does this observable handles observer registered with a given mask
  4966. * @param {number} trigger - the mask to be tested
  4967. * @return {boolean} whether or not one observer registered with the given mask is handeled
  4968. **/
  4969. Observable.prototype.hasSpecificMask = function (mask) {
  4970. if (mask === void 0) { mask = -1; }
  4971. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4972. var obs = _a[_i];
  4973. if (obs.mask & mask && obs.mask === mask) {
  4974. return true;
  4975. }
  4976. }
  4977. return false;
  4978. };
  4979. return Observable;
  4980. }());
  4981. BABYLON.Observable = Observable;
  4982. })(BABYLON || (BABYLON = {}));
  4983. //# sourceMappingURL=babylon.observable.js.map
  4984. var BABYLON;
  4985. (function (BABYLON) {
  4986. var Database = (function () {
  4987. function Database(urlToScene, callbackManifestChecked) {
  4988. // Handling various flavors of prefixed version of IndexedDB
  4989. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  4990. this.callbackManifestChecked = callbackManifestChecked;
  4991. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  4992. this.db = null;
  4993. this.enableSceneOffline = false;
  4994. this.enableTexturesOffline = false;
  4995. this.manifestVersionFound = 0;
  4996. this.mustUpdateRessources = false;
  4997. this.hasReachedQuota = false;
  4998. if (!Database.IDBStorageEnabled) {
  4999. this.callbackManifestChecked(true);
  5000. }
  5001. else {
  5002. this.checkManifestFile();
  5003. }
  5004. }
  5005. Database.prototype.checkManifestFile = function () {
  5006. var _this = this;
  5007. function noManifestFile() {
  5008. that.enableSceneOffline = false;
  5009. that.enableTexturesOffline = false;
  5010. that.callbackManifestChecked(false);
  5011. }
  5012. var that = this;
  5013. var timeStampUsed = false;
  5014. var manifestURL = this.currentSceneUrl + ".manifest";
  5015. var xhr = new XMLHttpRequest();
  5016. if (navigator.onLine) {
  5017. // Adding a timestamp to by-pass browsers' cache
  5018. timeStampUsed = true;
  5019. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  5020. }
  5021. xhr.open("GET", manifestURL, true);
  5022. xhr.addEventListener("load", function () {
  5023. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  5024. try {
  5025. var manifestFile = JSON.parse(xhr.response);
  5026. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  5027. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  5028. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  5029. _this.manifestVersionFound = manifestFile.version;
  5030. }
  5031. if (_this.callbackManifestChecked) {
  5032. _this.callbackManifestChecked(true);
  5033. }
  5034. }
  5035. catch (ex) {
  5036. noManifestFile();
  5037. }
  5038. }
  5039. else {
  5040. noManifestFile();
  5041. }
  5042. }, false);
  5043. xhr.addEventListener("error", function (event) {
  5044. if (timeStampUsed) {
  5045. timeStampUsed = false;
  5046. // Let's retry without the timeStamp
  5047. // It could fail when coupled with HTML5 Offline API
  5048. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  5049. xhr.open("GET", retryManifestURL, true);
  5050. xhr.send();
  5051. }
  5052. else {
  5053. noManifestFile();
  5054. }
  5055. }, false);
  5056. try {
  5057. xhr.send();
  5058. }
  5059. catch (ex) {
  5060. BABYLON.Tools.Error("Error on XHR send request.");
  5061. that.callbackManifestChecked(false);
  5062. }
  5063. };
  5064. Database.prototype.openAsync = function (successCallback, errorCallback) {
  5065. var _this = this;
  5066. function handleError() {
  5067. that.isSupported = false;
  5068. if (errorCallback)
  5069. errorCallback();
  5070. }
  5071. var that = this;
  5072. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  5073. // Your browser doesn't support IndexedDB
  5074. this.isSupported = false;
  5075. if (errorCallback)
  5076. errorCallback();
  5077. }
  5078. else {
  5079. // If the DB hasn't been opened or created yet
  5080. if (!this.db) {
  5081. this.hasReachedQuota = false;
  5082. this.isSupported = true;
  5083. var request = this.idbFactory.open("babylonjs", 1);
  5084. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  5085. request.onerror = function (event) {
  5086. handleError();
  5087. };
  5088. // executes when a version change transaction cannot complete due to other active transactions
  5089. request.onblocked = function (event) {
  5090. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  5091. handleError();
  5092. };
  5093. // DB has been opened successfully
  5094. request.onsuccess = function (event) {
  5095. _this.db = request.result;
  5096. successCallback();
  5097. };
  5098. // Initialization of the DB. Creating Scenes & Textures stores
  5099. request.onupgradeneeded = function (event) {
  5100. _this.db = (event.target).result;
  5101. try {
  5102. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  5103. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  5104. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  5105. }
  5106. catch (ex) {
  5107. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  5108. handleError();
  5109. }
  5110. };
  5111. }
  5112. else {
  5113. if (successCallback)
  5114. successCallback();
  5115. }
  5116. }
  5117. };
  5118. Database.prototype.loadImageFromDB = function (url, image) {
  5119. var _this = this;
  5120. var completeURL = Database.ReturnFullUrlLocation(url);
  5121. var saveAndLoadImage = function () {
  5122. if (!_this.hasReachedQuota && _this.db !== null) {
  5123. // the texture is not yet in the DB, let's try to save it
  5124. _this._saveImageIntoDBAsync(completeURL, image);
  5125. }
  5126. else {
  5127. image.src = url;
  5128. }
  5129. };
  5130. if (!this.mustUpdateRessources) {
  5131. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  5132. }
  5133. else {
  5134. saveAndLoadImage();
  5135. }
  5136. };
  5137. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  5138. if (this.isSupported && this.db !== null) {
  5139. var texture;
  5140. var transaction = this.db.transaction(["textures"]);
  5141. transaction.onabort = function (event) {
  5142. image.src = url;
  5143. };
  5144. transaction.oncomplete = function (event) {
  5145. var blobTextureURL;
  5146. if (texture) {
  5147. var URL = window.URL || window.webkitURL;
  5148. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  5149. image.onerror = function () {
  5150. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  5151. image.src = url;
  5152. };
  5153. image.src = blobTextureURL;
  5154. }
  5155. else {
  5156. notInDBCallback();
  5157. }
  5158. };
  5159. var getRequest = transaction.objectStore("textures").get(url);
  5160. getRequest.onsuccess = function (event) {
  5161. texture = (event.target).result;
  5162. };
  5163. getRequest.onerror = function (event) {
  5164. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  5165. image.src = url;
  5166. };
  5167. }
  5168. else {
  5169. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5170. image.src = url;
  5171. }
  5172. };
  5173. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  5174. var _this = this;
  5175. if (this.isSupported) {
  5176. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  5177. var generateBlobUrl = function () {
  5178. var blobTextureURL;
  5179. if (blob) {
  5180. var URL = window.URL || window.webkitURL;
  5181. try {
  5182. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  5183. }
  5184. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  5185. catch (ex) {
  5186. blobTextureURL = URL.createObjectURL(blob);
  5187. }
  5188. }
  5189. image.src = blobTextureURL;
  5190. };
  5191. if (Database.IsUASupportingBlobStorage) {
  5192. var xhr = new XMLHttpRequest(), blob;
  5193. xhr.open("GET", url, true);
  5194. xhr.responseType = "blob";
  5195. xhr.addEventListener("load", function () {
  5196. if (xhr.status === 200) {
  5197. // Blob as response (XHR2)
  5198. blob = xhr.response;
  5199. var transaction = _this.db.transaction(["textures"], "readwrite");
  5200. // the transaction could abort because of a QuotaExceededError error
  5201. transaction.onabort = function (event) {
  5202. try {
  5203. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5204. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5205. _this.hasReachedQuota = true;
  5206. }
  5207. }
  5208. catch (ex) { }
  5209. generateBlobUrl();
  5210. };
  5211. transaction.oncomplete = function (event) {
  5212. generateBlobUrl();
  5213. };
  5214. var newTexture = { textureUrl: url, data: blob };
  5215. try {
  5216. // Put the blob into the dabase
  5217. var addRequest = transaction.objectStore("textures").put(newTexture);
  5218. addRequest.onsuccess = function (event) {
  5219. };
  5220. addRequest.onerror = function (event) {
  5221. generateBlobUrl();
  5222. };
  5223. }
  5224. catch (ex) {
  5225. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  5226. if (ex.code === 25) {
  5227. Database.IsUASupportingBlobStorage = false;
  5228. }
  5229. image.src = url;
  5230. }
  5231. }
  5232. else {
  5233. image.src = url;
  5234. }
  5235. }, false);
  5236. xhr.addEventListener("error", function (event) {
  5237. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  5238. image.src = url;
  5239. }, false);
  5240. xhr.send();
  5241. }
  5242. else {
  5243. image.src = url;
  5244. }
  5245. }
  5246. else {
  5247. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5248. image.src = url;
  5249. }
  5250. };
  5251. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  5252. var _this = this;
  5253. var updateVersion = function (event) {
  5254. // the version is not yet in the DB or we need to update it
  5255. _this._saveVersionIntoDBAsync(url, versionLoaded);
  5256. };
  5257. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  5258. };
  5259. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  5260. var _this = this;
  5261. if (this.isSupported) {
  5262. var version;
  5263. try {
  5264. var transaction = this.db.transaction(["versions"]);
  5265. transaction.oncomplete = function (event) {
  5266. if (version) {
  5267. // If the version in the JSON file is > than the version in DB
  5268. if (_this.manifestVersionFound > version.data) {
  5269. _this.mustUpdateRessources = true;
  5270. updateInDBCallback();
  5271. }
  5272. else {
  5273. callback(version.data);
  5274. }
  5275. }
  5276. else {
  5277. _this.mustUpdateRessources = true;
  5278. updateInDBCallback();
  5279. }
  5280. };
  5281. transaction.onabort = function (event) {
  5282. callback(-1);
  5283. };
  5284. var getRequest = transaction.objectStore("versions").get(url);
  5285. getRequest.onsuccess = function (event) {
  5286. version = (event.target).result;
  5287. };
  5288. getRequest.onerror = function (event) {
  5289. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  5290. callback(-1);
  5291. };
  5292. }
  5293. catch (ex) {
  5294. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  5295. callback(-1);
  5296. }
  5297. }
  5298. else {
  5299. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5300. callback(-1);
  5301. }
  5302. };
  5303. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  5304. var _this = this;
  5305. if (this.isSupported && !this.hasReachedQuota) {
  5306. try {
  5307. // Open a transaction to the database
  5308. var transaction = this.db.transaction(["versions"], "readwrite");
  5309. // the transaction could abort because of a QuotaExceededError error
  5310. transaction.onabort = function (event) {
  5311. try {
  5312. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5313. _this.hasReachedQuota = true;
  5314. }
  5315. }
  5316. catch (ex) { }
  5317. callback(-1);
  5318. };
  5319. transaction.oncomplete = function (event) {
  5320. callback(_this.manifestVersionFound);
  5321. };
  5322. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  5323. // Put the scene into the database
  5324. var addRequest = transaction.objectStore("versions").put(newVersion);
  5325. addRequest.onsuccess = function (event) {
  5326. };
  5327. addRequest.onerror = function (event) {
  5328. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  5329. };
  5330. }
  5331. catch (ex) {
  5332. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  5333. callback(-1);
  5334. }
  5335. }
  5336. else {
  5337. callback(-1);
  5338. }
  5339. };
  5340. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  5341. var _this = this;
  5342. var completeUrl = Database.ReturnFullUrlLocation(url);
  5343. var saveAndLoadFile = function (event) {
  5344. // the scene is not yet in the DB, let's try to save it
  5345. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  5346. };
  5347. this._checkVersionFromDB(completeUrl, function (version) {
  5348. if (version !== -1) {
  5349. if (!_this.mustUpdateRessources) {
  5350. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  5351. }
  5352. else {
  5353. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  5354. }
  5355. }
  5356. else {
  5357. errorCallback();
  5358. }
  5359. });
  5360. };
  5361. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  5362. if (this.isSupported) {
  5363. var targetStore;
  5364. if (url.indexOf(".babylon") !== -1) {
  5365. targetStore = "scenes";
  5366. }
  5367. else {
  5368. targetStore = "textures";
  5369. }
  5370. var file;
  5371. var transaction = this.db.transaction([targetStore]);
  5372. transaction.oncomplete = function (event) {
  5373. if (file) {
  5374. callback(file.data);
  5375. }
  5376. else {
  5377. notInDBCallback();
  5378. }
  5379. };
  5380. transaction.onabort = function (event) {
  5381. notInDBCallback();
  5382. };
  5383. var getRequest = transaction.objectStore(targetStore).get(url);
  5384. getRequest.onsuccess = function (event) {
  5385. file = (event.target).result;
  5386. };
  5387. getRequest.onerror = function (event) {
  5388. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  5389. notInDBCallback();
  5390. };
  5391. }
  5392. else {
  5393. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5394. callback();
  5395. }
  5396. };
  5397. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  5398. var _this = this;
  5399. if (this.isSupported) {
  5400. var targetStore;
  5401. if (url.indexOf(".babylon") !== -1) {
  5402. targetStore = "scenes";
  5403. }
  5404. else {
  5405. targetStore = "textures";
  5406. }
  5407. // Create XHR
  5408. var xhr = new XMLHttpRequest(), fileData;
  5409. xhr.open("GET", url, true);
  5410. if (useArrayBuffer) {
  5411. xhr.responseType = "arraybuffer";
  5412. }
  5413. xhr.onprogress = progressCallback;
  5414. xhr.addEventListener("load", function () {
  5415. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  5416. // Blob as response (XHR2)
  5417. //fileData = xhr.responseText;
  5418. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  5419. if (!_this.hasReachedQuota) {
  5420. // Open a transaction to the database
  5421. var transaction = _this.db.transaction([targetStore], "readwrite");
  5422. // the transaction could abort because of a QuotaExceededError error
  5423. transaction.onabort = function (event) {
  5424. try {
  5425. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5426. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5427. _this.hasReachedQuota = true;
  5428. }
  5429. }
  5430. catch (ex) { }
  5431. callback(fileData);
  5432. };
  5433. transaction.oncomplete = function (event) {
  5434. callback(fileData);
  5435. };
  5436. var newFile;
  5437. if (targetStore === "scenes") {
  5438. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  5439. }
  5440. else {
  5441. newFile = { textureUrl: url, data: fileData };
  5442. }
  5443. try {
  5444. // Put the scene into the database
  5445. var addRequest = transaction.objectStore(targetStore).put(newFile);
  5446. addRequest.onsuccess = function (event) {
  5447. };
  5448. addRequest.onerror = function (event) {
  5449. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  5450. };
  5451. }
  5452. catch (ex) {
  5453. callback(fileData);
  5454. }
  5455. }
  5456. else {
  5457. callback(fileData);
  5458. }
  5459. }
  5460. else {
  5461. callback();
  5462. }
  5463. }, false);
  5464. xhr.addEventListener("error", function (event) {
  5465. BABYLON.Tools.Error("error on XHR request.");
  5466. callback();
  5467. }, false);
  5468. xhr.send();
  5469. }
  5470. else {
  5471. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5472. callback();
  5473. }
  5474. };
  5475. return Database;
  5476. }());
  5477. Database.IsUASupportingBlobStorage = true;
  5478. Database.IDBStorageEnabled = true;
  5479. Database.parseURL = function (url) {
  5480. var a = document.createElement('a');
  5481. a.href = url;
  5482. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  5483. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  5484. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  5485. return absLocation;
  5486. };
  5487. Database.ReturnFullUrlLocation = function (url) {
  5488. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  5489. return (Database.parseURL(window.location.href) + url);
  5490. }
  5491. else {
  5492. return url;
  5493. }
  5494. };
  5495. BABYLON.Database = Database;
  5496. })(BABYLON || (BABYLON = {}));
  5497. //# sourceMappingURL=babylon.database.js.map
  5498. var BABYLON;
  5499. (function (BABYLON) {
  5500. var Internals;
  5501. (function (Internals) {
  5502. /*
  5503. * Based on jsTGALoader - Javascript loader for TGA file
  5504. * By Vincent Thibault
  5505. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  5506. */
  5507. var TGATools = (function () {
  5508. function TGATools() {
  5509. }
  5510. TGATools.GetTGAHeader = function (data) {
  5511. var offset = 0;
  5512. var header = {
  5513. id_length: data[offset++],
  5514. colormap_type: data[offset++],
  5515. image_type: data[offset++],
  5516. colormap_index: data[offset++] | data[offset++] << 8,
  5517. colormap_length: data[offset++] | data[offset++] << 8,
  5518. colormap_size: data[offset++],
  5519. origin: [
  5520. data[offset++] | data[offset++] << 8,
  5521. data[offset++] | data[offset++] << 8
  5522. ],
  5523. width: data[offset++] | data[offset++] << 8,
  5524. height: data[offset++] | data[offset++] << 8,
  5525. pixel_size: data[offset++],
  5526. flags: data[offset++]
  5527. };
  5528. return header;
  5529. };
  5530. TGATools.UploadContent = function (gl, data) {
  5531. // Not enough data to contain header ?
  5532. if (data.length < 19) {
  5533. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  5534. return;
  5535. }
  5536. // Read Header
  5537. var offset = 18;
  5538. var header = TGATools.GetTGAHeader(data);
  5539. // Assume it's a valid Targa file.
  5540. if (header.id_length + offset > data.length) {
  5541. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  5542. return;
  5543. }
  5544. // Skip not needed data
  5545. offset += header.id_length;
  5546. var use_rle = false;
  5547. var use_pal = false;
  5548. var use_rgb = false;
  5549. var use_grey = false;
  5550. // Get some informations.
  5551. switch (header.image_type) {
  5552. case TGATools._TYPE_RLE_INDEXED:
  5553. use_rle = true;
  5554. case TGATools._TYPE_INDEXED:
  5555. use_pal = true;
  5556. break;
  5557. case TGATools._TYPE_RLE_RGB:
  5558. use_rle = true;
  5559. case TGATools._TYPE_RGB:
  5560. use_rgb = true;
  5561. break;
  5562. case TGATools._TYPE_RLE_GREY:
  5563. use_rle = true;
  5564. case TGATools._TYPE_GREY:
  5565. use_grey = true;
  5566. break;
  5567. }
  5568. var pixel_data;
  5569. var numAlphaBits = header.flags & 0xf;
  5570. var pixel_size = header.pixel_size >> 3;
  5571. var pixel_total = header.width * header.height * pixel_size;
  5572. // Read palettes
  5573. var palettes;
  5574. if (use_pal) {
  5575. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  5576. }
  5577. // Read LRE
  5578. if (use_rle) {
  5579. pixel_data = new Uint8Array(pixel_total);
  5580. var c, count, i;
  5581. var localOffset = 0;
  5582. var pixels = new Uint8Array(pixel_size);
  5583. while (offset < pixel_total && localOffset < pixel_total) {
  5584. c = data[offset++];
  5585. count = (c & 0x7f) + 1;
  5586. // RLE pixels
  5587. if (c & 0x80) {
  5588. // Bind pixel tmp array
  5589. for (i = 0; i < pixel_size; ++i) {
  5590. pixels[i] = data[offset++];
  5591. }
  5592. // Copy pixel array
  5593. for (i = 0; i < count; ++i) {
  5594. pixel_data.set(pixels, localOffset + i * pixel_size);
  5595. }
  5596. localOffset += pixel_size * count;
  5597. }
  5598. else {
  5599. count *= pixel_size;
  5600. for (i = 0; i < count; ++i) {
  5601. pixel_data[localOffset + i] = data[offset++];
  5602. }
  5603. localOffset += count;
  5604. }
  5605. }
  5606. }
  5607. else {
  5608. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  5609. }
  5610. // Load to texture
  5611. var x_start, y_start, x_step, y_step, y_end, x_end;
  5612. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  5613. default:
  5614. case TGATools._ORIGIN_UL:
  5615. x_start = 0;
  5616. x_step = 1;
  5617. x_end = header.width;
  5618. y_start = 0;
  5619. y_step = 1;
  5620. y_end = header.height;
  5621. break;
  5622. case TGATools._ORIGIN_BL:
  5623. x_start = 0;
  5624. x_step = 1;
  5625. x_end = header.width;
  5626. y_start = header.height - 1;
  5627. y_step = -1;
  5628. y_end = -1;
  5629. break;
  5630. case TGATools._ORIGIN_UR:
  5631. x_start = header.width - 1;
  5632. x_step = -1;
  5633. x_end = -1;
  5634. y_start = 0;
  5635. y_step = 1;
  5636. y_end = header.height;
  5637. break;
  5638. case TGATools._ORIGIN_BR:
  5639. x_start = header.width - 1;
  5640. x_step = -1;
  5641. x_end = -1;
  5642. y_start = header.height - 1;
  5643. y_step = -1;
  5644. y_end = -1;
  5645. break;
  5646. }
  5647. // Load the specify method
  5648. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  5649. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  5650. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  5651. };
  5652. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5653. var image = pixel_data, colormap = palettes;
  5654. var width = header.width, height = header.height;
  5655. var color, i = 0, x, y;
  5656. var imageData = new Uint8Array(width * height * 4);
  5657. for (y = y_start; y !== y_end; y += y_step) {
  5658. for (x = x_start; x !== x_end; x += x_step, i++) {
  5659. color = image[i];
  5660. imageData[(x + width * y) * 4 + 3] = 255;
  5661. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  5662. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  5663. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  5664. }
  5665. }
  5666. return imageData;
  5667. };
  5668. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5669. var image = pixel_data;
  5670. var width = header.width, height = header.height;
  5671. var color, i = 0, x, y;
  5672. var imageData = new Uint8Array(width * height * 4);
  5673. for (y = y_start; y !== y_end; y += y_step) {
  5674. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5675. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  5676. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  5677. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  5678. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  5679. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  5680. }
  5681. }
  5682. return imageData;
  5683. };
  5684. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5685. var image = pixel_data;
  5686. var width = header.width, height = header.height;
  5687. var i = 0, x, y;
  5688. var imageData = new Uint8Array(width * height * 4);
  5689. for (y = y_start; y !== y_end; y += y_step) {
  5690. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  5691. imageData[(x + width * y) * 4 + 3] = 255;
  5692. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5693. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5694. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5695. }
  5696. }
  5697. return imageData;
  5698. };
  5699. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5700. var image = pixel_data;
  5701. var width = header.width, height = header.height;
  5702. var i = 0, x, y;
  5703. var imageData = new Uint8Array(width * height * 4);
  5704. for (y = y_start; y !== y_end; y += y_step) {
  5705. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  5706. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5707. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5708. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5709. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  5710. }
  5711. }
  5712. return imageData;
  5713. };
  5714. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5715. var image = pixel_data;
  5716. var width = header.width, height = header.height;
  5717. var color, i = 0, x, y;
  5718. var imageData = new Uint8Array(width * height * 4);
  5719. for (y = y_start; y !== y_end; y += y_step) {
  5720. for (x = x_start; x !== x_end; x += x_step, i++) {
  5721. color = image[i];
  5722. imageData[(x + width * y) * 4 + 0] = color;
  5723. imageData[(x + width * y) * 4 + 1] = color;
  5724. imageData[(x + width * y) * 4 + 2] = color;
  5725. imageData[(x + width * y) * 4 + 3] = 255;
  5726. }
  5727. }
  5728. return imageData;
  5729. };
  5730. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5731. var image = pixel_data;
  5732. var width = header.width, height = header.height;
  5733. var i = 0, x, y;
  5734. var imageData = new Uint8Array(width * height * 4);
  5735. for (y = y_start; y !== y_end; y += y_step) {
  5736. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5737. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  5738. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  5739. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5740. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  5741. }
  5742. }
  5743. return imageData;
  5744. };
  5745. return TGATools;
  5746. }());
  5747. TGATools._TYPE_NO_DATA = 0;
  5748. TGATools._TYPE_INDEXED = 1;
  5749. TGATools._TYPE_RGB = 2;
  5750. TGATools._TYPE_GREY = 3;
  5751. TGATools._TYPE_RLE_INDEXED = 9;
  5752. TGATools._TYPE_RLE_RGB = 10;
  5753. TGATools._TYPE_RLE_GREY = 11;
  5754. TGATools._ORIGIN_MASK = 0x30;
  5755. TGATools._ORIGIN_SHIFT = 0x04;
  5756. TGATools._ORIGIN_BL = 0x00;
  5757. TGATools._ORIGIN_BR = 0x01;
  5758. TGATools._ORIGIN_UL = 0x02;
  5759. TGATools._ORIGIN_UR = 0x03;
  5760. Internals.TGATools = TGATools;
  5761. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5762. })(BABYLON || (BABYLON = {}));
  5763. //# sourceMappingURL=babylon.tools.tga.js.map
  5764. var BABYLON;
  5765. (function (BABYLON) {
  5766. var SmartArray = (function () {
  5767. function SmartArray(capacity) {
  5768. this.length = 0;
  5769. this._duplicateId = 0;
  5770. this.data = new Array(capacity);
  5771. this._id = SmartArray._GlobalId++;
  5772. }
  5773. SmartArray.prototype.push = function (value) {
  5774. this.data[this.length++] = value;
  5775. if (this.length > this.data.length) {
  5776. this.data.length *= 2;
  5777. }
  5778. if (!value.__smartArrayFlags) {
  5779. value.__smartArrayFlags = {};
  5780. }
  5781. value.__smartArrayFlags[this._id] = this._duplicateId;
  5782. };
  5783. SmartArray.prototype.forEach = function (func) {
  5784. for (var index = 0; index < this.length; index++) {
  5785. func(this.data[index]);
  5786. }
  5787. };
  5788. SmartArray.prototype.pushNoDuplicate = function (value) {
  5789. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5790. return false;
  5791. }
  5792. this.push(value);
  5793. return true;
  5794. };
  5795. SmartArray.prototype.sort = function (compareFn) {
  5796. this.data.sort(compareFn);
  5797. };
  5798. SmartArray.prototype.reset = function () {
  5799. this.length = 0;
  5800. this._duplicateId++;
  5801. };
  5802. SmartArray.prototype.dispose = function () {
  5803. this.reset();
  5804. this.data.length = 0;
  5805. };
  5806. SmartArray.prototype.concat = function (array) {
  5807. if (array.length === 0) {
  5808. return;
  5809. }
  5810. if (this.length + array.length > this.data.length) {
  5811. this.data.length = (this.length + array.length) * 2;
  5812. }
  5813. for (var index = 0; index < array.length; index++) {
  5814. this.data[this.length++] = (array.data || array)[index];
  5815. }
  5816. };
  5817. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5818. if (array.length === 0) {
  5819. return;
  5820. }
  5821. if (this.length + array.length > this.data.length) {
  5822. this.data.length = (this.length + array.length) * 2;
  5823. }
  5824. for (var index = 0; index < array.length; index++) {
  5825. var item = (array.data || array)[index];
  5826. this.pushNoDuplicate(item);
  5827. }
  5828. };
  5829. SmartArray.prototype.indexOf = function (value) {
  5830. var position = this.data.indexOf(value);
  5831. if (position >= this.length) {
  5832. return -1;
  5833. }
  5834. return position;
  5835. };
  5836. SmartArray.prototype.contains = function (value) {
  5837. return this.data.indexOf(value) !== -1;
  5838. };
  5839. return SmartArray;
  5840. }());
  5841. // Statics
  5842. SmartArray._GlobalId = 0;
  5843. BABYLON.SmartArray = SmartArray;
  5844. })(BABYLON || (BABYLON = {}));
  5845. //# sourceMappingURL=babylon.smartArray.js.map
  5846. var BABYLON;
  5847. (function (BABYLON) {
  5848. /**
  5849. * This class implement a typical dictionary using a string as key and the generic type T as value.
  5850. * The underlying implementation relies on an associative array to ensure the best performances.
  5851. * The value can be anything including 'null' but except 'undefined'
  5852. */
  5853. var StringDictionary = (function () {
  5854. function StringDictionary() {
  5855. this._count = 0;
  5856. this._data = {};
  5857. }
  5858. /**
  5859. * This will clear this dictionary and copy the content from the 'source' one.
  5860. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  5861. * @param source the dictionary to take the content from and copy to this dictionary
  5862. */
  5863. StringDictionary.prototype.copyFrom = function (source) {
  5864. var _this = this;
  5865. this.clear();
  5866. source.forEach(function (t, v) { return _this.add(t, v); });
  5867. };
  5868. /**
  5869. * Get a value based from its key
  5870. * @param key the given key to get the matching value from
  5871. * @return the value if found, otherwise undefined is returned
  5872. */
  5873. StringDictionary.prototype.get = function (key) {
  5874. var val = this._data[key];
  5875. if (val !== undefined) {
  5876. return val;
  5877. }
  5878. return undefined;
  5879. };
  5880. /**
  5881. * Get a value from its key or add it if it doesn't exist.
  5882. * This method will ensure you that a given key/data will be present in the dictionary.
  5883. * @param key the given key to get the matching value from
  5884. * @param factory the factory that will create the value if the key is not present in the dictionary.
  5885. * The factory will only be invoked if there's no data for the given key.
  5886. * @return the value corresponding to the key.
  5887. */
  5888. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  5889. var val = this.get(key);
  5890. if (val !== undefined) {
  5891. return val;
  5892. }
  5893. val = factory(key);
  5894. if (val) {
  5895. this.add(key, val);
  5896. }
  5897. return val;
  5898. };
  5899. /**
  5900. * Get a value from its key if present in the dictionary otherwise add it
  5901. * @param key the key to get the value from
  5902. * @param val if there's no such key/value pair in the dictionary add it with this value
  5903. * @return the value corresponding to the key
  5904. */
  5905. StringDictionary.prototype.getOrAdd = function (key, val) {
  5906. var curVal = this.get(key);
  5907. if (curVal !== undefined) {
  5908. return curVal;
  5909. }
  5910. this.add(key, val);
  5911. return val;
  5912. };
  5913. /**
  5914. * Check if there's a given key in the dictionary
  5915. * @param key the key to check for
  5916. * @return true if the key is present, false otherwise
  5917. */
  5918. StringDictionary.prototype.contains = function (key) {
  5919. return this._data[key] !== undefined;
  5920. };
  5921. /**
  5922. * Add a new key and its corresponding value
  5923. * @param key the key to add
  5924. * @param value the value corresponding to the key
  5925. * @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
  5926. */
  5927. StringDictionary.prototype.add = function (key, value) {
  5928. if (this._data[key] !== undefined) {
  5929. return false;
  5930. }
  5931. this._data[key] = value;
  5932. ++this._count;
  5933. return true;
  5934. };
  5935. StringDictionary.prototype.set = function (key, value) {
  5936. if (this._data[key] === undefined) {
  5937. return false;
  5938. }
  5939. this._data[key] = value;
  5940. return true;
  5941. };
  5942. /**
  5943. * Get the element of the given key and remove it from the dictionary
  5944. * @param key
  5945. */
  5946. StringDictionary.prototype.getAndRemove = function (key) {
  5947. var val = this.get(key);
  5948. if (val !== undefined) {
  5949. delete this._data[key];
  5950. --this._count;
  5951. return val;
  5952. }
  5953. return null;
  5954. };
  5955. /**
  5956. * Remove a key/value from the dictionary.
  5957. * @param key the key to remove
  5958. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  5959. */
  5960. StringDictionary.prototype.remove = function (key) {
  5961. if (this.contains(key)) {
  5962. delete this._data[key];
  5963. --this._count;
  5964. return true;
  5965. }
  5966. return false;
  5967. };
  5968. /**
  5969. * Clear the whole content of the dictionary
  5970. */
  5971. StringDictionary.prototype.clear = function () {
  5972. this._data = {};
  5973. this._count = 0;
  5974. };
  5975. Object.defineProperty(StringDictionary.prototype, "count", {
  5976. get: function () {
  5977. return this._count;
  5978. },
  5979. enumerable: true,
  5980. configurable: true
  5981. });
  5982. /**
  5983. * Execute a callback on each key/val of the dictionary.
  5984. * Note that you can remove any element in this dictionary in the callback implementation
  5985. * @param callback the callback to execute on a given key/value pair
  5986. */
  5987. StringDictionary.prototype.forEach = function (callback) {
  5988. for (var cur in this._data) {
  5989. var val = this._data[cur];
  5990. callback(cur, val);
  5991. }
  5992. };
  5993. /**
  5994. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  5995. * If the callback returns null or undefined the method will iterate to the next key/value pair
  5996. * Note that you can remove any element in this dictionary in the callback implementation
  5997. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  5998. */
  5999. StringDictionary.prototype.first = function (callback) {
  6000. for (var cur in this._data) {
  6001. var val = this._data[cur];
  6002. var res = callback(cur, val);
  6003. if (res) {
  6004. return res;
  6005. }
  6006. }
  6007. return null;
  6008. };
  6009. return StringDictionary;
  6010. }());
  6011. BABYLON.StringDictionary = StringDictionary;
  6012. })(BABYLON || (BABYLON = {}));
  6013. //# sourceMappingURL=babylon.stringDictionary.js.map
  6014. var BABYLON;
  6015. (function (BABYLON) {
  6016. // Screenshots
  6017. var screenshotCanvas;
  6018. var cloneValue = function (source, destinationObject) {
  6019. if (!source)
  6020. return null;
  6021. if (source instanceof BABYLON.Mesh) {
  6022. return null;
  6023. }
  6024. if (source instanceof BABYLON.SubMesh) {
  6025. return source.clone(destinationObject);
  6026. }
  6027. else if (source.clone) {
  6028. return source.clone();
  6029. }
  6030. return null;
  6031. };
  6032. var Tools = (function () {
  6033. function Tools() {
  6034. }
  6035. ;
  6036. Tools.Instantiate = function (className) {
  6037. var arr = className.split(".");
  6038. var fn = (window || this);
  6039. for (var i = 0, len = arr.length; i < len; i++) {
  6040. fn = fn[arr[i]];
  6041. }
  6042. if (typeof fn !== "function") {
  6043. return null;
  6044. }
  6045. return fn;
  6046. };
  6047. Tools.SetImmediate = function (action) {
  6048. if (window.setImmediate) {
  6049. window.setImmediate(action);
  6050. }
  6051. else {
  6052. setTimeout(action, 1);
  6053. }
  6054. };
  6055. Tools.IsExponentOfTwo = function (value) {
  6056. var count = 1;
  6057. do {
  6058. count *= 2;
  6059. } while (count < value);
  6060. return count === value;
  6061. };
  6062. Tools.GetExponentOfTwo = function (value, max) {
  6063. var count = 1;
  6064. do {
  6065. count *= 2;
  6066. } while (count < value);
  6067. if (count > max)
  6068. count = max;
  6069. return count;
  6070. };
  6071. Tools.GetFilename = function (path) {
  6072. var index = path.lastIndexOf("/");
  6073. if (index < 0)
  6074. return path;
  6075. return path.substring(index + 1);
  6076. };
  6077. Tools.GetDOMTextContent = function (element) {
  6078. var result = "";
  6079. var child = element.firstChild;
  6080. while (child) {
  6081. if (child.nodeType === 3) {
  6082. result += child.textContent;
  6083. }
  6084. child = child.nextSibling;
  6085. }
  6086. return result;
  6087. };
  6088. Tools.ToDegrees = function (angle) {
  6089. return angle * 180 / Math.PI;
  6090. };
  6091. Tools.ToRadians = function (angle) {
  6092. return angle * Math.PI / 180;
  6093. };
  6094. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6095. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6096. var output = "";
  6097. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6098. var i = 0;
  6099. var bytes = new Uint8Array(buffer);
  6100. while (i < bytes.length) {
  6101. chr1 = bytes[i++];
  6102. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6103. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6104. enc1 = chr1 >> 2;
  6105. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6106. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6107. enc4 = chr3 & 63;
  6108. if (isNaN(chr2)) {
  6109. enc3 = enc4 = 64;
  6110. }
  6111. else if (isNaN(chr3)) {
  6112. enc4 = 64;
  6113. }
  6114. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6115. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6116. }
  6117. return "data:image/png;base64," + output;
  6118. };
  6119. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6120. if (bias === void 0) { bias = null; }
  6121. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6122. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6123. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6124. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6125. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6126. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6127. }
  6128. if (bias) {
  6129. minimum.x -= minimum.x * bias.x + bias.y;
  6130. minimum.y -= minimum.y * bias.x + bias.y;
  6131. minimum.z -= minimum.z * bias.x + bias.y;
  6132. maximum.x += maximum.x * bias.x + bias.y;
  6133. maximum.y += maximum.y * bias.x + bias.y;
  6134. maximum.z += maximum.z * bias.x + bias.y;
  6135. }
  6136. return {
  6137. minimum: minimum,
  6138. maximum: maximum
  6139. };
  6140. };
  6141. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6142. if (bias === void 0) { bias = null; }
  6143. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6144. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6145. if (!stride) {
  6146. stride = 3;
  6147. }
  6148. for (var index = start; index < start + count; index++) {
  6149. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6150. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6151. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6152. }
  6153. if (bias) {
  6154. minimum.x -= minimum.x * bias.x + bias.y;
  6155. minimum.y -= minimum.y * bias.x + bias.y;
  6156. minimum.z -= minimum.z * bias.x + bias.y;
  6157. maximum.x += maximum.x * bias.x + bias.y;
  6158. maximum.y += maximum.y * bias.x + bias.y;
  6159. maximum.z += maximum.z * bias.x + bias.y;
  6160. }
  6161. return {
  6162. minimum: minimum,
  6163. maximum: maximum
  6164. };
  6165. };
  6166. Tools.Vector2ArrayFeeder = function (array) {
  6167. return function (index) {
  6168. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6169. var length = isFloatArray ? array.length / 2 : array.length;
  6170. if (index >= length) {
  6171. return null;
  6172. }
  6173. if (isFloatArray) {
  6174. var fa = array;
  6175. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6176. }
  6177. var a = array;
  6178. return a[index];
  6179. };
  6180. };
  6181. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6182. if (bias === void 0) { bias = null; }
  6183. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6184. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6185. var i = 0;
  6186. var cur = feeder(i++);
  6187. while (cur) {
  6188. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6189. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6190. cur = feeder(i++);
  6191. }
  6192. if (bias) {
  6193. minimum.x -= minimum.x * bias.x + bias.y;
  6194. minimum.y -= minimum.y * bias.x + bias.y;
  6195. maximum.x += maximum.x * bias.x + bias.y;
  6196. maximum.y += maximum.y * bias.x + bias.y;
  6197. }
  6198. return {
  6199. minimum: minimum,
  6200. maximum: maximum
  6201. };
  6202. };
  6203. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6204. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6205. return undefined;
  6206. return Array.isArray(obj) ? obj : [obj];
  6207. };
  6208. // Misc.
  6209. Tools.GetPointerPrefix = function () {
  6210. var eventPrefix = "pointer";
  6211. // Check if pointer events are supported
  6212. if (!window.PointerEvent && !navigator.pointerEnabled) {
  6213. eventPrefix = "mouse";
  6214. }
  6215. return eventPrefix;
  6216. };
  6217. /**
  6218. * @param func - the function to be called
  6219. * @param requester - the object that will request the next frame. Falls back to window.
  6220. */
  6221. Tools.QueueNewFrame = function (func, requester) {
  6222. if (requester === void 0) { requester = window; }
  6223. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  6224. /*if(requester.isPresenting) {
  6225. return;
  6226. } else*/ if (requester.requestAnimationFrame)
  6227. requester.requestAnimationFrame(func);
  6228. else if (requester.msRequestAnimationFrame)
  6229. requester.msRequestAnimationFrame(func);
  6230. else if (requester.webkitRequestAnimationFrame)
  6231. requester.webkitRequestAnimationFrame(func);
  6232. else if (requester.mozRequestAnimationFrame)
  6233. requester.mozRequestAnimationFrame(func);
  6234. else if (requester.oRequestAnimationFrame)
  6235. requester.oRequestAnimationFrame(func);
  6236. else {
  6237. window.setTimeout(func, 16);
  6238. }
  6239. };
  6240. Tools.RequestFullscreen = function (element) {
  6241. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6242. if (!requestFunction)
  6243. return;
  6244. requestFunction.call(element);
  6245. };
  6246. Tools.ExitFullscreen = function () {
  6247. if (document.exitFullscreen) {
  6248. document.exitFullscreen();
  6249. }
  6250. else if (document.mozCancelFullScreen) {
  6251. document.mozCancelFullScreen();
  6252. }
  6253. else if (document.webkitCancelFullScreen) {
  6254. document.webkitCancelFullScreen();
  6255. }
  6256. else if (document.msCancelFullScreen) {
  6257. document.msCancelFullScreen();
  6258. }
  6259. };
  6260. Tools.SetCorsBehavior = function (url, img) {
  6261. if (Tools.CorsBehavior) {
  6262. switch (typeof (Tools.CorsBehavior)) {
  6263. case "function":
  6264. var result = Tools.CorsBehavior(url);
  6265. if (result) {
  6266. img.crossOrigin = result;
  6267. }
  6268. break;
  6269. case "string":
  6270. default:
  6271. img.crossOrigin = Tools.CorsBehavior;
  6272. break;
  6273. }
  6274. }
  6275. };
  6276. // External files
  6277. Tools.CleanUrl = function (url) {
  6278. url = url.replace(/#/mg, "%23");
  6279. return url;
  6280. };
  6281. Tools.LoadImage = function (url, onload, onerror, database) {
  6282. if (url instanceof ArrayBuffer) {
  6283. url = Tools.EncodeArrayBufferTobase64(url);
  6284. }
  6285. url = Tools.CleanUrl(url);
  6286. var img = new Image();
  6287. if (url.substr(0, 5) !== "data:") {
  6288. Tools.SetCorsBehavior(url, img);
  6289. }
  6290. img.onload = function () {
  6291. onload(img);
  6292. };
  6293. img.onerror = function (err) {
  6294. Tools.Error("Error while trying to load image: " + url);
  6295. if (Tools.UseFallbackTexture) {
  6296. img.src = Tools.fallbackTexture;
  6297. onload(img);
  6298. }
  6299. else {
  6300. onerror();
  6301. }
  6302. };
  6303. var noIndexedDB = function () {
  6304. img.src = url;
  6305. };
  6306. var loadFromIndexedDB = function () {
  6307. database.loadImageFromDB(url, img);
  6308. };
  6309. //ANY database to do!
  6310. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6311. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6312. }
  6313. else {
  6314. if (url.indexOf("file:") === -1) {
  6315. noIndexedDB();
  6316. }
  6317. else {
  6318. var textureName = url.substring(5).toLowerCase();
  6319. if (BABYLON.FilesInput.FilesTextures[textureName]) {
  6320. try {
  6321. var blobURL;
  6322. try {
  6323. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  6324. }
  6325. catch (ex) {
  6326. // Chrome doesn't support oneTimeOnly parameter
  6327. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  6328. }
  6329. img.src = blobURL;
  6330. }
  6331. catch (e) {
  6332. img.src = null;
  6333. }
  6334. }
  6335. else {
  6336. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6337. img.src = Tools.fallbackTexture;
  6338. }
  6339. }
  6340. }
  6341. return img;
  6342. };
  6343. //ANY
  6344. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6345. url = Tools.CleanUrl(url);
  6346. var noIndexedDB = function () {
  6347. var request = new XMLHttpRequest();
  6348. var loadUrl = Tools.BaseUrl + url;
  6349. request.open('GET', loadUrl, true);
  6350. if (useArrayBuffer) {
  6351. request.responseType = "arraybuffer";
  6352. }
  6353. request.onprogress = progressCallBack;
  6354. request.onreadystatechange = function () {
  6355. if (request.readyState === 4) {
  6356. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6357. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  6358. callback(!useArrayBuffer ? request.responseText : request.response);
  6359. }
  6360. else {
  6361. if (onError) {
  6362. onError();
  6363. }
  6364. else {
  6365. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  6366. }
  6367. }
  6368. }
  6369. };
  6370. request.send(null);
  6371. };
  6372. var loadFromIndexedDB = function () {
  6373. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6374. };
  6375. if (url.indexOf("file:") !== -1) {
  6376. var fileName = url.substring(5).toLowerCase();
  6377. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6378. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6379. }
  6380. else {
  6381. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  6382. }
  6383. }
  6384. else {
  6385. // Caching all files
  6386. if (database && database.enableSceneOffline) {
  6387. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6388. }
  6389. else {
  6390. noIndexedDB();
  6391. }
  6392. }
  6393. };
  6394. /**
  6395. * Load a script (identified by an url). When the url returns, the
  6396. * content of this file is added into a new script element, attached to the DOM (body element)
  6397. */
  6398. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6399. var head = document.getElementsByTagName('head')[0];
  6400. var script = document.createElement('script');
  6401. script.type = 'text/javascript';
  6402. script.src = scriptUrl;
  6403. var self = this;
  6404. script.onload = function () {
  6405. if (onSuccess) {
  6406. onSuccess();
  6407. }
  6408. };
  6409. script.onerror = function () {
  6410. if (onError) {
  6411. onError();
  6412. }
  6413. };
  6414. head.appendChild(script);
  6415. };
  6416. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6417. var reader = new FileReader();
  6418. reader.onload = function (e) {
  6419. //target doesn't have result from ts 1.3
  6420. callback(e.target['result']);
  6421. };
  6422. reader.onprogress = progressCallback;
  6423. reader.readAsDataURL(fileToLoad);
  6424. };
  6425. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6426. var reader = new FileReader();
  6427. reader.onerror = function (e) {
  6428. Tools.Log("Error while reading file: " + fileToLoad.name);
  6429. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6430. };
  6431. reader.onload = function (e) {
  6432. //target doesn't have result from ts 1.3
  6433. callback(e.target['result']);
  6434. };
  6435. reader.onprogress = progressCallBack;
  6436. if (!useArrayBuffer) {
  6437. // Asynchronous read
  6438. reader.readAsText(fileToLoad);
  6439. }
  6440. else {
  6441. reader.readAsArrayBuffer(fileToLoad);
  6442. }
  6443. };
  6444. //returns a downloadable url to a file content.
  6445. Tools.FileAsURL = function (content) {
  6446. var fileBlob = new Blob([content]);
  6447. var url = window.URL || window.webkitURL;
  6448. var link = url.createObjectURL(fileBlob);
  6449. return link;
  6450. };
  6451. // Misc.
  6452. Tools.Format = function (value, decimals) {
  6453. if (decimals === void 0) { decimals = 2; }
  6454. return value.toFixed(decimals);
  6455. };
  6456. Tools.CheckExtends = function (v, min, max) {
  6457. if (v.x < min.x)
  6458. min.x = v.x;
  6459. if (v.y < min.y)
  6460. min.y = v.y;
  6461. if (v.z < min.z)
  6462. min.z = v.z;
  6463. if (v.x > max.x)
  6464. max.x = v.x;
  6465. if (v.y > max.y)
  6466. max.y = v.y;
  6467. if (v.z > max.z)
  6468. max.z = v.z;
  6469. };
  6470. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6471. for (var prop in source) {
  6472. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6473. continue;
  6474. }
  6475. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6476. continue;
  6477. }
  6478. var sourceValue = source[prop];
  6479. var typeOfSourceValue = typeof sourceValue;
  6480. if (typeOfSourceValue === "function") {
  6481. continue;
  6482. }
  6483. if (typeOfSourceValue === "object") {
  6484. if (sourceValue instanceof Array) {
  6485. destination[prop] = [];
  6486. if (sourceValue.length > 0) {
  6487. if (typeof sourceValue[0] == "object") {
  6488. for (var index = 0; index < sourceValue.length; index++) {
  6489. var clonedValue = cloneValue(sourceValue[index], destination);
  6490. if (destination[prop].indexOf(clonedValue) === -1) {
  6491. destination[prop].push(clonedValue);
  6492. }
  6493. }
  6494. }
  6495. else {
  6496. destination[prop] = sourceValue.slice(0);
  6497. }
  6498. }
  6499. }
  6500. else {
  6501. destination[prop] = cloneValue(sourceValue, destination);
  6502. }
  6503. }
  6504. else {
  6505. destination[prop] = sourceValue;
  6506. }
  6507. }
  6508. };
  6509. Tools.IsEmpty = function (obj) {
  6510. for (var i in obj) {
  6511. return false;
  6512. }
  6513. return true;
  6514. };
  6515. Tools.RegisterTopRootEvents = function (events) {
  6516. for (var index = 0; index < events.length; index++) {
  6517. var event = events[index];
  6518. window.addEventListener(event.name, event.handler, false);
  6519. try {
  6520. if (window.parent) {
  6521. window.parent.addEventListener(event.name, event.handler, false);
  6522. }
  6523. }
  6524. catch (e) {
  6525. // Silently fails...
  6526. }
  6527. }
  6528. };
  6529. Tools.UnregisterTopRootEvents = function (events) {
  6530. for (var index = 0; index < events.length; index++) {
  6531. var event = events[index];
  6532. window.removeEventListener(event.name, event.handler);
  6533. try {
  6534. if (window.parent) {
  6535. window.parent.removeEventListener(event.name, event.handler);
  6536. }
  6537. }
  6538. catch (e) {
  6539. // Silently fails...
  6540. }
  6541. }
  6542. };
  6543. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6544. if (mimeType === void 0) { mimeType = "image/png"; }
  6545. // Read the contents of the framebuffer
  6546. var numberOfChannelsByLine = width * 4;
  6547. var halfHeight = height / 2;
  6548. //Reading datas from WebGL
  6549. var data = engine.readPixels(0, 0, width, height);
  6550. //To flip image on Y axis.
  6551. for (var i = 0; i < halfHeight; i++) {
  6552. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6553. var currentCell = j + i * numberOfChannelsByLine;
  6554. var targetLine = height - i - 1;
  6555. var targetCell = j + targetLine * numberOfChannelsByLine;
  6556. var temp = data[currentCell];
  6557. data[currentCell] = data[targetCell];
  6558. data[targetCell] = temp;
  6559. }
  6560. }
  6561. // Create a 2D canvas to store the result
  6562. if (!screenshotCanvas) {
  6563. screenshotCanvas = document.createElement('canvas');
  6564. }
  6565. screenshotCanvas.width = width;
  6566. screenshotCanvas.height = height;
  6567. var context = screenshotCanvas.getContext('2d');
  6568. // Copy the pixels to a 2D canvas
  6569. var imageData = context.createImageData(width, height);
  6570. var castData = (imageData.data);
  6571. castData.set(data);
  6572. context.putImageData(imageData, 0, 0);
  6573. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6574. };
  6575. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6576. if (mimeType === void 0) { mimeType = "image/png"; }
  6577. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6578. if (successCallback) {
  6579. successCallback(base64Image);
  6580. }
  6581. else {
  6582. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6583. if (("download" in document.createElement("a"))) {
  6584. var a = window.document.createElement("a");
  6585. a.href = base64Image;
  6586. var date = new Date();
  6587. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6588. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6589. window.document.body.appendChild(a);
  6590. a.addEventListener("click", function () {
  6591. a.parentElement.removeChild(a);
  6592. });
  6593. a.click();
  6594. //Or opening a new tab with the image if it is not possible to automatically start download.
  6595. }
  6596. else {
  6597. var newWindow = window.open("");
  6598. var img = newWindow.document.createElement("img");
  6599. img.src = base64Image;
  6600. newWindow.document.body.appendChild(img);
  6601. }
  6602. }
  6603. };
  6604. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6605. if (mimeType === void 0) { mimeType = "image/png"; }
  6606. var width;
  6607. var height;
  6608. // If a precision value is specified
  6609. if (size.precision) {
  6610. width = Math.round(engine.getRenderWidth() * size.precision);
  6611. height = Math.round(width / engine.getAspectRatio(camera));
  6612. }
  6613. else if (size.width && size.height) {
  6614. width = size.width;
  6615. height = size.height;
  6616. }
  6617. else if (size.width && !size.height) {
  6618. width = size.width;
  6619. height = Math.round(width / engine.getAspectRatio(camera));
  6620. }
  6621. else if (size.height && !size.width) {
  6622. height = size.height;
  6623. width = Math.round(height * engine.getAspectRatio(camera));
  6624. }
  6625. else if (!isNaN(size)) {
  6626. height = size;
  6627. width = size;
  6628. }
  6629. else {
  6630. Tools.Error("Invalid 'size' parameter !");
  6631. return;
  6632. }
  6633. if (!screenshotCanvas) {
  6634. screenshotCanvas = document.createElement('canvas');
  6635. }
  6636. screenshotCanvas.width = width;
  6637. screenshotCanvas.height = height;
  6638. var renderContext = screenshotCanvas.getContext("2d");
  6639. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6640. var newWidth = width;
  6641. var newHeight = newWidth / ratio;
  6642. if (newHeight > height) {
  6643. newHeight = height;
  6644. newWidth = newHeight * ratio;
  6645. }
  6646. var offsetX = Math.max(0, width - newWidth) / 2;
  6647. var offsetY = Math.max(0, height - newHeight) / 2;
  6648. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6649. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6650. };
  6651. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6652. if (mimeType === void 0) { mimeType = "image/png"; }
  6653. if (samples === void 0) { samples = 1; }
  6654. var width;
  6655. var height;
  6656. //If a precision value is specified
  6657. if (size.precision) {
  6658. width = Math.round(engine.getRenderWidth() * size.precision);
  6659. height = Math.round(width / engine.getAspectRatio(camera));
  6660. size = { width: width, height: height };
  6661. }
  6662. else if (size.width && size.height) {
  6663. width = size.width;
  6664. height = size.height;
  6665. }
  6666. else if (size.width && !size.height) {
  6667. width = size.width;
  6668. height = Math.round(width / engine.getAspectRatio(camera));
  6669. size = { width: width, height: height };
  6670. }
  6671. else if (size.height && !size.width) {
  6672. height = size.height;
  6673. width = Math.round(height * engine.getAspectRatio(camera));
  6674. size = { width: width, height: height };
  6675. }
  6676. else if (!isNaN(size)) {
  6677. height = size;
  6678. width = size;
  6679. }
  6680. else {
  6681. Tools.Error("Invalid 'size' parameter !");
  6682. return;
  6683. }
  6684. var scene = camera.getScene();
  6685. var previousCamera = null;
  6686. if (scene.activeCamera !== camera) {
  6687. previousCamera = scene.activeCamera;
  6688. scene.activeCamera = camera;
  6689. }
  6690. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6691. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6692. texture.renderList = scene.meshes;
  6693. texture.samples = samples;
  6694. texture.onAfterRenderObservable.add(function () {
  6695. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6696. });
  6697. scene.incrementRenderId();
  6698. scene.resetCachedMaterial();
  6699. texture.render(true);
  6700. texture.dispose();
  6701. if (previousCamera) {
  6702. scene.activeCamera = previousCamera;
  6703. }
  6704. camera.getProjectionMatrix(true); // Force cache refresh;
  6705. };
  6706. // XHR response validator for local file scenario
  6707. Tools.ValidateXHRData = function (xhr, dataType) {
  6708. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6709. if (dataType === void 0) { dataType = 7; }
  6710. try {
  6711. if (dataType & 1) {
  6712. if (xhr.responseText && xhr.responseText.length > 0) {
  6713. return true;
  6714. }
  6715. else if (dataType === 1) {
  6716. return false;
  6717. }
  6718. }
  6719. if (dataType & 2) {
  6720. // Check header width and height since there is no "TGA" magic number
  6721. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6722. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6723. return true;
  6724. }
  6725. else if (dataType === 2) {
  6726. return false;
  6727. }
  6728. }
  6729. if (dataType & 4) {
  6730. // Check for the "DDS" magic number
  6731. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6732. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6733. return true;
  6734. }
  6735. else {
  6736. return false;
  6737. }
  6738. }
  6739. }
  6740. catch (e) {
  6741. // Global protection
  6742. }
  6743. return false;
  6744. };
  6745. /**
  6746. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6747. * Be aware Math.random() could cause collisions, but:
  6748. * "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"
  6749. */
  6750. Tools.RandomId = function () {
  6751. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6752. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6753. return v.toString(16);
  6754. });
  6755. };
  6756. Object.defineProperty(Tools, "NoneLogLevel", {
  6757. get: function () {
  6758. return Tools._NoneLogLevel;
  6759. },
  6760. enumerable: true,
  6761. configurable: true
  6762. });
  6763. Object.defineProperty(Tools, "MessageLogLevel", {
  6764. get: function () {
  6765. return Tools._MessageLogLevel;
  6766. },
  6767. enumerable: true,
  6768. configurable: true
  6769. });
  6770. Object.defineProperty(Tools, "WarningLogLevel", {
  6771. get: function () {
  6772. return Tools._WarningLogLevel;
  6773. },
  6774. enumerable: true,
  6775. configurable: true
  6776. });
  6777. Object.defineProperty(Tools, "ErrorLogLevel", {
  6778. get: function () {
  6779. return Tools._ErrorLogLevel;
  6780. },
  6781. enumerable: true,
  6782. configurable: true
  6783. });
  6784. Object.defineProperty(Tools, "AllLogLevel", {
  6785. get: function () {
  6786. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6787. },
  6788. enumerable: true,
  6789. configurable: true
  6790. });
  6791. Tools._AddLogEntry = function (entry) {
  6792. Tools._LogCache = entry + Tools._LogCache;
  6793. if (Tools.OnNewCacheEntry) {
  6794. Tools.OnNewCacheEntry(entry);
  6795. }
  6796. };
  6797. Tools._FormatMessage = function (message) {
  6798. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6799. var date = new Date();
  6800. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6801. };
  6802. Tools._LogDisabled = function (message) {
  6803. // nothing to do
  6804. };
  6805. Tools._LogEnabled = function (message) {
  6806. var formattedMessage = Tools._FormatMessage(message);
  6807. console.log("BJS - " + formattedMessage);
  6808. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6809. Tools._AddLogEntry(entry);
  6810. };
  6811. Tools._WarnDisabled = function (message) {
  6812. // nothing to do
  6813. };
  6814. Tools._WarnEnabled = function (message) {
  6815. var formattedMessage = Tools._FormatMessage(message);
  6816. console.warn("BJS - " + formattedMessage);
  6817. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6818. Tools._AddLogEntry(entry);
  6819. };
  6820. Tools._ErrorDisabled = function (message) {
  6821. // nothing to do
  6822. };
  6823. Tools._ErrorEnabled = function (message) {
  6824. Tools.errorsCount++;
  6825. var formattedMessage = Tools._FormatMessage(message);
  6826. console.error("BJS - " + formattedMessage);
  6827. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6828. Tools._AddLogEntry(entry);
  6829. };
  6830. Object.defineProperty(Tools, "LogCache", {
  6831. get: function () {
  6832. return Tools._LogCache;
  6833. },
  6834. enumerable: true,
  6835. configurable: true
  6836. });
  6837. Tools.ClearLogCache = function () {
  6838. Tools._LogCache = "";
  6839. Tools.errorsCount = 0;
  6840. };
  6841. Object.defineProperty(Tools, "LogLevels", {
  6842. set: function (level) {
  6843. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6844. Tools.Log = Tools._LogEnabled;
  6845. }
  6846. else {
  6847. Tools.Log = Tools._LogDisabled;
  6848. }
  6849. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6850. Tools.Warn = Tools._WarnEnabled;
  6851. }
  6852. else {
  6853. Tools.Warn = Tools._WarnDisabled;
  6854. }
  6855. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6856. Tools.Error = Tools._ErrorEnabled;
  6857. }
  6858. else {
  6859. Tools.Error = Tools._ErrorDisabled;
  6860. }
  6861. },
  6862. enumerable: true,
  6863. configurable: true
  6864. });
  6865. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6866. get: function () {
  6867. return Tools._PerformanceNoneLogLevel;
  6868. },
  6869. enumerable: true,
  6870. configurable: true
  6871. });
  6872. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6873. get: function () {
  6874. return Tools._PerformanceUserMarkLogLevel;
  6875. },
  6876. enumerable: true,
  6877. configurable: true
  6878. });
  6879. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6880. get: function () {
  6881. return Tools._PerformanceConsoleLogLevel;
  6882. },
  6883. enumerable: true,
  6884. configurable: true
  6885. });
  6886. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6887. set: function (level) {
  6888. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6889. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6890. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6891. return;
  6892. }
  6893. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6894. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6895. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6896. return;
  6897. }
  6898. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6899. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6900. },
  6901. enumerable: true,
  6902. configurable: true
  6903. });
  6904. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6905. };
  6906. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6907. };
  6908. Tools._StartUserMark = function (counterName, condition) {
  6909. if (condition === void 0) { condition = true; }
  6910. if (!condition || !Tools._performance.mark) {
  6911. return;
  6912. }
  6913. Tools._performance.mark(counterName + "-Begin");
  6914. };
  6915. Tools._EndUserMark = function (counterName, condition) {
  6916. if (condition === void 0) { condition = true; }
  6917. if (!condition || !Tools._performance.mark) {
  6918. return;
  6919. }
  6920. Tools._performance.mark(counterName + "-End");
  6921. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6922. };
  6923. Tools._StartPerformanceConsole = function (counterName, condition) {
  6924. if (condition === void 0) { condition = true; }
  6925. if (!condition) {
  6926. return;
  6927. }
  6928. Tools._StartUserMark(counterName, condition);
  6929. if (console.time) {
  6930. console.time(counterName);
  6931. }
  6932. };
  6933. Tools._EndPerformanceConsole = function (counterName, condition) {
  6934. if (condition === void 0) { condition = true; }
  6935. if (!condition) {
  6936. return;
  6937. }
  6938. Tools._EndUserMark(counterName, condition);
  6939. if (console.time) {
  6940. console.timeEnd(counterName);
  6941. }
  6942. };
  6943. Object.defineProperty(Tools, "Now", {
  6944. get: function () {
  6945. if (window.performance && window.performance.now) {
  6946. return window.performance.now();
  6947. }
  6948. return new Date().getTime();
  6949. },
  6950. enumerable: true,
  6951. configurable: true
  6952. });
  6953. /**
  6954. * This method will return the name of the class used to create the instance of the given object.
  6955. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6956. * @param object the object to get the class name from
  6957. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6958. */
  6959. Tools.getClassName = function (object, isType) {
  6960. if (isType === void 0) { isType = false; }
  6961. var name = null;
  6962. if (!isType && object.getClassName) {
  6963. name = object.getClassName();
  6964. }
  6965. else {
  6966. if (object instanceof Object) {
  6967. var classObj = isType ? object : Object.getPrototypeOf(object);
  6968. name = classObj.constructor["__bjsclassName__"];
  6969. }
  6970. if (!name) {
  6971. name = typeof object;
  6972. }
  6973. }
  6974. return name;
  6975. };
  6976. Tools.first = function (array, predicate) {
  6977. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6978. var el = array_1[_i];
  6979. if (predicate(el)) {
  6980. return el;
  6981. }
  6982. }
  6983. };
  6984. /**
  6985. * This method will return the name of the full name of the class, including its owning module (if any).
  6986. * 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).
  6987. * @param object the object to get the class name from
  6988. * @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.
  6989. */
  6990. Tools.getFullClassName = function (object, isType) {
  6991. if (isType === void 0) { isType = false; }
  6992. var className = null;
  6993. var moduleName = null;
  6994. if (!isType && object.getClassName) {
  6995. className = object.getClassName();
  6996. }
  6997. else {
  6998. if (object instanceof Object) {
  6999. var classObj = isType ? object : Object.getPrototypeOf(object);
  7000. className = classObj.constructor["__bjsclassName__"];
  7001. moduleName = classObj.constructor["__bjsmoduleName__"];
  7002. }
  7003. if (!className) {
  7004. className = typeof object;
  7005. }
  7006. }
  7007. if (!className) {
  7008. return null;
  7009. }
  7010. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7011. };
  7012. /**
  7013. * 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.
  7014. * @param array
  7015. */
  7016. Tools.arrayOrStringFeeder = function (array) {
  7017. return function (index) {
  7018. if (index >= array.length) {
  7019. return null;
  7020. }
  7021. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7022. if (val && val.getHashCode) {
  7023. val = val.getHashCode();
  7024. }
  7025. if (typeof val === "string") {
  7026. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7027. }
  7028. return val;
  7029. };
  7030. };
  7031. /**
  7032. * Compute the hashCode of a stream of number
  7033. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7034. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7035. * @return the hash code computed
  7036. */
  7037. Tools.hashCodeFromStream = function (feeder) {
  7038. // Based from here: http://stackoverflow.com/a/7616484/802124
  7039. var hash = 0;
  7040. var index = 0;
  7041. var chr = feeder(index++);
  7042. while (chr != null) {
  7043. hash = ((hash << 5) - hash) + chr;
  7044. hash |= 0; // Convert to 32bit integer
  7045. chr = feeder(index++);
  7046. }
  7047. return hash;
  7048. };
  7049. return Tools;
  7050. }());
  7051. Tools.BaseUrl = "";
  7052. Tools.CorsBehavior = "anonymous";
  7053. Tools.UseFallbackTexture = true;
  7054. // Used in case of a texture loading problem
  7055. 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";
  7056. // Logs
  7057. Tools._NoneLogLevel = 0;
  7058. Tools._MessageLogLevel = 1;
  7059. Tools._WarningLogLevel = 2;
  7060. Tools._ErrorLogLevel = 4;
  7061. Tools._LogCache = "";
  7062. Tools.errorsCount = 0;
  7063. Tools.Log = Tools._LogEnabled;
  7064. Tools.Warn = Tools._WarnEnabled;
  7065. Tools.Error = Tools._ErrorEnabled;
  7066. // Performances
  7067. Tools._PerformanceNoneLogLevel = 0;
  7068. Tools._PerformanceUserMarkLogLevel = 1;
  7069. Tools._PerformanceConsoleLogLevel = 2;
  7070. Tools._performance = window.performance;
  7071. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7072. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7073. BABYLON.Tools = Tools;
  7074. /**
  7075. * This class is used to track a performance counter which is number based.
  7076. * The user has access to many properties which give statistics of different nature
  7077. *
  7078. * The implementer can track two kinds of Performance Counter: time and count
  7079. * 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.
  7080. * 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.
  7081. */
  7082. var PerfCounter = (function () {
  7083. function PerfCounter() {
  7084. this._startMonitoringTime = 0;
  7085. this._min = 0;
  7086. this._max = 0;
  7087. this._average = 0;
  7088. this._lastSecAverage = 0;
  7089. this._current = 0;
  7090. this._totalValueCount = 0;
  7091. this._totalAccumulated = 0;
  7092. this._lastSecAccumulated = 0;
  7093. this._lastSecTime = 0;
  7094. this._lastSecValueCount = 0;
  7095. }
  7096. Object.defineProperty(PerfCounter.prototype, "min", {
  7097. /**
  7098. * Returns the smallest value ever
  7099. */
  7100. get: function () {
  7101. return this._min;
  7102. },
  7103. enumerable: true,
  7104. configurable: true
  7105. });
  7106. Object.defineProperty(PerfCounter.prototype, "max", {
  7107. /**
  7108. * Returns the biggest value ever
  7109. */
  7110. get: function () {
  7111. return this._max;
  7112. },
  7113. enumerable: true,
  7114. configurable: true
  7115. });
  7116. Object.defineProperty(PerfCounter.prototype, "average", {
  7117. /**
  7118. * Returns the average value since the performance counter is running
  7119. */
  7120. get: function () {
  7121. return this._average;
  7122. },
  7123. enumerable: true,
  7124. configurable: true
  7125. });
  7126. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7127. /**
  7128. * Returns the average value of the last second the counter was monitored
  7129. */
  7130. get: function () {
  7131. return this._lastSecAverage;
  7132. },
  7133. enumerable: true,
  7134. configurable: true
  7135. });
  7136. Object.defineProperty(PerfCounter.prototype, "current", {
  7137. /**
  7138. * Returns the current value
  7139. */
  7140. get: function () {
  7141. return this._current;
  7142. },
  7143. enumerable: true,
  7144. configurable: true
  7145. });
  7146. Object.defineProperty(PerfCounter.prototype, "total", {
  7147. get: function () {
  7148. return this._totalAccumulated;
  7149. },
  7150. enumerable: true,
  7151. configurable: true
  7152. });
  7153. /**
  7154. * Call this method to start monitoring a new frame.
  7155. * 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.
  7156. */
  7157. PerfCounter.prototype.fetchNewFrame = function () {
  7158. this._totalValueCount++;
  7159. this._current = 0;
  7160. this._lastSecValueCount++;
  7161. };
  7162. /**
  7163. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7164. * @param newCount the count value to add to the monitored count
  7165. * @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.
  7166. */
  7167. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7168. if (!PerfCounter.Enabled) {
  7169. return;
  7170. }
  7171. this._current += newCount;
  7172. if (fetchResult) {
  7173. this._fetchResult();
  7174. }
  7175. };
  7176. /**
  7177. * Start monitoring this performance counter
  7178. */
  7179. PerfCounter.prototype.beginMonitoring = function () {
  7180. if (!PerfCounter.Enabled) {
  7181. return;
  7182. }
  7183. this._startMonitoringTime = Tools.Now;
  7184. };
  7185. /**
  7186. * Compute the time lapsed since the previous beginMonitoring() call.
  7187. * @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
  7188. */
  7189. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7190. if (newFrame === void 0) { newFrame = true; }
  7191. if (!PerfCounter.Enabled) {
  7192. return;
  7193. }
  7194. if (newFrame) {
  7195. this.fetchNewFrame();
  7196. }
  7197. var currentTime = Tools.Now;
  7198. this._current = currentTime - this._startMonitoringTime;
  7199. if (newFrame) {
  7200. this._fetchResult();
  7201. }
  7202. };
  7203. PerfCounter.prototype._fetchResult = function () {
  7204. this._totalAccumulated += this._current;
  7205. this._lastSecAccumulated += this._current;
  7206. // Min/Max update
  7207. this._min = Math.min(this._min, this._current);
  7208. this._max = Math.max(this._max, this._current);
  7209. this._average = this._totalAccumulated / this._totalValueCount;
  7210. // Reset last sec?
  7211. var now = Tools.Now;
  7212. if ((now - this._lastSecTime) > 1000) {
  7213. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7214. this._lastSecTime = now;
  7215. this._lastSecAccumulated = 0;
  7216. this._lastSecValueCount = 0;
  7217. }
  7218. };
  7219. return PerfCounter;
  7220. }());
  7221. PerfCounter.Enabled = true;
  7222. BABYLON.PerfCounter = PerfCounter;
  7223. /**
  7224. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7225. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7226. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7227. * @param name The name of the class, case should be preserved
  7228. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7229. */
  7230. function className(name, module) {
  7231. return function (target) {
  7232. target["__bjsclassName__"] = name;
  7233. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7234. };
  7235. }
  7236. BABYLON.className = className;
  7237. /**
  7238. * An implementation of a loop for asynchronous functions.
  7239. */
  7240. var AsyncLoop = (function () {
  7241. /**
  7242. * Constroctor.
  7243. * @param iterations the number of iterations.
  7244. * @param _fn the function to run each iteration
  7245. * @param _successCallback the callback that will be called upon succesful execution
  7246. * @param offset starting offset.
  7247. */
  7248. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7249. if (offset === void 0) { offset = 0; }
  7250. this.iterations = iterations;
  7251. this._fn = _fn;
  7252. this._successCallback = _successCallback;
  7253. this.index = offset - 1;
  7254. this._done = false;
  7255. }
  7256. /**
  7257. * Execute the next iteration. Must be called after the last iteration was finished.
  7258. */
  7259. AsyncLoop.prototype.executeNext = function () {
  7260. if (!this._done) {
  7261. if (this.index + 1 < this.iterations) {
  7262. ++this.index;
  7263. this._fn(this);
  7264. }
  7265. else {
  7266. this.breakLoop();
  7267. }
  7268. }
  7269. };
  7270. /**
  7271. * Break the loop and run the success callback.
  7272. */
  7273. AsyncLoop.prototype.breakLoop = function () {
  7274. this._done = true;
  7275. this._successCallback();
  7276. };
  7277. /**
  7278. * Helper function
  7279. */
  7280. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7281. if (offset === void 0) { offset = 0; }
  7282. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7283. loop.executeNext();
  7284. return loop;
  7285. };
  7286. /**
  7287. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7288. * @param iterations total number of iterations
  7289. * @param syncedIterations number of synchronous iterations in each async iteration.
  7290. * @param fn the function to call each iteration.
  7291. * @param callback a success call back that will be called when iterating stops.
  7292. * @param breakFunction a break condition (optional)
  7293. * @param timeout timeout settings for the setTimeout function. default - 0.
  7294. * @constructor
  7295. */
  7296. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7297. if (timeout === void 0) { timeout = 0; }
  7298. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7299. if (breakFunction && breakFunction())
  7300. loop.breakLoop();
  7301. else {
  7302. setTimeout(function () {
  7303. for (var i = 0; i < syncedIterations; ++i) {
  7304. var iteration = (loop.index * syncedIterations) + i;
  7305. if (iteration >= iterations)
  7306. break;
  7307. fn(iteration);
  7308. if (breakFunction && breakFunction()) {
  7309. loop.breakLoop();
  7310. break;
  7311. }
  7312. }
  7313. loop.executeNext();
  7314. }, timeout);
  7315. }
  7316. }, callback);
  7317. };
  7318. return AsyncLoop;
  7319. }());
  7320. BABYLON.AsyncLoop = AsyncLoop;
  7321. })(BABYLON || (BABYLON = {}));
  7322. //# sourceMappingURL=babylon.tools.js.map
  7323. var BABYLON;
  7324. (function (BABYLON) {
  7325. var Internals;
  7326. (function (Internals) {
  7327. var _AlphaState = (function () {
  7328. /**
  7329. * Initializes the state.
  7330. */
  7331. function _AlphaState() {
  7332. this._isAlphaBlendDirty = false;
  7333. this._isBlendFunctionParametersDirty = false;
  7334. this._alphaBlend = false;
  7335. this._blendFunctionParameters = new Array(4);
  7336. this.reset();
  7337. }
  7338. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7339. get: function () {
  7340. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7341. },
  7342. enumerable: true,
  7343. configurable: true
  7344. });
  7345. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7346. get: function () {
  7347. return this._alphaBlend;
  7348. },
  7349. set: function (value) {
  7350. if (this._alphaBlend === value) {
  7351. return;
  7352. }
  7353. this._alphaBlend = value;
  7354. this._isAlphaBlendDirty = true;
  7355. },
  7356. enumerable: true,
  7357. configurable: true
  7358. });
  7359. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7360. if (this._blendFunctionParameters[0] === value0 &&
  7361. this._blendFunctionParameters[1] === value1 &&
  7362. this._blendFunctionParameters[2] === value2 &&
  7363. this._blendFunctionParameters[3] === value3) {
  7364. return;
  7365. }
  7366. this._blendFunctionParameters[0] = value0;
  7367. this._blendFunctionParameters[1] = value1;
  7368. this._blendFunctionParameters[2] = value2;
  7369. this._blendFunctionParameters[3] = value3;
  7370. this._isBlendFunctionParametersDirty = true;
  7371. };
  7372. _AlphaState.prototype.reset = function () {
  7373. this._alphaBlend = false;
  7374. this._blendFunctionParameters[0] = null;
  7375. this._blendFunctionParameters[1] = null;
  7376. this._blendFunctionParameters[2] = null;
  7377. this._blendFunctionParameters[3] = null;
  7378. this._isAlphaBlendDirty = true;
  7379. this._isBlendFunctionParametersDirty = false;
  7380. };
  7381. _AlphaState.prototype.apply = function (gl) {
  7382. if (!this.isDirty) {
  7383. return;
  7384. }
  7385. // Alpha blend
  7386. if (this._isAlphaBlendDirty) {
  7387. if (this._alphaBlend) {
  7388. gl.enable(gl.BLEND);
  7389. }
  7390. else {
  7391. gl.disable(gl.BLEND);
  7392. }
  7393. this._isAlphaBlendDirty = false;
  7394. }
  7395. // Alpha function
  7396. if (this._isBlendFunctionParametersDirty) {
  7397. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7398. this._isBlendFunctionParametersDirty = false;
  7399. }
  7400. };
  7401. return _AlphaState;
  7402. }());
  7403. Internals._AlphaState = _AlphaState;
  7404. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7405. })(BABYLON || (BABYLON = {}));
  7406. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7407. var BABYLON;
  7408. (function (BABYLON) {
  7409. var Internals;
  7410. (function (Internals) {
  7411. var _DepthCullingState = (function () {
  7412. /**
  7413. * Initializes the state.
  7414. */
  7415. function _DepthCullingState() {
  7416. this._isDepthTestDirty = false;
  7417. this._isDepthMaskDirty = false;
  7418. this._isDepthFuncDirty = false;
  7419. this._isCullFaceDirty = false;
  7420. this._isCullDirty = false;
  7421. this._isZOffsetDirty = false;
  7422. this.reset();
  7423. }
  7424. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7425. get: function () {
  7426. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7427. },
  7428. enumerable: true,
  7429. configurable: true
  7430. });
  7431. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7432. get: function () {
  7433. return this._zOffset;
  7434. },
  7435. set: function (value) {
  7436. if (this._zOffset === value) {
  7437. return;
  7438. }
  7439. this._zOffset = value;
  7440. this._isZOffsetDirty = true;
  7441. },
  7442. enumerable: true,
  7443. configurable: true
  7444. });
  7445. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7446. get: function () {
  7447. return this._cullFace;
  7448. },
  7449. set: function (value) {
  7450. if (this._cullFace === value) {
  7451. return;
  7452. }
  7453. this._cullFace = value;
  7454. this._isCullFaceDirty = true;
  7455. },
  7456. enumerable: true,
  7457. configurable: true
  7458. });
  7459. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7460. get: function () {
  7461. return this._cull;
  7462. },
  7463. set: function (value) {
  7464. if (this._cull === value) {
  7465. return;
  7466. }
  7467. this._cull = value;
  7468. this._isCullDirty = true;
  7469. },
  7470. enumerable: true,
  7471. configurable: true
  7472. });
  7473. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7474. get: function () {
  7475. return this._depthFunc;
  7476. },
  7477. set: function (value) {
  7478. if (this._depthFunc === value) {
  7479. return;
  7480. }
  7481. this._depthFunc = value;
  7482. this._isDepthFuncDirty = true;
  7483. },
  7484. enumerable: true,
  7485. configurable: true
  7486. });
  7487. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7488. get: function () {
  7489. return this._depthMask;
  7490. },
  7491. set: function (value) {
  7492. if (this._depthMask === value) {
  7493. return;
  7494. }
  7495. this._depthMask = value;
  7496. this._isDepthMaskDirty = true;
  7497. },
  7498. enumerable: true,
  7499. configurable: true
  7500. });
  7501. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7502. get: function () {
  7503. return this._depthTest;
  7504. },
  7505. set: function (value) {
  7506. if (this._depthTest === value) {
  7507. return;
  7508. }
  7509. this._depthTest = value;
  7510. this._isDepthTestDirty = true;
  7511. },
  7512. enumerable: true,
  7513. configurable: true
  7514. });
  7515. _DepthCullingState.prototype.reset = function () {
  7516. this._depthMask = true;
  7517. this._depthTest = true;
  7518. this._depthFunc = null;
  7519. this._cullFace = null;
  7520. this._cull = null;
  7521. this._zOffset = 0;
  7522. this._isDepthTestDirty = true;
  7523. this._isDepthMaskDirty = true;
  7524. this._isDepthFuncDirty = false;
  7525. this._isCullFaceDirty = false;
  7526. this._isCullDirty = false;
  7527. this._isZOffsetDirty = false;
  7528. };
  7529. _DepthCullingState.prototype.apply = function (gl) {
  7530. if (!this.isDirty) {
  7531. return;
  7532. }
  7533. // Cull
  7534. if (this._isCullDirty) {
  7535. if (this.cull) {
  7536. gl.enable(gl.CULL_FACE);
  7537. }
  7538. else {
  7539. gl.disable(gl.CULL_FACE);
  7540. }
  7541. this._isCullDirty = false;
  7542. }
  7543. // Cull face
  7544. if (this._isCullFaceDirty) {
  7545. gl.cullFace(this.cullFace);
  7546. this._isCullFaceDirty = false;
  7547. }
  7548. // Depth mask
  7549. if (this._isDepthMaskDirty) {
  7550. gl.depthMask(this.depthMask);
  7551. this._isDepthMaskDirty = false;
  7552. }
  7553. // Depth test
  7554. if (this._isDepthTestDirty) {
  7555. if (this.depthTest) {
  7556. gl.enable(gl.DEPTH_TEST);
  7557. }
  7558. else {
  7559. gl.disable(gl.DEPTH_TEST);
  7560. }
  7561. this._isDepthTestDirty = false;
  7562. }
  7563. // Depth func
  7564. if (this._isDepthFuncDirty) {
  7565. gl.depthFunc(this.depthFunc);
  7566. this._isDepthFuncDirty = false;
  7567. }
  7568. // zOffset
  7569. if (this._isZOffsetDirty) {
  7570. if (this.zOffset) {
  7571. gl.enable(gl.POLYGON_OFFSET_FILL);
  7572. gl.polygonOffset(this.zOffset, 0);
  7573. }
  7574. else {
  7575. gl.disable(gl.POLYGON_OFFSET_FILL);
  7576. }
  7577. this._isZOffsetDirty = false;
  7578. }
  7579. };
  7580. return _DepthCullingState;
  7581. }());
  7582. Internals._DepthCullingState = _DepthCullingState;
  7583. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7584. })(BABYLON || (BABYLON = {}));
  7585. //# sourceMappingURL=babylon.depthCullingState.js.map
  7586. var BABYLON;
  7587. (function (BABYLON) {
  7588. var Internals;
  7589. (function (Internals) {
  7590. var _StencilState = (function () {
  7591. function _StencilState() {
  7592. this._isStencilTestDirty = false;
  7593. this._isStencilMaskDirty = false;
  7594. this._isStencilFuncDirty = false;
  7595. this._isStencilOpDirty = false;
  7596. this.reset();
  7597. }
  7598. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7599. get: function () {
  7600. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7601. },
  7602. enumerable: true,
  7603. configurable: true
  7604. });
  7605. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7606. get: function () {
  7607. return this._stencilFunc;
  7608. },
  7609. set: function (value) {
  7610. if (this._stencilFunc === value) {
  7611. return;
  7612. }
  7613. this._stencilFunc = value;
  7614. this._isStencilFuncDirty = true;
  7615. },
  7616. enumerable: true,
  7617. configurable: true
  7618. });
  7619. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7620. get: function () {
  7621. return this._stencilFuncRef;
  7622. },
  7623. set: function (value) {
  7624. if (this._stencilFuncRef === value) {
  7625. return;
  7626. }
  7627. this._stencilFuncRef = value;
  7628. this._isStencilFuncDirty = true;
  7629. },
  7630. enumerable: true,
  7631. configurable: true
  7632. });
  7633. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7634. get: function () {
  7635. return this._stencilFuncMask;
  7636. },
  7637. set: function (value) {
  7638. if (this._stencilFuncMask === value) {
  7639. return;
  7640. }
  7641. this._stencilFuncMask = value;
  7642. this._isStencilFuncDirty = true;
  7643. },
  7644. enumerable: true,
  7645. configurable: true
  7646. });
  7647. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7648. get: function () {
  7649. return this._stencilOpStencilFail;
  7650. },
  7651. set: function (value) {
  7652. if (this._stencilOpStencilFail === value) {
  7653. return;
  7654. }
  7655. this._stencilOpStencilFail = value;
  7656. this._isStencilOpDirty = true;
  7657. },
  7658. enumerable: true,
  7659. configurable: true
  7660. });
  7661. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7662. get: function () {
  7663. return this._stencilOpDepthFail;
  7664. },
  7665. set: function (value) {
  7666. if (this._stencilOpDepthFail === value) {
  7667. return;
  7668. }
  7669. this._stencilOpDepthFail = value;
  7670. this._isStencilOpDirty = true;
  7671. },
  7672. enumerable: true,
  7673. configurable: true
  7674. });
  7675. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7676. get: function () {
  7677. return this._stencilOpStencilDepthPass;
  7678. },
  7679. set: function (value) {
  7680. if (this._stencilOpStencilDepthPass === value) {
  7681. return;
  7682. }
  7683. this._stencilOpStencilDepthPass = value;
  7684. this._isStencilOpDirty = true;
  7685. },
  7686. enumerable: true,
  7687. configurable: true
  7688. });
  7689. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7690. get: function () {
  7691. return this._stencilMask;
  7692. },
  7693. set: function (value) {
  7694. if (this._stencilMask === value) {
  7695. return;
  7696. }
  7697. this._stencilMask = value;
  7698. this._isStencilMaskDirty = true;
  7699. },
  7700. enumerable: true,
  7701. configurable: true
  7702. });
  7703. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7704. get: function () {
  7705. return this._stencilTest;
  7706. },
  7707. set: function (value) {
  7708. if (this._stencilTest === value) {
  7709. return;
  7710. }
  7711. this._stencilTest = value;
  7712. this._isStencilTestDirty = true;
  7713. },
  7714. enumerable: true,
  7715. configurable: true
  7716. });
  7717. _StencilState.prototype.reset = function () {
  7718. this._stencilTest = false;
  7719. this._stencilMask = 0xFF;
  7720. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7721. this._stencilFuncRef = 1;
  7722. this._stencilFuncMask = 0xFF;
  7723. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7724. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7725. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7726. this._isStencilTestDirty = true;
  7727. this._isStencilMaskDirty = true;
  7728. this._isStencilFuncDirty = true;
  7729. this._isStencilOpDirty = true;
  7730. };
  7731. _StencilState.prototype.apply = function (gl) {
  7732. if (!this.isDirty) {
  7733. return;
  7734. }
  7735. // Stencil test
  7736. if (this._isStencilTestDirty) {
  7737. if (this.stencilTest) {
  7738. gl.enable(gl.STENCIL_TEST);
  7739. }
  7740. else {
  7741. gl.disable(gl.STENCIL_TEST);
  7742. }
  7743. this._isStencilTestDirty = false;
  7744. }
  7745. // Stencil mask
  7746. if (this._isStencilMaskDirty) {
  7747. gl.stencilMask(this.stencilMask);
  7748. this._isStencilMaskDirty = false;
  7749. }
  7750. // Stencil func
  7751. if (this._isStencilFuncDirty) {
  7752. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7753. this._isStencilFuncDirty = false;
  7754. }
  7755. // Stencil op
  7756. if (this._isStencilOpDirty) {
  7757. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7758. this._isStencilOpDirty = false;
  7759. }
  7760. };
  7761. return _StencilState;
  7762. }());
  7763. Internals._StencilState = _StencilState;
  7764. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7765. })(BABYLON || (BABYLON = {}));
  7766. //# sourceMappingURL=babylon.stencilState.js.map
  7767. var BABYLON;
  7768. (function (BABYLON) {
  7769. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7770. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7771. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7772. gl.compileShader(shader);
  7773. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7774. throw new Error(gl.getShaderInfoLog(shader));
  7775. }
  7776. return shader;
  7777. };
  7778. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7779. var magFilter = gl.NEAREST;
  7780. var minFilter = gl.NEAREST;
  7781. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7782. magFilter = gl.LINEAR;
  7783. if (generateMipMaps) {
  7784. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7785. }
  7786. else {
  7787. minFilter = gl.LINEAR;
  7788. }
  7789. }
  7790. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7791. magFilter = gl.LINEAR;
  7792. if (generateMipMaps) {
  7793. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7794. }
  7795. else {
  7796. minFilter = gl.LINEAR;
  7797. }
  7798. }
  7799. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7800. magFilter = gl.NEAREST;
  7801. if (generateMipMaps) {
  7802. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7803. }
  7804. else {
  7805. minFilter = gl.NEAREST;
  7806. }
  7807. }
  7808. return {
  7809. min: minFilter,
  7810. mag: magFilter
  7811. };
  7812. };
  7813. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7814. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7815. var engine = scene.getEngine();
  7816. if (!engine) {
  7817. return;
  7818. }
  7819. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7820. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7821. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7822. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7823. texture._baseWidth = width;
  7824. texture._baseHeight = height;
  7825. texture._width = potWidth;
  7826. texture._height = potHeight;
  7827. texture.isReady = true;
  7828. processFunction(potWidth, potHeight);
  7829. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7830. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7831. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7832. if (!noMipmap && !isCompressed) {
  7833. gl.generateMipmap(gl.TEXTURE_2D);
  7834. }
  7835. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7836. engine.resetTextureCache();
  7837. scene._removePendingData(texture);
  7838. texture.onLoadedCallbacks.forEach(function (callback) {
  7839. callback();
  7840. });
  7841. texture.onLoadedCallbacks = [];
  7842. };
  7843. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7844. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7845. var img;
  7846. var onload = function () {
  7847. loadedImages[index] = img;
  7848. loadedImages._internalCount++;
  7849. scene._removePendingData(img);
  7850. if (loadedImages._internalCount === 6) {
  7851. onfinish(loadedImages);
  7852. }
  7853. };
  7854. var onerror = function () {
  7855. scene._removePendingData(img);
  7856. if (onErrorCallBack) {
  7857. onErrorCallBack();
  7858. }
  7859. };
  7860. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7861. scene._addPendingData(img);
  7862. };
  7863. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7864. if (onError === void 0) { onError = null; }
  7865. var loadedImages = [];
  7866. loadedImages._internalCount = 0;
  7867. for (var index = 0; index < 6; index++) {
  7868. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7869. }
  7870. };
  7871. var InstancingAttributeInfo = (function () {
  7872. function InstancingAttributeInfo() {
  7873. }
  7874. return InstancingAttributeInfo;
  7875. }());
  7876. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7877. var EngineCapabilities = (function () {
  7878. function EngineCapabilities() {
  7879. }
  7880. return EngineCapabilities;
  7881. }());
  7882. BABYLON.EngineCapabilities = EngineCapabilities;
  7883. /**
  7884. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7885. */
  7886. var Engine = (function () {
  7887. /**
  7888. * @constructor
  7889. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7890. * @param {boolean} [antialias] - enable antialias
  7891. * @param options - further options to be sent to the getContext function
  7892. */
  7893. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7894. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7895. var _this = this;
  7896. // Public members
  7897. this.isFullscreen = false;
  7898. this.isPointerLock = false;
  7899. this.cullBackFaces = true;
  7900. this.renderEvenInBackground = true;
  7901. this.preventCacheWipeBetweenFrames = false;
  7902. // To enable/disable IDB support and avoid XHR on .manifest
  7903. this.enableOfflineSupport = true;
  7904. this.scenes = new Array();
  7905. this._windowIsBackground = false;
  7906. this._webGLVersion = 1.0;
  7907. this._badOS = false;
  7908. this._drawCalls = new BABYLON.PerfCounter();
  7909. this._renderingQueueLaunched = false;
  7910. this._activeRenderLoops = [];
  7911. // FPS
  7912. this.fpsRange = 60;
  7913. this.previousFramesDuration = [];
  7914. this.fps = 60;
  7915. this.deltaTime = 0;
  7916. // States
  7917. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7918. this._stencilState = new BABYLON.Internals._StencilState();
  7919. this._alphaState = new BABYLON.Internals._AlphaState();
  7920. this._alphaMode = Engine.ALPHA_DISABLE;
  7921. // Cache
  7922. this._loadedTexturesCache = new Array();
  7923. this._maxTextureChannels = 16;
  7924. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7925. this._compiledEffects = {};
  7926. this._vertexAttribArraysEnabled = [];
  7927. this._uintIndicesCurrentlySet = false;
  7928. this._currentBoundBuffer = new Array();
  7929. this._currentBufferPointers = [];
  7930. this._currentInstanceLocations = new Array();
  7931. this._currentInstanceBuffers = new Array();
  7932. this._vaoRecordInProgress = false;
  7933. this._mustWipeVertexAttributes = false;
  7934. // Hardware supported Compressed Textures
  7935. this._texturesSupported = new Array();
  7936. this._onVRFullScreenTriggered = function () {
  7937. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7938. //get the old size before we change
  7939. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7940. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7941. //get the width and height, change the render size
  7942. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7943. var width, height;
  7944. _this.setHardwareScalingLevel(1);
  7945. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7946. }
  7947. else {
  7948. //When the specs are implemented, need to uncomment this.
  7949. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7950. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7951. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7952. _this._vrDisplayEnabled = undefined;
  7953. }
  7954. };
  7955. this._renderingCanvas = canvas;
  7956. Engine.Instances.push(this);
  7957. this._externalData = new BABYLON.StringDictionary();
  7958. options = options || {};
  7959. if (antialias != null) {
  7960. options.antialias = antialias;
  7961. }
  7962. if (options.preserveDrawingBuffer === undefined) {
  7963. options.preserveDrawingBuffer = false;
  7964. }
  7965. if (options.audioEngine === undefined) {
  7966. options.audioEngine = true;
  7967. }
  7968. if (options.stencil === undefined) {
  7969. options.stencil = true;
  7970. }
  7971. // GL
  7972. if (!options.disableWebGL2Support) {
  7973. try {
  7974. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7975. if (this._gl) {
  7976. this._webGLVersion = 2.0;
  7977. }
  7978. }
  7979. catch (e) {
  7980. // Do nothing
  7981. }
  7982. }
  7983. if (!this._gl) {
  7984. if (!canvas) {
  7985. throw new Error("The provided canvas is null or undefined.");
  7986. }
  7987. try {
  7988. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7989. }
  7990. catch (e) {
  7991. throw new Error("WebGL not supported");
  7992. }
  7993. }
  7994. if (!this._gl) {
  7995. throw new Error("WebGL not supported");
  7996. }
  7997. this._onBlur = function () {
  7998. _this._windowIsBackground = true;
  7999. };
  8000. this._onFocus = function () {
  8001. _this._windowIsBackground = false;
  8002. };
  8003. window.addEventListener("blur", this._onBlur);
  8004. window.addEventListener("focus", this._onFocus);
  8005. // Viewport
  8006. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8007. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8008. this.resize();
  8009. // Caps
  8010. this._isStencilEnable = options.stencil;
  8011. this._caps = new EngineCapabilities();
  8012. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8013. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8014. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8015. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8016. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8017. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8018. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8019. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8020. // Infos
  8021. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8022. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8023. if (rendererInfo != null) {
  8024. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8025. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8026. }
  8027. if (!this._glVendor) {
  8028. this._glVendor = "Unknown vendor";
  8029. }
  8030. if (!this._glRenderer) {
  8031. this._glRenderer = "Unknown renderer";
  8032. }
  8033. // Extensions
  8034. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8035. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8036. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8037. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8038. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8039. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8040. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8041. 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');
  8042. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8043. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8044. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8045. this._caps.highPrecisionShaderSupported = true;
  8046. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8047. // Checks if some of the format renders first to allow the use of webgl inspector.
  8048. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8049. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8050. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8051. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8052. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8053. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8054. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8055. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8056. // Vertex array object
  8057. if (this._webGLVersion > 1) {
  8058. this._caps.vertexArrayObject = true;
  8059. }
  8060. else {
  8061. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8062. if (vertexArrayObjectExtension != null) {
  8063. this._caps.vertexArrayObject = true;
  8064. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8065. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8066. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8067. }
  8068. else {
  8069. this._caps.vertexArrayObject = false;
  8070. }
  8071. }
  8072. // Instances count
  8073. if (this._webGLVersion > 1) {
  8074. this._caps.instancedArrays = true;
  8075. }
  8076. else {
  8077. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8078. if (instanceExtension != null) {
  8079. this._caps.instancedArrays = true;
  8080. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8081. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8082. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8083. }
  8084. else {
  8085. this._caps.instancedArrays = false;
  8086. }
  8087. }
  8088. // Intelligently add supported compressed formats in order to check for.
  8089. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8090. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8091. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8092. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8093. if (this._caps.astc)
  8094. this.texturesSupported.push('-astc.ktx');
  8095. if (this._caps.s3tc)
  8096. this.texturesSupported.push('-dxt.ktx');
  8097. if (this._caps.pvrtc)
  8098. this.texturesSupported.push('-pvrtc.ktx');
  8099. if (this._caps.etc2)
  8100. this.texturesSupported.push('-etc2.ktx');
  8101. if (this._caps.etc1)
  8102. this.texturesSupported.push('-etc1.ktx');
  8103. if (this._gl.getShaderPrecisionFormat) {
  8104. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8105. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8106. }
  8107. // Depth buffer
  8108. this.setDepthBuffer(true);
  8109. this.setDepthFunctionToLessOrEqual();
  8110. this.setDepthWrite(true);
  8111. // Fullscreen
  8112. this._onFullscreenChange = function () {
  8113. if (document.fullscreen !== undefined) {
  8114. _this.isFullscreen = document.fullscreen;
  8115. }
  8116. else if (document.mozFullScreen !== undefined) {
  8117. _this.isFullscreen = document.mozFullScreen;
  8118. }
  8119. else if (document.webkitIsFullScreen !== undefined) {
  8120. _this.isFullscreen = document.webkitIsFullScreen;
  8121. }
  8122. else if (document.msIsFullScreen !== undefined) {
  8123. _this.isFullscreen = document.msIsFullScreen;
  8124. }
  8125. // Pointer lock
  8126. if (_this.isFullscreen && _this._pointerLockRequested) {
  8127. canvas.requestPointerLock = canvas.requestPointerLock ||
  8128. canvas.msRequestPointerLock ||
  8129. canvas.mozRequestPointerLock ||
  8130. canvas.webkitRequestPointerLock;
  8131. if (canvas.requestPointerLock) {
  8132. canvas.requestPointerLock();
  8133. }
  8134. }
  8135. };
  8136. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8137. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8138. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8139. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8140. // Pointer lock
  8141. this._onPointerLockChange = function () {
  8142. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8143. document.webkitPointerLockElement === canvas ||
  8144. document.msPointerLockElement === canvas ||
  8145. document.pointerLockElement === canvas);
  8146. };
  8147. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8148. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8149. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8150. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8151. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8152. Engine.audioEngine = new BABYLON.AudioEngine();
  8153. }
  8154. //default loading screen
  8155. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  8156. //Load WebVR Devices
  8157. if (options.autoEnableWebVR) {
  8158. this.initWebVR();
  8159. }
  8160. //Detect if we are running on a faulty buggy OS.
  8161. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  8162. //ua sniffing is the tool of the devil.
  8163. this._badOS = regexp.test(navigator.userAgent);
  8164. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8165. }
  8166. Object.defineProperty(Engine, "LastCreatedEngine", {
  8167. get: function () {
  8168. if (Engine.Instances.length === 0) {
  8169. return null;
  8170. }
  8171. return Engine.Instances[Engine.Instances.length - 1];
  8172. },
  8173. enumerable: true,
  8174. configurable: true
  8175. });
  8176. Object.defineProperty(Engine, "LastCreatedScene", {
  8177. get: function () {
  8178. var lastCreatedEngine = Engine.LastCreatedEngine;
  8179. if (!lastCreatedEngine) {
  8180. return null;
  8181. }
  8182. if (lastCreatedEngine.scenes.length === 0) {
  8183. return null;
  8184. }
  8185. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8186. },
  8187. enumerable: true,
  8188. configurable: true
  8189. });
  8190. /**
  8191. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8192. */
  8193. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8194. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8195. var engine = Engine.Instances[engineIndex];
  8196. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8197. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8198. }
  8199. }
  8200. };
  8201. Object.defineProperty(Engine, "NEVER", {
  8202. get: function () {
  8203. return Engine._NEVER;
  8204. },
  8205. enumerable: true,
  8206. configurable: true
  8207. });
  8208. Object.defineProperty(Engine, "ALWAYS", {
  8209. get: function () {
  8210. return Engine._ALWAYS;
  8211. },
  8212. enumerable: true,
  8213. configurable: true
  8214. });
  8215. Object.defineProperty(Engine, "LESS", {
  8216. get: function () {
  8217. return Engine._LESS;
  8218. },
  8219. enumerable: true,
  8220. configurable: true
  8221. });
  8222. Object.defineProperty(Engine, "EQUAL", {
  8223. get: function () {
  8224. return Engine._EQUAL;
  8225. },
  8226. enumerable: true,
  8227. configurable: true
  8228. });
  8229. Object.defineProperty(Engine, "LEQUAL", {
  8230. get: function () {
  8231. return Engine._LEQUAL;
  8232. },
  8233. enumerable: true,
  8234. configurable: true
  8235. });
  8236. Object.defineProperty(Engine, "GREATER", {
  8237. get: function () {
  8238. return Engine._GREATER;
  8239. },
  8240. enumerable: true,
  8241. configurable: true
  8242. });
  8243. Object.defineProperty(Engine, "GEQUAL", {
  8244. get: function () {
  8245. return Engine._GEQUAL;
  8246. },
  8247. enumerable: true,
  8248. configurable: true
  8249. });
  8250. Object.defineProperty(Engine, "NOTEQUAL", {
  8251. get: function () {
  8252. return Engine._NOTEQUAL;
  8253. },
  8254. enumerable: true,
  8255. configurable: true
  8256. });
  8257. Object.defineProperty(Engine, "KEEP", {
  8258. get: function () {
  8259. return Engine._KEEP;
  8260. },
  8261. enumerable: true,
  8262. configurable: true
  8263. });
  8264. Object.defineProperty(Engine, "REPLACE", {
  8265. get: function () {
  8266. return Engine._REPLACE;
  8267. },
  8268. enumerable: true,
  8269. configurable: true
  8270. });
  8271. Object.defineProperty(Engine, "INCR", {
  8272. get: function () {
  8273. return Engine._INCR;
  8274. },
  8275. enumerable: true,
  8276. configurable: true
  8277. });
  8278. Object.defineProperty(Engine, "DECR", {
  8279. get: function () {
  8280. return Engine._DECR;
  8281. },
  8282. enumerable: true,
  8283. configurable: true
  8284. });
  8285. Object.defineProperty(Engine, "INVERT", {
  8286. get: function () {
  8287. return Engine._INVERT;
  8288. },
  8289. enumerable: true,
  8290. configurable: true
  8291. });
  8292. Object.defineProperty(Engine, "INCR_WRAP", {
  8293. get: function () {
  8294. return Engine._INCR_WRAP;
  8295. },
  8296. enumerable: true,
  8297. configurable: true
  8298. });
  8299. Object.defineProperty(Engine, "DECR_WRAP", {
  8300. get: function () {
  8301. return Engine._DECR_WRAP;
  8302. },
  8303. enumerable: true,
  8304. configurable: true
  8305. });
  8306. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8307. get: function () {
  8308. return Engine._ALPHA_DISABLE;
  8309. },
  8310. enumerable: true,
  8311. configurable: true
  8312. });
  8313. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8314. get: function () {
  8315. return Engine._ALPHA_ONEONE;
  8316. },
  8317. enumerable: true,
  8318. configurable: true
  8319. });
  8320. Object.defineProperty(Engine, "ALPHA_ADD", {
  8321. get: function () {
  8322. return Engine._ALPHA_ADD;
  8323. },
  8324. enumerable: true,
  8325. configurable: true
  8326. });
  8327. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8328. get: function () {
  8329. return Engine._ALPHA_COMBINE;
  8330. },
  8331. enumerable: true,
  8332. configurable: true
  8333. });
  8334. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8335. get: function () {
  8336. return Engine._ALPHA_SUBTRACT;
  8337. },
  8338. enumerable: true,
  8339. configurable: true
  8340. });
  8341. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8342. get: function () {
  8343. return Engine._ALPHA_MULTIPLY;
  8344. },
  8345. enumerable: true,
  8346. configurable: true
  8347. });
  8348. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8349. get: function () {
  8350. return Engine._ALPHA_MAXIMIZED;
  8351. },
  8352. enumerable: true,
  8353. configurable: true
  8354. });
  8355. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8356. get: function () {
  8357. return Engine._ALPHA_PREMULTIPLIED;
  8358. },
  8359. enumerable: true,
  8360. configurable: true
  8361. });
  8362. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8363. get: function () {
  8364. return Engine._DELAYLOADSTATE_NONE;
  8365. },
  8366. enumerable: true,
  8367. configurable: true
  8368. });
  8369. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8370. get: function () {
  8371. return Engine._DELAYLOADSTATE_LOADED;
  8372. },
  8373. enumerable: true,
  8374. configurable: true
  8375. });
  8376. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8377. get: function () {
  8378. return Engine._DELAYLOADSTATE_LOADING;
  8379. },
  8380. enumerable: true,
  8381. configurable: true
  8382. });
  8383. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8384. get: function () {
  8385. return Engine._DELAYLOADSTATE_NOTLOADED;
  8386. },
  8387. enumerable: true,
  8388. configurable: true
  8389. });
  8390. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8391. get: function () {
  8392. return Engine._TEXTUREFORMAT_ALPHA;
  8393. },
  8394. enumerable: true,
  8395. configurable: true
  8396. });
  8397. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8398. get: function () {
  8399. return Engine._TEXTUREFORMAT_LUMINANCE;
  8400. },
  8401. enumerable: true,
  8402. configurable: true
  8403. });
  8404. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8405. get: function () {
  8406. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8407. },
  8408. enumerable: true,
  8409. configurable: true
  8410. });
  8411. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8412. get: function () {
  8413. return Engine._TEXTUREFORMAT_RGB;
  8414. },
  8415. enumerable: true,
  8416. configurable: true
  8417. });
  8418. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8419. get: function () {
  8420. return Engine._TEXTUREFORMAT_RGBA;
  8421. },
  8422. enumerable: true,
  8423. configurable: true
  8424. });
  8425. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8426. get: function () {
  8427. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8428. },
  8429. enumerable: true,
  8430. configurable: true
  8431. });
  8432. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8433. get: function () {
  8434. return Engine._TEXTURETYPE_FLOAT;
  8435. },
  8436. enumerable: true,
  8437. configurable: true
  8438. });
  8439. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8440. get: function () {
  8441. return Engine._TEXTURETYPE_HALF_FLOAT;
  8442. },
  8443. enumerable: true,
  8444. configurable: true
  8445. });
  8446. Object.defineProperty(Engine, "Version", {
  8447. get: function () {
  8448. return "3.0-alpha";
  8449. },
  8450. enumerable: true,
  8451. configurable: true
  8452. });
  8453. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8454. get: function () {
  8455. return this._texturesSupported;
  8456. },
  8457. enumerable: true,
  8458. configurable: true
  8459. });
  8460. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8461. get: function () {
  8462. return this._textureFormatInUse;
  8463. },
  8464. enumerable: true,
  8465. configurable: true
  8466. });
  8467. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8468. get: function () {
  8469. return this._webGLVersion;
  8470. },
  8471. enumerable: true,
  8472. configurable: true
  8473. });
  8474. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8475. /**
  8476. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8477. */
  8478. get: function () {
  8479. return this._isStencilEnable;
  8480. },
  8481. enumerable: true,
  8482. configurable: true
  8483. });
  8484. Engine.prototype._prepareWorkingCanvas = function () {
  8485. if (this._workingCanvas) {
  8486. return;
  8487. }
  8488. this._workingCanvas = document.createElement("canvas");
  8489. this._workingContext = this._workingCanvas.getContext("2d");
  8490. };
  8491. Engine.prototype.resetTextureCache = function () {
  8492. for (var index = 0; index < this._maxTextureChannels; index++) {
  8493. this._activeTexturesCache[index] = null;
  8494. }
  8495. };
  8496. Engine.prototype.getGlInfo = function () {
  8497. return {
  8498. vendor: this._glVendor,
  8499. renderer: this._glRenderer,
  8500. version: this._glVersion
  8501. };
  8502. };
  8503. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8504. if (useScreen === void 0) { useScreen = false; }
  8505. var viewport = camera.viewport;
  8506. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8507. };
  8508. Engine.prototype.getRenderWidth = function (useScreen) {
  8509. if (useScreen === void 0) { useScreen = false; }
  8510. if (!useScreen && this._currentRenderTarget) {
  8511. return this._currentRenderTarget._width;
  8512. }
  8513. return this._renderingCanvas.width;
  8514. };
  8515. Engine.prototype.getRenderHeight = function (useScreen) {
  8516. if (useScreen === void 0) { useScreen = false; }
  8517. if (!useScreen && this._currentRenderTarget) {
  8518. return this._currentRenderTarget._height;
  8519. }
  8520. return this._renderingCanvas.height;
  8521. };
  8522. Engine.prototype.getRenderingCanvas = function () {
  8523. return this._renderingCanvas;
  8524. };
  8525. Engine.prototype.getRenderingCanvasClientRect = function () {
  8526. return this._renderingCanvas.getBoundingClientRect();
  8527. };
  8528. Engine.prototype.setHardwareScalingLevel = function (level) {
  8529. this._hardwareScalingLevel = level;
  8530. this.resize();
  8531. };
  8532. Engine.prototype.getHardwareScalingLevel = function () {
  8533. return this._hardwareScalingLevel;
  8534. };
  8535. Engine.prototype.getLoadedTexturesCache = function () {
  8536. return this._loadedTexturesCache;
  8537. };
  8538. Engine.prototype.getCaps = function () {
  8539. return this._caps;
  8540. };
  8541. Object.defineProperty(Engine.prototype, "drawCalls", {
  8542. get: function () {
  8543. return this._drawCalls.current;
  8544. },
  8545. enumerable: true,
  8546. configurable: true
  8547. });
  8548. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8549. get: function () {
  8550. return this._drawCalls;
  8551. },
  8552. enumerable: true,
  8553. configurable: true
  8554. });
  8555. Engine.prototype.getDepthFunction = function () {
  8556. return this._depthCullingState.depthFunc;
  8557. };
  8558. Engine.prototype.setDepthFunction = function (depthFunc) {
  8559. this._depthCullingState.depthFunc = depthFunc;
  8560. };
  8561. Engine.prototype.setDepthFunctionToGreater = function () {
  8562. this._depthCullingState.depthFunc = this._gl.GREATER;
  8563. };
  8564. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8565. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8566. };
  8567. Engine.prototype.setDepthFunctionToLess = function () {
  8568. this._depthCullingState.depthFunc = this._gl.LESS;
  8569. };
  8570. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8571. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8572. };
  8573. Engine.prototype.getStencilBuffer = function () {
  8574. return this._stencilState.stencilTest;
  8575. };
  8576. Engine.prototype.setStencilBuffer = function (enable) {
  8577. this._stencilState.stencilTest = enable;
  8578. };
  8579. Engine.prototype.getStencilMask = function () {
  8580. return this._stencilState.stencilMask;
  8581. };
  8582. Engine.prototype.setStencilMask = function (mask) {
  8583. this._stencilState.stencilMask = mask;
  8584. };
  8585. Engine.prototype.getStencilFunction = function () {
  8586. return this._stencilState.stencilFunc;
  8587. };
  8588. Engine.prototype.getStencilFunctionReference = function () {
  8589. return this._stencilState.stencilFuncRef;
  8590. };
  8591. Engine.prototype.getStencilFunctionMask = function () {
  8592. return this._stencilState.stencilFuncMask;
  8593. };
  8594. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8595. this._stencilState.stencilFunc = stencilFunc;
  8596. };
  8597. Engine.prototype.setStencilFunctionReference = function (reference) {
  8598. this._stencilState.stencilFuncRef = reference;
  8599. };
  8600. Engine.prototype.setStencilFunctionMask = function (mask) {
  8601. this._stencilState.stencilFuncMask = mask;
  8602. };
  8603. Engine.prototype.getStencilOperationFail = function () {
  8604. return this._stencilState.stencilOpStencilFail;
  8605. };
  8606. Engine.prototype.getStencilOperationDepthFail = function () {
  8607. return this._stencilState.stencilOpDepthFail;
  8608. };
  8609. Engine.prototype.getStencilOperationPass = function () {
  8610. return this._stencilState.stencilOpStencilDepthPass;
  8611. };
  8612. Engine.prototype.setStencilOperationFail = function (operation) {
  8613. this._stencilState.stencilOpStencilFail = operation;
  8614. };
  8615. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8616. this._stencilState.stencilOpDepthFail = operation;
  8617. };
  8618. Engine.prototype.setStencilOperationPass = function (operation) {
  8619. this._stencilState.stencilOpStencilDepthPass = operation;
  8620. };
  8621. /**
  8622. * stop executing a render loop function and remove it from the execution array
  8623. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8624. */
  8625. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8626. if (!renderFunction) {
  8627. this._activeRenderLoops = [];
  8628. return;
  8629. }
  8630. var index = this._activeRenderLoops.indexOf(renderFunction);
  8631. if (index >= 0) {
  8632. this._activeRenderLoops.splice(index, 1);
  8633. }
  8634. };
  8635. Engine.prototype._renderLoop = function () {
  8636. var shouldRender = true;
  8637. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8638. shouldRender = false;
  8639. }
  8640. if (shouldRender) {
  8641. // Start new frame
  8642. this.beginFrame();
  8643. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8644. var renderFunction = this._activeRenderLoops[index];
  8645. renderFunction();
  8646. }
  8647. // Present
  8648. this.endFrame();
  8649. }
  8650. if (this._activeRenderLoops.length > 0) {
  8651. // Register new frame
  8652. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8653. }
  8654. else {
  8655. this._renderingQueueLaunched = false;
  8656. }
  8657. };
  8658. /**
  8659. * Register and execute a render loop. The engine can have more than one render function.
  8660. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8661. * @example
  8662. * engine.runRenderLoop(function () {
  8663. * scene.render()
  8664. * })
  8665. */
  8666. Engine.prototype.runRenderLoop = function (renderFunction) {
  8667. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8668. return;
  8669. }
  8670. this._activeRenderLoops.push(renderFunction);
  8671. if (!this._renderingQueueLaunched) {
  8672. this._renderingQueueLaunched = true;
  8673. this._bindedRenderFunction = this._renderLoop.bind(this);
  8674. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8675. }
  8676. };
  8677. /**
  8678. * Toggle full screen mode.
  8679. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8680. * @param {any} options - an options object to be sent to the requestFullscreen function
  8681. */
  8682. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8683. if (this.isFullscreen) {
  8684. BABYLON.Tools.ExitFullscreen();
  8685. }
  8686. else {
  8687. this._pointerLockRequested = requestPointerLock;
  8688. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8689. }
  8690. };
  8691. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8692. if (stencil === void 0) { stencil = false; }
  8693. this.applyStates();
  8694. var mode = 0;
  8695. if (backBuffer && color) {
  8696. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8697. mode |= this._gl.COLOR_BUFFER_BIT;
  8698. }
  8699. if (depth) {
  8700. this._gl.clearDepth(1.0);
  8701. mode |= this._gl.DEPTH_BUFFER_BIT;
  8702. }
  8703. if (stencil) {
  8704. this._gl.clearStencil(0);
  8705. mode |= this._gl.STENCIL_BUFFER_BIT;
  8706. }
  8707. this._gl.clear(mode);
  8708. };
  8709. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8710. var gl = this._gl;
  8711. // Save state
  8712. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8713. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8714. // Change state
  8715. gl.enable(gl.SCISSOR_TEST);
  8716. gl.scissor(x, y, width, height);
  8717. // Clear
  8718. this.clear(clearColor, true, true, true);
  8719. // Restore state
  8720. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8721. if (curScissor === true) {
  8722. gl.enable(gl.SCISSOR_TEST);
  8723. }
  8724. else {
  8725. gl.disable(gl.SCISSOR_TEST);
  8726. }
  8727. };
  8728. /**
  8729. * Set the WebGL's viewport
  8730. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8731. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8732. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8733. */
  8734. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8735. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8736. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8737. var x = viewport.x || 0;
  8738. var y = viewport.y || 0;
  8739. this._cachedViewport = viewport;
  8740. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8741. };
  8742. /**
  8743. * Directly set the WebGL Viewport
  8744. * The x, y, width & height are directly passed to the WebGL call
  8745. * @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.
  8746. */
  8747. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8748. var currentViewport = this._cachedViewport;
  8749. this._cachedViewport = null;
  8750. this._gl.viewport(x, y, width, height);
  8751. return currentViewport;
  8752. };
  8753. Engine.prototype.beginFrame = function () {
  8754. this._measureFps();
  8755. };
  8756. Engine.prototype.endFrame = function () {
  8757. //force a flush in case we are using a bad OS.
  8758. if (this._badOS) {
  8759. this.flushFramebuffer();
  8760. }
  8761. //submit frame to the vr device, if enabled
  8762. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8763. this._vrDisplayEnabled.submitFrame();
  8764. }
  8765. };
  8766. /**
  8767. * resize the view according to the canvas' size.
  8768. * @example
  8769. * window.addEventListener("resize", function () {
  8770. * engine.resize();
  8771. * });
  8772. */
  8773. Engine.prototype.resize = function () {
  8774. // We're not resizing the size of the canvas while in VR mode & presenting
  8775. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8776. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8777. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8778. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8779. }
  8780. };
  8781. /**
  8782. * force a specific size of the canvas
  8783. * @param {number} width - the new canvas' width
  8784. * @param {number} height - the new canvas' height
  8785. */
  8786. Engine.prototype.setSize = function (width, height) {
  8787. this._renderingCanvas.width = width;
  8788. this._renderingCanvas.height = height;
  8789. for (var index = 0; index < this.scenes.length; index++) {
  8790. var scene = this.scenes[index];
  8791. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8792. var cam = scene.cameras[camIndex];
  8793. cam._currentRenderId = 0;
  8794. }
  8795. }
  8796. };
  8797. //WebVR functions
  8798. Engine.prototype.initWebVR = function () {
  8799. if (!this.vrDisplaysPromise) {
  8800. this._getVRDisplays();
  8801. }
  8802. };
  8803. Engine.prototype.enableVR = function (vrDevice) {
  8804. this._vrDisplayEnabled = vrDevice;
  8805. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8806. };
  8807. Engine.prototype.disableVR = function () {
  8808. if (this._vrDisplayEnabled) {
  8809. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8810. }
  8811. };
  8812. Engine.prototype._getVRDisplays = function () {
  8813. var _this = this;
  8814. var getWebVRDevices = function (devices) {
  8815. var size = devices.length;
  8816. var i = 0;
  8817. _this._vrDisplays = devices.filter(function (device) {
  8818. return devices[i] instanceof VRDisplay;
  8819. });
  8820. return _this._vrDisplays;
  8821. };
  8822. //using a key due to typescript
  8823. if (navigator.getVRDisplays) {
  8824. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8825. }
  8826. };
  8827. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8828. this._currentRenderTarget = texture;
  8829. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8830. var gl = this._gl;
  8831. if (texture.isCube) {
  8832. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8833. }
  8834. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8835. this.wipeCaches();
  8836. };
  8837. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8838. if (this._currentFramebuffer !== framebuffer) {
  8839. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8840. this._currentFramebuffer = framebuffer;
  8841. }
  8842. };
  8843. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8844. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8845. this._currentRenderTarget = null;
  8846. // If MSAA, we need to bitblt back to main texture
  8847. var gl = this._gl;
  8848. if (texture._MSAAFramebuffer) {
  8849. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8850. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8851. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8852. }
  8853. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8854. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8855. gl.generateMipmap(gl.TEXTURE_2D);
  8856. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8857. }
  8858. if (onBeforeUnbind) {
  8859. if (texture._MSAAFramebuffer) {
  8860. // Bind the correct framebuffer
  8861. this.bindUnboundFramebuffer(texture._framebuffer);
  8862. }
  8863. onBeforeUnbind();
  8864. }
  8865. this.bindUnboundFramebuffer(null);
  8866. };
  8867. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8868. if (texture.generateMipMaps) {
  8869. var gl = this._gl;
  8870. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8871. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8872. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8873. }
  8874. };
  8875. Engine.prototype.flushFramebuffer = function () {
  8876. this._gl.flush();
  8877. };
  8878. Engine.prototype.restoreDefaultFramebuffer = function () {
  8879. this._currentRenderTarget = null;
  8880. this.bindUnboundFramebuffer(null);
  8881. this.setViewport(this._cachedViewport);
  8882. this.wipeCaches();
  8883. };
  8884. // VBOs
  8885. Engine.prototype._resetVertexBufferBinding = function () {
  8886. this.bindArrayBuffer(null);
  8887. this._cachedVertexBuffers = null;
  8888. };
  8889. Engine.prototype.createVertexBuffer = function (vertices) {
  8890. var vbo = this._gl.createBuffer();
  8891. this.bindArrayBuffer(vbo);
  8892. if (vertices instanceof Float32Array) {
  8893. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8894. }
  8895. else {
  8896. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8897. }
  8898. this._resetVertexBufferBinding();
  8899. vbo.references = 1;
  8900. return vbo;
  8901. };
  8902. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8903. var vbo = this._gl.createBuffer();
  8904. this.bindArrayBuffer(vbo);
  8905. if (vertices instanceof Float32Array) {
  8906. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8907. }
  8908. else {
  8909. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8910. }
  8911. this._resetVertexBufferBinding();
  8912. vbo.references = 1;
  8913. return vbo;
  8914. };
  8915. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8916. this.bindArrayBuffer(vertexBuffer);
  8917. if (offset === undefined) {
  8918. offset = 0;
  8919. }
  8920. if (count === undefined) {
  8921. if (vertices instanceof Float32Array) {
  8922. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8923. }
  8924. else {
  8925. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8926. }
  8927. }
  8928. else {
  8929. if (vertices instanceof Float32Array) {
  8930. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8931. }
  8932. else {
  8933. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8934. }
  8935. }
  8936. this._resetVertexBufferBinding();
  8937. };
  8938. Engine.prototype._resetIndexBufferBinding = function () {
  8939. this.bindIndexBuffer(null);
  8940. this._cachedIndexBuffer = null;
  8941. };
  8942. Engine.prototype.createIndexBuffer = function (indices) {
  8943. var vbo = this._gl.createBuffer();
  8944. this.bindIndexBuffer(vbo);
  8945. // Check for 32 bits indices
  8946. var arrayBuffer;
  8947. var need32Bits = false;
  8948. if (indices instanceof Uint16Array) {
  8949. arrayBuffer = indices;
  8950. }
  8951. else {
  8952. //check 32 bit support
  8953. if (this._caps.uintIndices) {
  8954. if (indices instanceof Uint32Array) {
  8955. arrayBuffer = indices;
  8956. need32Bits = true;
  8957. }
  8958. else {
  8959. //number[] or Int32Array, check if 32 bit is necessary
  8960. for (var index = 0; index < indices.length; index++) {
  8961. if (indices[index] > 65535) {
  8962. need32Bits = true;
  8963. break;
  8964. }
  8965. }
  8966. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8967. }
  8968. }
  8969. else {
  8970. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8971. arrayBuffer = new Uint16Array(indices);
  8972. }
  8973. }
  8974. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8975. this._resetIndexBufferBinding();
  8976. vbo.references = 1;
  8977. vbo.is32Bits = need32Bits;
  8978. return vbo;
  8979. };
  8980. Engine.prototype.bindArrayBuffer = function (buffer) {
  8981. if (!this._vaoRecordInProgress) {
  8982. this._unBindVertexArrayObject();
  8983. }
  8984. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8985. };
  8986. Engine.prototype.bindIndexBuffer = function (buffer) {
  8987. if (!this._vaoRecordInProgress) {
  8988. this._unBindVertexArrayObject();
  8989. }
  8990. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8991. };
  8992. Engine.prototype.bindBuffer = function (buffer, target) {
  8993. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8994. this._gl.bindBuffer(target, buffer);
  8995. this._currentBoundBuffer[target] = buffer;
  8996. }
  8997. };
  8998. Engine.prototype.updateArrayBuffer = function (data) {
  8999. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9000. };
  9001. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9002. var pointer = this._currentBufferPointers[indx];
  9003. var changed = false;
  9004. if (!pointer) {
  9005. changed = true;
  9006. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  9007. }
  9008. else {
  9009. if (pointer.buffer !== buffer) {
  9010. pointer.buffer = buffer;
  9011. changed = true;
  9012. }
  9013. if (pointer.size !== size) {
  9014. pointer.size = size;
  9015. changed = true;
  9016. }
  9017. if (pointer.type !== type) {
  9018. pointer.type = type;
  9019. changed = true;
  9020. }
  9021. if (pointer.normalized !== normalized) {
  9022. pointer.normalized = normalized;
  9023. changed = true;
  9024. }
  9025. if (pointer.stride !== stride) {
  9026. pointer.stride = stride;
  9027. changed = true;
  9028. }
  9029. if (pointer.offset !== offset) {
  9030. pointer.offset = offset;
  9031. changed = true;
  9032. }
  9033. }
  9034. if (changed || this._vaoRecordInProgress) {
  9035. this.bindArrayBuffer(buffer);
  9036. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9037. }
  9038. };
  9039. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9040. if (indexBuffer == null) {
  9041. return;
  9042. }
  9043. if (this._cachedIndexBuffer !== indexBuffer) {
  9044. this._cachedIndexBuffer = indexBuffer;
  9045. this.bindIndexBuffer(indexBuffer);
  9046. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9047. }
  9048. };
  9049. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9050. var attributes = effect.getAttributesNames();
  9051. if (!this._vaoRecordInProgress) {
  9052. this._unBindVertexArrayObject();
  9053. }
  9054. this.unbindAllAttributes();
  9055. for (var index = 0; index < attributes.length; index++) {
  9056. var order = effect.getAttributeLocation(index);
  9057. if (order >= 0) {
  9058. var vertexBuffer = vertexBuffers[attributes[index]];
  9059. if (!vertexBuffer) {
  9060. continue;
  9061. }
  9062. this._gl.enableVertexAttribArray(order);
  9063. if (!this._vaoRecordInProgress) {
  9064. this._vertexAttribArraysEnabled[order] = true;
  9065. }
  9066. var buffer = vertexBuffer.getBuffer();
  9067. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9068. if (vertexBuffer.getIsInstanced()) {
  9069. this._gl.vertexAttribDivisor(order, 1);
  9070. if (!this._vaoRecordInProgress) {
  9071. this._currentInstanceLocations.push(order);
  9072. this._currentInstanceBuffers.push(buffer);
  9073. }
  9074. }
  9075. }
  9076. }
  9077. };
  9078. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9079. var vao = this._gl.createVertexArray();
  9080. this._vaoRecordInProgress = true;
  9081. this._gl.bindVertexArray(vao);
  9082. this._mustWipeVertexAttributes = true;
  9083. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9084. this.bindIndexBuffer(indexBuffer);
  9085. this._vaoRecordInProgress = false;
  9086. this._gl.bindVertexArray(null);
  9087. return vao;
  9088. };
  9089. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9090. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9091. this._cachedVertexArrayObject = vertexArrayObject;
  9092. this._gl.bindVertexArray(vertexArrayObject);
  9093. this._cachedVertexBuffers = null;
  9094. this._cachedIndexBuffer = null;
  9095. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9096. this._mustWipeVertexAttributes = true;
  9097. }
  9098. };
  9099. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9100. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9101. this._cachedVertexBuffers = vertexBuffer;
  9102. this._cachedEffectForVertexBuffers = effect;
  9103. var attributesCount = effect.getAttributesCount();
  9104. this._unBindVertexArrayObject();
  9105. this.unbindAllAttributes();
  9106. var offset = 0;
  9107. for (var index = 0; index < attributesCount; index++) {
  9108. if (index < vertexDeclaration.length) {
  9109. var order = effect.getAttributeLocation(index);
  9110. if (order >= 0) {
  9111. this._gl.enableVertexAttribArray(order);
  9112. this._vertexAttribArraysEnabled[order] = true;
  9113. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9114. }
  9115. offset += vertexDeclaration[index] * 4;
  9116. }
  9117. }
  9118. }
  9119. this._bindIndexBufferWithCache(indexBuffer);
  9120. };
  9121. Engine.prototype._unBindVertexArrayObject = function () {
  9122. if (!this._cachedVertexArrayObject) {
  9123. return;
  9124. }
  9125. this._cachedVertexArrayObject = null;
  9126. this._gl.bindVertexArray(null);
  9127. };
  9128. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9129. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9130. this._cachedVertexBuffers = vertexBuffers;
  9131. this._cachedEffectForVertexBuffers = effect;
  9132. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9133. }
  9134. this._bindIndexBufferWithCache(indexBuffer);
  9135. };
  9136. Engine.prototype.unbindInstanceAttributes = function () {
  9137. var boundBuffer;
  9138. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9139. var instancesBuffer = this._currentInstanceBuffers[i];
  9140. if (boundBuffer != instancesBuffer) {
  9141. boundBuffer = instancesBuffer;
  9142. this.bindArrayBuffer(instancesBuffer);
  9143. }
  9144. var offsetLocation = this._currentInstanceLocations[i];
  9145. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9146. }
  9147. this._currentInstanceBuffers.length = 0;
  9148. this._currentInstanceLocations.length = 0;
  9149. };
  9150. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9151. this._gl.deleteVertexArray(vao);
  9152. };
  9153. Engine.prototype._releaseBuffer = function (buffer) {
  9154. buffer.references--;
  9155. if (buffer.references === 0) {
  9156. this._gl.deleteBuffer(buffer);
  9157. return true;
  9158. }
  9159. return false;
  9160. };
  9161. Engine.prototype.createInstancesBuffer = function (capacity) {
  9162. var buffer = this._gl.createBuffer();
  9163. buffer.capacity = capacity;
  9164. this.bindArrayBuffer(buffer);
  9165. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9166. return buffer;
  9167. };
  9168. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9169. this._gl.deleteBuffer(buffer);
  9170. };
  9171. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9172. this.bindArrayBuffer(instancesBuffer);
  9173. if (data) {
  9174. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9175. }
  9176. if (offsetLocations[0].index !== undefined) {
  9177. var stride = 0;
  9178. for (var i = 0; i < offsetLocations.length; i++) {
  9179. var ai = offsetLocations[i];
  9180. stride += ai.attributeSize * 4;
  9181. }
  9182. for (var i = 0; i < offsetLocations.length; i++) {
  9183. var ai = offsetLocations[i];
  9184. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9185. this._gl.enableVertexAttribArray(ai.index);
  9186. this._vertexAttribArraysEnabled[ai.index] = true;
  9187. }
  9188. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9189. this._gl.vertexAttribDivisor(ai.index, 1);
  9190. this._currentInstanceLocations.push(ai.index);
  9191. this._currentInstanceBuffers.push(instancesBuffer);
  9192. }
  9193. }
  9194. else {
  9195. for (var index = 0; index < 4; index++) {
  9196. var offsetLocation = offsetLocations[index];
  9197. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9198. this._gl.enableVertexAttribArray(offsetLocation);
  9199. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9200. }
  9201. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9202. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9203. this._currentInstanceLocations.push(offsetLocation);
  9204. this._currentInstanceBuffers.push(instancesBuffer);
  9205. }
  9206. }
  9207. };
  9208. Engine.prototype.applyStates = function () {
  9209. this._depthCullingState.apply(this._gl);
  9210. this._stencilState.apply(this._gl);
  9211. this._alphaState.apply(this._gl);
  9212. };
  9213. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9214. // Apply states
  9215. this.applyStates();
  9216. this._drawCalls.addCount(1, false);
  9217. // Render
  9218. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9219. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9220. if (instancesCount) {
  9221. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9222. return;
  9223. }
  9224. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9225. };
  9226. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9227. // Apply states
  9228. this.applyStates();
  9229. this._drawCalls.addCount(1, false);
  9230. if (instancesCount) {
  9231. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9232. return;
  9233. }
  9234. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9235. };
  9236. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9237. // Apply states
  9238. this.applyStates();
  9239. this._drawCalls.addCount(1, false);
  9240. if (instancesCount) {
  9241. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9242. return;
  9243. }
  9244. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9245. };
  9246. // Shaders
  9247. Engine.prototype._releaseEffect = function (effect) {
  9248. if (this._compiledEffects[effect._key]) {
  9249. delete this._compiledEffects[effect._key];
  9250. if (effect.getProgram()) {
  9251. this._gl.deleteProgram(effect.getProgram());
  9252. }
  9253. }
  9254. };
  9255. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9256. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9257. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9258. var name = vertex + "+" + fragment + "@" + defines;
  9259. if (this._compiledEffects[name]) {
  9260. return this._compiledEffects[name];
  9261. }
  9262. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9263. effect._key = name;
  9264. this._compiledEffects[name] = effect;
  9265. return effect;
  9266. };
  9267. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9268. if (uniformsNames === void 0) { uniformsNames = []; }
  9269. if (samplers === void 0) { samplers = []; }
  9270. if (defines === void 0) { defines = ""; }
  9271. return this.createEffect({
  9272. vertex: "particles",
  9273. fragmentElement: fragmentName
  9274. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9275. };
  9276. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9277. context = context || this._gl;
  9278. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9279. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9280. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9281. var shaderProgram = context.createProgram();
  9282. context.attachShader(shaderProgram, vertexShader);
  9283. context.attachShader(shaderProgram, fragmentShader);
  9284. context.linkProgram(shaderProgram);
  9285. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9286. if (!linked) {
  9287. var error = context.getProgramInfoLog(shaderProgram);
  9288. if (error) {
  9289. throw new Error(error);
  9290. }
  9291. }
  9292. context.deleteShader(vertexShader);
  9293. context.deleteShader(fragmentShader);
  9294. return shaderProgram;
  9295. };
  9296. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9297. var results = [];
  9298. for (var index = 0; index < uniformsNames.length; index++) {
  9299. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9300. }
  9301. return results;
  9302. };
  9303. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9304. var results = [];
  9305. for (var index = 0; index < attributesNames.length; index++) {
  9306. try {
  9307. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9308. }
  9309. catch (e) {
  9310. results.push(-1);
  9311. }
  9312. }
  9313. return results;
  9314. };
  9315. Engine.prototype.enableEffect = function (effect) {
  9316. // Use program
  9317. this.setProgram(effect.getProgram());
  9318. this._currentEffect = effect;
  9319. if (effect.onBind) {
  9320. effect.onBind(effect);
  9321. }
  9322. };
  9323. Engine.prototype.setIntArray = function (uniform, array) {
  9324. if (!uniform)
  9325. return;
  9326. this._gl.uniform1iv(uniform, array);
  9327. };
  9328. Engine.prototype.setIntArray2 = function (uniform, array) {
  9329. if (!uniform || array.length % 2 !== 0)
  9330. return;
  9331. this._gl.uniform2iv(uniform, array);
  9332. };
  9333. Engine.prototype.setIntArray3 = function (uniform, array) {
  9334. if (!uniform || array.length % 3 !== 0)
  9335. return;
  9336. this._gl.uniform3iv(uniform, array);
  9337. };
  9338. Engine.prototype.setIntArray4 = function (uniform, array) {
  9339. if (!uniform || array.length % 4 !== 0)
  9340. return;
  9341. this._gl.uniform4iv(uniform, array);
  9342. };
  9343. Engine.prototype.setFloatArray = function (uniform, array) {
  9344. if (!uniform)
  9345. return;
  9346. this._gl.uniform1fv(uniform, array);
  9347. };
  9348. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9349. if (!uniform || array.length % 2 !== 0)
  9350. return;
  9351. this._gl.uniform2fv(uniform, array);
  9352. };
  9353. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9354. if (!uniform || array.length % 3 !== 0)
  9355. return;
  9356. this._gl.uniform3fv(uniform, array);
  9357. };
  9358. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9359. if (!uniform || array.length % 4 !== 0)
  9360. return;
  9361. this._gl.uniform4fv(uniform, array);
  9362. };
  9363. Engine.prototype.setArray = function (uniform, array) {
  9364. if (!uniform)
  9365. return;
  9366. this._gl.uniform1fv(uniform, array);
  9367. };
  9368. Engine.prototype.setArray2 = function (uniform, array) {
  9369. if (!uniform || array.length % 2 !== 0)
  9370. return;
  9371. this._gl.uniform2fv(uniform, array);
  9372. };
  9373. Engine.prototype.setArray3 = function (uniform, array) {
  9374. if (!uniform || array.length % 3 !== 0)
  9375. return;
  9376. this._gl.uniform3fv(uniform, array);
  9377. };
  9378. Engine.prototype.setArray4 = function (uniform, array) {
  9379. if (!uniform || array.length % 4 !== 0)
  9380. return;
  9381. this._gl.uniform4fv(uniform, array);
  9382. };
  9383. Engine.prototype.setMatrices = function (uniform, matrices) {
  9384. if (!uniform)
  9385. return;
  9386. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9387. };
  9388. Engine.prototype.setMatrix = function (uniform, matrix) {
  9389. if (!uniform)
  9390. return;
  9391. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9392. };
  9393. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9394. if (!uniform)
  9395. return;
  9396. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9397. };
  9398. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9399. if (!uniform)
  9400. return;
  9401. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9402. };
  9403. Engine.prototype.setFloat = function (uniform, value) {
  9404. if (!uniform)
  9405. return;
  9406. this._gl.uniform1f(uniform, value);
  9407. };
  9408. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9409. if (!uniform)
  9410. return;
  9411. this._gl.uniform2f(uniform, x, y);
  9412. };
  9413. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9414. if (!uniform)
  9415. return;
  9416. this._gl.uniform3f(uniform, x, y, z);
  9417. };
  9418. Engine.prototype.setBool = function (uniform, bool) {
  9419. if (!uniform)
  9420. return;
  9421. this._gl.uniform1i(uniform, bool);
  9422. };
  9423. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9424. if (!uniform)
  9425. return;
  9426. this._gl.uniform4f(uniform, x, y, z, w);
  9427. };
  9428. Engine.prototype.setColor3 = function (uniform, color3) {
  9429. if (!uniform)
  9430. return;
  9431. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9432. };
  9433. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9434. if (!uniform)
  9435. return;
  9436. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9437. };
  9438. // States
  9439. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9440. if (zOffset === void 0) { zOffset = 0; }
  9441. if (reverseSide === void 0) { reverseSide = false; }
  9442. // Culling
  9443. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9444. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9445. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9446. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9447. if (culling) {
  9448. this._depthCullingState.cullFace = cullFace;
  9449. this._depthCullingState.cull = true;
  9450. }
  9451. else {
  9452. this._depthCullingState.cull = false;
  9453. }
  9454. }
  9455. // Z offset
  9456. this._depthCullingState.zOffset = zOffset;
  9457. };
  9458. Engine.prototype.setDepthBuffer = function (enable) {
  9459. this._depthCullingState.depthTest = enable;
  9460. };
  9461. Engine.prototype.getDepthWrite = function () {
  9462. return this._depthCullingState.depthMask;
  9463. };
  9464. Engine.prototype.setDepthWrite = function (enable) {
  9465. this._depthCullingState.depthMask = enable;
  9466. };
  9467. Engine.prototype.setColorWrite = function (enable) {
  9468. this._gl.colorMask(enable, enable, enable, enable);
  9469. };
  9470. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9471. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9472. if (this._alphaMode === mode) {
  9473. return;
  9474. }
  9475. switch (mode) {
  9476. case Engine.ALPHA_DISABLE:
  9477. this._alphaState.alphaBlend = false;
  9478. break;
  9479. case Engine.ALPHA_PREMULTIPLIED:
  9480. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9481. this._alphaState.alphaBlend = true;
  9482. break;
  9483. case Engine.ALPHA_COMBINE:
  9484. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9485. this._alphaState.alphaBlend = true;
  9486. break;
  9487. case Engine.ALPHA_ONEONE:
  9488. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9489. this._alphaState.alphaBlend = true;
  9490. break;
  9491. case Engine.ALPHA_ADD:
  9492. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9493. this._alphaState.alphaBlend = true;
  9494. break;
  9495. case Engine.ALPHA_SUBTRACT:
  9496. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9497. this._alphaState.alphaBlend = true;
  9498. break;
  9499. case Engine.ALPHA_MULTIPLY:
  9500. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9501. this._alphaState.alphaBlend = true;
  9502. break;
  9503. case Engine.ALPHA_MAXIMIZED:
  9504. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9505. this._alphaState.alphaBlend = true;
  9506. break;
  9507. }
  9508. if (!noDepthWriteChange) {
  9509. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9510. }
  9511. this._alphaMode = mode;
  9512. };
  9513. Engine.prototype.getAlphaMode = function () {
  9514. return this._alphaMode;
  9515. };
  9516. Engine.prototype.setAlphaTesting = function (enable) {
  9517. this._alphaTest = enable;
  9518. };
  9519. Engine.prototype.getAlphaTesting = function () {
  9520. return this._alphaTest;
  9521. };
  9522. // Textures
  9523. Engine.prototype.wipeCaches = function () {
  9524. if (this.preventCacheWipeBetweenFrames) {
  9525. return;
  9526. }
  9527. this.resetTextureCache();
  9528. this._currentEffect = null;
  9529. this._stencilState.reset();
  9530. this._depthCullingState.reset();
  9531. this.setDepthFunctionToLessOrEqual();
  9532. this._alphaState.reset();
  9533. this._cachedVertexBuffers = null;
  9534. this._cachedIndexBuffer = null;
  9535. this._cachedEffectForVertexBuffers = null;
  9536. this._unBindVertexArrayObject();
  9537. this.bindIndexBuffer(null);
  9538. this.bindArrayBuffer(null);
  9539. };
  9540. /**
  9541. * Set the compressed texture format to use, based on the formats you have, and the formats
  9542. * supported by the hardware / browser.
  9543. *
  9544. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9545. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9546. * to API arguments needed to compressed textures. This puts the burden on the container
  9547. * generator to house the arcane code for determining these for current & future formats.
  9548. *
  9549. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9550. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9551. *
  9552. * Note: The result of this call is not taken into account when a texture is base64.
  9553. *
  9554. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9555. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9556. *
  9557. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9558. * @returns The extension selected.
  9559. */
  9560. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9561. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9562. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9563. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9564. return this._textureFormatInUse = this._texturesSupported[i];
  9565. }
  9566. }
  9567. }
  9568. // actively set format to nothing, to allow this to be called more than once
  9569. // and possibly fail the 2nd time
  9570. return this._textureFormatInUse = null;
  9571. };
  9572. /**
  9573. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9574. * @param {string} urlArg- This contains one of the following:
  9575. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9576. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9577. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9578. *
  9579. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9580. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9581. * @param {Scene} scene- Needed for loading to the correct scene.
  9582. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9583. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9584. * @param {callback} onError- Optional callback to be called upon failure.
  9585. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9586. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9587. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9588. *
  9589. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9590. */
  9591. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9592. var _this = this;
  9593. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9594. if (onLoad === void 0) { onLoad = null; }
  9595. if (onError === void 0) { onError = null; }
  9596. if (buffer === void 0) { buffer = null; }
  9597. var texture = fallBack ? fallBack : this._gl.createTexture();
  9598. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9599. var fromData = url.substr(0, 5) === "data:";
  9600. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9601. // establish the file extension, if possible
  9602. var lastDot = url.lastIndexOf('.');
  9603. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9604. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9605. if (isDDS) {
  9606. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9607. }
  9608. var isTGA = (extension === ".tga");
  9609. // determine if a ktx file should be substituted
  9610. var isKTX = false;
  9611. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9612. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9613. isKTX = true;
  9614. }
  9615. scene._addPendingData(texture);
  9616. texture.url = url;
  9617. texture.noMipmap = noMipmap;
  9618. texture.references = 1;
  9619. texture.samplingMode = samplingMode;
  9620. texture.onLoadedCallbacks = [];
  9621. if (onLoad) {
  9622. texture.onLoadedCallbacks.push(onLoad);
  9623. }
  9624. if (!fallBack)
  9625. this._loadedTexturesCache.push(texture);
  9626. var onerror = function () {
  9627. scene._removePendingData(texture);
  9628. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9629. if (isKTX) {
  9630. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9631. }
  9632. else if (onError) {
  9633. onError();
  9634. }
  9635. };
  9636. var callback;
  9637. // processing for non-image formats
  9638. if (isKTX || isTGA || isDDS) {
  9639. if (isKTX) {
  9640. callback = function (data) {
  9641. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9642. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9643. ktx.uploadLevels(_this._gl, !noMipmap);
  9644. }, samplingMode);
  9645. };
  9646. }
  9647. else if (isTGA) {
  9648. callback = function (arrayBuffer) {
  9649. var data = new Uint8Array(arrayBuffer);
  9650. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9651. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9652. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9653. }, samplingMode);
  9654. };
  9655. }
  9656. else if (isDDS) {
  9657. callback = function (data) {
  9658. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9659. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9660. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9661. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9662. }, samplingMode);
  9663. };
  9664. }
  9665. if (!buffer) {
  9666. BABYLON.Tools.LoadFile(url, function (data) {
  9667. callback(data);
  9668. }, null, scene.database, true, onerror);
  9669. }
  9670. else {
  9671. callback(buffer);
  9672. }
  9673. // image format processing
  9674. }
  9675. else {
  9676. var onload = function (img) {
  9677. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9678. var isPot = (img.width === potWidth && img.height === potHeight);
  9679. if (!isPot) {
  9680. _this._prepareWorkingCanvas();
  9681. _this._workingCanvas.width = potWidth;
  9682. _this._workingCanvas.height = potHeight;
  9683. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9684. _this._workingContext.imageSmoothingEnabled = false;
  9685. _this._workingContext.mozImageSmoothingEnabled = false;
  9686. _this._workingContext.oImageSmoothingEnabled = false;
  9687. _this._workingContext.webkitImageSmoothingEnabled = false;
  9688. _this._workingContext.msImageSmoothingEnabled = false;
  9689. }
  9690. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9691. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9692. _this._workingContext.imageSmoothingEnabled = true;
  9693. _this._workingContext.mozImageSmoothingEnabled = true;
  9694. _this._workingContext.oImageSmoothingEnabled = true;
  9695. _this._workingContext.webkitImageSmoothingEnabled = true;
  9696. _this._workingContext.msImageSmoothingEnabled = true;
  9697. }
  9698. }
  9699. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9700. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9701. }, samplingMode);
  9702. };
  9703. if (!fromData || isBase64)
  9704. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9705. else if (buffer instanceof Array || typeof buffer === "string")
  9706. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9707. else
  9708. onload(buffer);
  9709. }
  9710. return texture;
  9711. };
  9712. Engine.prototype._getInternalFormat = function (format) {
  9713. var internalFormat = this._gl.RGBA;
  9714. switch (format) {
  9715. case Engine.TEXTUREFORMAT_ALPHA:
  9716. internalFormat = this._gl.ALPHA;
  9717. break;
  9718. case Engine.TEXTUREFORMAT_LUMINANCE:
  9719. internalFormat = this._gl.LUMINANCE;
  9720. break;
  9721. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9722. internalFormat = this._gl.LUMINANCE_ALPHA;
  9723. break;
  9724. case Engine.TEXTUREFORMAT_RGB:
  9725. internalFormat = this._gl.RGB;
  9726. break;
  9727. case Engine.TEXTUREFORMAT_RGBA:
  9728. internalFormat = this._gl.RGBA;
  9729. break;
  9730. }
  9731. return internalFormat;
  9732. };
  9733. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9734. if (compression === void 0) { compression = null; }
  9735. var internalFormat = this._getInternalFormat(format);
  9736. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9737. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9738. if (texture._width % 4 !== 0) {
  9739. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9740. }
  9741. if (compression) {
  9742. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9743. }
  9744. else {
  9745. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9746. }
  9747. if (texture.generateMipMaps) {
  9748. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9749. }
  9750. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9751. this.resetTextureCache();
  9752. texture.isReady = true;
  9753. };
  9754. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9755. if (compression === void 0) { compression = null; }
  9756. var texture = this._gl.createTexture();
  9757. texture._baseWidth = width;
  9758. texture._baseHeight = height;
  9759. texture._width = width;
  9760. texture._height = height;
  9761. texture.references = 1;
  9762. this.updateRawTexture(texture, data, format, invertY, compression);
  9763. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9764. // Filters
  9765. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9766. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9767. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9768. if (generateMipMaps) {
  9769. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9770. }
  9771. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9772. texture.samplingMode = samplingMode;
  9773. this._loadedTexturesCache.push(texture);
  9774. return texture;
  9775. };
  9776. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9777. var texture = this._gl.createTexture();
  9778. texture._baseWidth = width;
  9779. texture._baseHeight = height;
  9780. if (generateMipMaps) {
  9781. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9782. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9783. }
  9784. this.resetTextureCache();
  9785. texture._width = width;
  9786. texture._height = height;
  9787. texture.isReady = false;
  9788. texture.generateMipMaps = generateMipMaps;
  9789. texture.references = 1;
  9790. texture.samplingMode = samplingMode;
  9791. this.updateTextureSamplingMode(samplingMode, texture);
  9792. this._loadedTexturesCache.push(texture);
  9793. return texture;
  9794. };
  9795. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9796. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9797. if (texture.isCube) {
  9798. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9799. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9800. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9801. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9802. }
  9803. else {
  9804. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9805. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9806. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9807. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9808. }
  9809. texture.samplingMode = samplingMode;
  9810. };
  9811. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9812. if (premulAlpha === void 0) { premulAlpha = false; }
  9813. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9814. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9815. if (premulAlpha) {
  9816. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9817. }
  9818. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9819. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9820. if (texture.generateMipMaps) {
  9821. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9822. }
  9823. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9824. if (premulAlpha) {
  9825. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9826. }
  9827. this.resetTextureCache();
  9828. texture.isReady = true;
  9829. };
  9830. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9831. if (texture._isDisabled) {
  9832. return;
  9833. }
  9834. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9835. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9836. try {
  9837. // Testing video texture support
  9838. if (this._videoTextureSupported === undefined) {
  9839. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9840. if (this._gl.getError() !== 0) {
  9841. this._videoTextureSupported = false;
  9842. }
  9843. else {
  9844. this._videoTextureSupported = true;
  9845. }
  9846. }
  9847. // Copy video through the current working canvas if video texture is not supported
  9848. if (!this._videoTextureSupported) {
  9849. if (!texture._workingCanvas) {
  9850. texture._workingCanvas = document.createElement("canvas");
  9851. texture._workingContext = texture._workingCanvas.getContext("2d");
  9852. texture._workingCanvas.width = texture._width;
  9853. texture._workingCanvas.height = texture._height;
  9854. }
  9855. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9856. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9857. }
  9858. else {
  9859. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9860. }
  9861. if (texture.generateMipMaps) {
  9862. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9863. }
  9864. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9865. this.resetTextureCache();
  9866. texture.isReady = true;
  9867. }
  9868. catch (ex) {
  9869. // Something unexpected
  9870. // Let's disable the texture
  9871. texture._isDisabled = true;
  9872. }
  9873. };
  9874. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9875. // old version had a "generateMipMaps" arg instead of options.
  9876. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9877. // in the same way, generateDepthBuffer is defaulted to true
  9878. var generateMipMaps = false;
  9879. var generateDepthBuffer = true;
  9880. var generateStencilBuffer = false;
  9881. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9882. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9883. if (options !== undefined) {
  9884. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9885. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9886. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9887. type = options.type === undefined ? type : options.type;
  9888. if (options.samplingMode !== undefined) {
  9889. samplingMode = options.samplingMode;
  9890. }
  9891. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9892. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9893. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9894. }
  9895. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9896. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9897. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9898. }
  9899. }
  9900. var gl = this._gl;
  9901. var texture = gl.createTexture();
  9902. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9903. var width = size.width || size;
  9904. var height = size.height || size;
  9905. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9906. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9907. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9908. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9909. }
  9910. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9911. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9912. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9913. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9914. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9915. // Create the framebuffer
  9916. var framebuffer = gl.createFramebuffer();
  9917. this.bindUnboundFramebuffer(framebuffer);
  9918. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9919. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9920. if (generateMipMaps) {
  9921. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9922. }
  9923. // Unbind
  9924. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9925. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9926. this.bindUnboundFramebuffer(null);
  9927. texture._framebuffer = framebuffer;
  9928. texture._baseWidth = width;
  9929. texture._baseHeight = height;
  9930. texture._width = width;
  9931. texture._height = height;
  9932. texture.isReady = true;
  9933. texture.samples = 1;
  9934. texture.generateMipMaps = generateMipMaps;
  9935. texture.references = 1;
  9936. texture.samplingMode = samplingMode;
  9937. texture.type = type;
  9938. texture._generateDepthBuffer = generateDepthBuffer;
  9939. texture._generateStencilBuffer = generateStencilBuffer;
  9940. this.resetTextureCache();
  9941. this._loadedTexturesCache.push(texture);
  9942. return texture;
  9943. };
  9944. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9945. if (samples === void 0) { samples = 1; }
  9946. var depthStencilBuffer = null;
  9947. var gl = this._gl;
  9948. // Create the depth/stencil buffer
  9949. if (generateStencilBuffer) {
  9950. depthStencilBuffer = gl.createRenderbuffer();
  9951. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9952. if (samples > 1) {
  9953. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9954. }
  9955. else {
  9956. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9957. }
  9958. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9959. }
  9960. else if (generateDepthBuffer) {
  9961. depthStencilBuffer = gl.createRenderbuffer();
  9962. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9963. if (samples > 1) {
  9964. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9965. }
  9966. else {
  9967. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9968. }
  9969. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9970. }
  9971. return depthStencilBuffer;
  9972. };
  9973. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9974. if (this.webGLVersion < 2) {
  9975. return 1;
  9976. }
  9977. if (texture.samples === samples) {
  9978. return samples;
  9979. }
  9980. var gl = this._gl;
  9981. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9982. // Dispose previous render buffers
  9983. if (texture._depthStencilBuffer) {
  9984. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9985. }
  9986. if (texture._MSAAFramebuffer) {
  9987. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9988. }
  9989. if (texture._MSAARenderBuffer) {
  9990. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9991. }
  9992. if (samples > 1) {
  9993. texture._MSAAFramebuffer = gl.createFramebuffer();
  9994. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9995. var colorRenderbuffer = gl.createRenderbuffer();
  9996. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9997. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9998. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9999. texture._MSAARenderBuffer = colorRenderbuffer;
  10000. }
  10001. else {
  10002. this.bindUnboundFramebuffer(texture._framebuffer);
  10003. }
  10004. texture.samples = samples;
  10005. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  10006. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10007. this.bindUnboundFramebuffer(null);
  10008. return samples;
  10009. };
  10010. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10011. var gl = this._gl;
  10012. var texture = gl.createTexture();
  10013. var generateMipMaps = true;
  10014. var generateDepthBuffer = true;
  10015. var generateStencilBuffer = false;
  10016. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10017. if (options !== undefined) {
  10018. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  10019. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10020. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10021. if (options.samplingMode !== undefined) {
  10022. samplingMode = options.samplingMode;
  10023. }
  10024. }
  10025. texture.isCube = true;
  10026. texture.references = 1;
  10027. texture.generateMipMaps = generateMipMaps;
  10028. texture.references = 1;
  10029. texture.samples = 1;
  10030. texture.samplingMode = samplingMode;
  10031. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10032. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10033. for (var face = 0; face < 6; face++) {
  10034. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10035. }
  10036. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10037. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10038. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10039. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10040. // Create the framebuffer
  10041. var framebuffer = gl.createFramebuffer();
  10042. this.bindUnboundFramebuffer(framebuffer);
  10043. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10044. // Mipmaps
  10045. if (texture.generateMipMaps) {
  10046. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10047. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10048. }
  10049. // Unbind
  10050. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10051. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10052. this.bindUnboundFramebuffer(null);
  10053. texture._framebuffer = framebuffer;
  10054. texture._width = size;
  10055. texture._height = size;
  10056. texture.isReady = true;
  10057. this.resetTextureCache();
  10058. this._loadedTexturesCache.push(texture);
  10059. return texture;
  10060. };
  10061. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  10062. var _this = this;
  10063. if (onLoad === void 0) { onLoad = null; }
  10064. if (onError === void 0) { onError = null; }
  10065. var gl = this._gl;
  10066. var texture = gl.createTexture();
  10067. texture.isCube = true;
  10068. texture.url = rootUrl;
  10069. texture.references = 1;
  10070. texture.onLoadedCallbacks = [];
  10071. var isKTX = false;
  10072. var lastDot = rootUrl.lastIndexOf('.');
  10073. var extension = rootUrl.substring(lastDot).toLowerCase();
  10074. if (this._textureFormatInUse) {
  10075. extension = this._textureFormatInUse;
  10076. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10077. isKTX = true;
  10078. }
  10079. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10080. if (isDDS) {
  10081. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  10082. }
  10083. if (isKTX) {
  10084. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10085. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10086. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10087. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10088. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10089. ktx.uploadLevels(_this._gl, !noMipmap);
  10090. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10091. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10092. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10093. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10094. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10095. _this.resetTextureCache();
  10096. texture._width = ktx.pixelWidth;
  10097. texture._height = ktx.pixelHeight;
  10098. texture.isReady = true;
  10099. }, null, null, true, onError);
  10100. }
  10101. else if (isDDS) {
  10102. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10103. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10104. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10105. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10106. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10107. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  10108. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10109. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10110. }
  10111. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10112. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10113. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10114. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10115. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10116. _this.resetTextureCache();
  10117. texture._width = info.width;
  10118. texture._height = info.height;
  10119. texture.isReady = true;
  10120. }, null, null, true, onError);
  10121. }
  10122. else {
  10123. cascadeLoad(rootUrl, scene, function (imgs) {
  10124. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  10125. var height = width;
  10126. _this._prepareWorkingCanvas();
  10127. _this._workingCanvas.width = width;
  10128. _this._workingCanvas.height = height;
  10129. var faces = [
  10130. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10131. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10132. ];
  10133. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10134. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10135. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10136. for (var index = 0; index < faces.length; index++) {
  10137. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10138. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10139. }
  10140. if (!noMipmap) {
  10141. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10142. }
  10143. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10144. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10145. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10146. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10147. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10148. _this.resetTextureCache();
  10149. texture._width = width;
  10150. texture._height = height;
  10151. texture.isReady = true;
  10152. texture.onLoadedCallbacks.forEach(function (callback) {
  10153. callback();
  10154. });
  10155. if (onLoad) {
  10156. onLoad();
  10157. }
  10158. }, files, onError);
  10159. }
  10160. this._loadedTexturesCache.push(texture);
  10161. return texture;
  10162. };
  10163. Engine.prototype.updateTextureSize = function (texture, width, height) {
  10164. texture._width = width;
  10165. texture._height = height;
  10166. texture._size = width * height;
  10167. texture._baseWidth = width;
  10168. texture._baseHeight = height;
  10169. };
  10170. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  10171. var _this = this;
  10172. if (onLoad === void 0) { onLoad = null; }
  10173. if (onError === void 0) { onError = null; }
  10174. var gl = this._gl;
  10175. var texture = gl.createTexture();
  10176. scene._addPendingData(texture);
  10177. texture.isCube = true;
  10178. texture.references = 1;
  10179. texture.url = url;
  10180. var textureType = gl.UNSIGNED_BYTE;
  10181. if (type === Engine.TEXTURETYPE_FLOAT) {
  10182. textureType = gl.FLOAT;
  10183. }
  10184. var internalFormat = this._getInternalFormat(format);
  10185. var needConversion = false;
  10186. if (internalFormat === gl.RGB) {
  10187. internalFormat = gl.RGBA;
  10188. needConversion = true;
  10189. }
  10190. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10191. var width = size;
  10192. var height = width;
  10193. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10194. texture._width = width;
  10195. texture._height = height;
  10196. var onerror = function () {
  10197. scene._removePendingData(texture);
  10198. if (onError) {
  10199. onError();
  10200. }
  10201. };
  10202. var internalCallback = function (data) {
  10203. var rgbeDataArrays = callback(data);
  10204. var facesIndex = [
  10205. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10206. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10207. ];
  10208. width = texture._width;
  10209. height = texture._height;
  10210. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10211. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10212. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10213. if (mipmmapGenerator) {
  10214. var arrayTemp = [];
  10215. // Data are known to be in +X +Y +Z -X -Y -Z
  10216. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  10217. arrayTemp.push(rgbeDataArrays[0]); // +X
  10218. arrayTemp.push(rgbeDataArrays[3]); // -X
  10219. arrayTemp.push(rgbeDataArrays[1]); // +Y
  10220. arrayTemp.push(rgbeDataArrays[4]); // -Y
  10221. arrayTemp.push(rgbeDataArrays[2]); // +Z
  10222. arrayTemp.push(rgbeDataArrays[5]); // -Z
  10223. var mipData = mipmmapGenerator(arrayTemp);
  10224. // mipData is order in +X -X +Y -Y +Z -Z
  10225. var mipFaces = [0, 2, 4, 1, 3, 5];
  10226. for (var level = 0; level < mipData.length; level++) {
  10227. var mipSize = width >> level;
  10228. for (var mipIndex in mipFaces) {
  10229. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  10230. if (needConversion) {
  10231. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10232. }
  10233. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10234. }
  10235. }
  10236. }
  10237. else {
  10238. // Data are known to be in +X +Y +Z -X -Y -Z
  10239. for (var index = 0; index < facesIndex.length; index++) {
  10240. var faceData = rgbeDataArrays[index];
  10241. if (needConversion) {
  10242. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  10243. }
  10244. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  10245. }
  10246. if (!noMipmap && isPot) {
  10247. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10248. }
  10249. else {
  10250. noMipmap = true;
  10251. }
  10252. }
  10253. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  10254. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10255. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10256. }
  10257. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  10258. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10259. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10260. }
  10261. else {
  10262. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10263. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10264. }
  10265. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10266. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10267. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10268. texture.isReady = true;
  10269. _this.resetTextureCache();
  10270. scene._removePendingData(texture);
  10271. if (onLoad) {
  10272. onLoad();
  10273. }
  10274. };
  10275. BABYLON.Tools.LoadFile(url, function (data) {
  10276. internalCallback(data);
  10277. }, onerror, scene.database, true);
  10278. return texture;
  10279. };
  10280. ;
  10281. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10282. // Create new RGBA data container.
  10283. var rgbaData;
  10284. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10285. rgbaData = new Float32Array(width * height * 4);
  10286. }
  10287. else {
  10288. rgbaData = new Uint32Array(width * height * 4);
  10289. }
  10290. // Convert each pixel.
  10291. for (var x = 0; x < width; x++) {
  10292. for (var y = 0; y < height; y++) {
  10293. var index = (y * width + x) * 3;
  10294. var newIndex = (y * width + x) * 4;
  10295. // Map Old Value to new value.
  10296. rgbaData[newIndex + 0] = rgbData[index + 0];
  10297. rgbaData[newIndex + 1] = rgbData[index + 1];
  10298. rgbaData[newIndex + 2] = rgbData[index + 2];
  10299. // Add fully opaque alpha channel.
  10300. rgbaData[newIndex + 3] = 1;
  10301. }
  10302. }
  10303. return rgbaData;
  10304. };
  10305. Engine.prototype._releaseTexture = function (texture) {
  10306. var gl = this._gl;
  10307. if (texture._framebuffer) {
  10308. gl.deleteFramebuffer(texture._framebuffer);
  10309. }
  10310. if (texture._depthStencilBuffer) {
  10311. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10312. }
  10313. if (texture._MSAAFramebuffer) {
  10314. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10315. }
  10316. if (texture._MSAARenderBuffer) {
  10317. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10318. }
  10319. gl.deleteTexture(texture);
  10320. // Unbind channels
  10321. this.unbindAllTextures();
  10322. var index = this._loadedTexturesCache.indexOf(texture);
  10323. if (index !== -1) {
  10324. this._loadedTexturesCache.splice(index, 1);
  10325. }
  10326. };
  10327. Engine.prototype.setProgram = function (program) {
  10328. if (this._currentProgram !== program) {
  10329. this._gl.useProgram(program);
  10330. this._currentProgram = program;
  10331. }
  10332. };
  10333. Engine.prototype.bindSamplers = function (effect) {
  10334. this.setProgram(effect.getProgram());
  10335. var samplers = effect.getSamplers();
  10336. for (var index = 0; index < samplers.length; index++) {
  10337. var uniform = effect.getUniform(samplers[index]);
  10338. this._gl.uniform1i(uniform, index);
  10339. }
  10340. this._currentEffect = null;
  10341. };
  10342. Engine.prototype.activateTexture = function (texture) {
  10343. if (this._activeTexture !== texture) {
  10344. this._gl.activeTexture(texture);
  10345. this._activeTexture = texture;
  10346. }
  10347. };
  10348. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10349. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10350. this._gl.bindTexture(target, texture);
  10351. this._activeTexturesCache[this._activeTexture] = texture;
  10352. }
  10353. };
  10354. Engine.prototype._bindTexture = function (channel, texture) {
  10355. if (channel < 0) {
  10356. return;
  10357. }
  10358. this.activateTexture(this._gl.TEXTURE0 + channel);
  10359. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10360. };
  10361. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10362. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10363. };
  10364. Engine.prototype.unbindAllTextures = function () {
  10365. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10366. this.activateTexture(this._gl["TEXTURE" + channel]);
  10367. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10368. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10369. }
  10370. };
  10371. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10372. if (channel < 0) {
  10373. return;
  10374. }
  10375. this._gl.uniform1i(uniform, channel);
  10376. this._setTexture(channel, texture);
  10377. };
  10378. Engine.prototype._setTexture = function (channel, texture) {
  10379. // Not ready?
  10380. if (!texture || !texture.isReady()) {
  10381. if (this._activeTexturesCache[channel] != null) {
  10382. this.activateTexture(this._gl["TEXTURE" + channel]);
  10383. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10384. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10385. }
  10386. return;
  10387. }
  10388. // Video
  10389. var alreadyActivated = false;
  10390. if (texture instanceof BABYLON.VideoTexture) {
  10391. this.activateTexture(this._gl["TEXTURE" + channel]);
  10392. alreadyActivated = true;
  10393. texture.update();
  10394. }
  10395. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10396. texture.delayLoad();
  10397. return;
  10398. }
  10399. var internalTexture = texture.getInternalTexture();
  10400. if (this._activeTexturesCache[channel] === internalTexture) {
  10401. return;
  10402. }
  10403. if (!alreadyActivated) {
  10404. this.activateTexture(this._gl["TEXTURE" + channel]);
  10405. }
  10406. if (internalTexture.isCube) {
  10407. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10408. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10409. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10410. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10411. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10412. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10413. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10414. }
  10415. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10416. }
  10417. else {
  10418. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10419. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10420. internalTexture._cachedWrapU = texture.wrapU;
  10421. switch (texture.wrapU) {
  10422. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10423. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10424. break;
  10425. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10426. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10427. break;
  10428. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10429. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10430. break;
  10431. }
  10432. }
  10433. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10434. internalTexture._cachedWrapV = texture.wrapV;
  10435. switch (texture.wrapV) {
  10436. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10437. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10438. break;
  10439. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10440. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10441. break;
  10442. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10443. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10444. break;
  10445. }
  10446. }
  10447. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10448. }
  10449. };
  10450. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10451. if (channel < 0) {
  10452. return;
  10453. }
  10454. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10455. this._textureUnits = new Int32Array(textures.length);
  10456. }
  10457. for (var i = 0; i < textures.length; i++) {
  10458. this._textureUnits[i] = channel + i;
  10459. }
  10460. this._gl.uniform1iv(uniform, this._textureUnits);
  10461. for (var index = 0; index < textures.length; index++) {
  10462. this._setTexture(channel + index, textures[index]);
  10463. }
  10464. };
  10465. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10466. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10467. var value = texture.anisotropicFilteringLevel;
  10468. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10469. value = 1;
  10470. }
  10471. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10472. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10473. texture._cachedAnisotropicFilteringLevel = value;
  10474. }
  10475. };
  10476. Engine.prototype.readPixels = function (x, y, width, height) {
  10477. var data = new Uint8Array(height * width * 4);
  10478. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10479. return data;
  10480. };
  10481. /**
  10482. * Add an externaly attached data from its key.
  10483. * This method call will fail and return false, if such key already exists.
  10484. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10485. * @param key the unique key that identifies the data
  10486. * @param data the data object to associate to the key for this Engine instance
  10487. * @return true if no such key were already present and the data was added successfully, false otherwise
  10488. */
  10489. Engine.prototype.addExternalData = function (key, data) {
  10490. return this._externalData.add(key, data);
  10491. };
  10492. /**
  10493. * Get an externaly attached data from its key
  10494. * @param key the unique key that identifies the data
  10495. * @return the associated data, if present (can be null), or undefined if not present
  10496. */
  10497. Engine.prototype.getExternalData = function (key) {
  10498. return this._externalData.get(key);
  10499. };
  10500. /**
  10501. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10502. * @param key the unique key that identifies the data
  10503. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10504. * @return the associated data, can be null if the factory returned null.
  10505. */
  10506. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10507. return this._externalData.getOrAddWithFactory(key, factory);
  10508. };
  10509. /**
  10510. * Remove an externaly attached data from the Engine instance
  10511. * @param key the unique key that identifies the data
  10512. * @return true if the data was successfully removed, false if it doesn't exist
  10513. */
  10514. Engine.prototype.removeExternalData = function (key) {
  10515. return this._externalData.remove(key);
  10516. };
  10517. Engine.prototype.releaseInternalTexture = function (texture) {
  10518. if (!texture) {
  10519. return;
  10520. }
  10521. texture.references--;
  10522. // Final reference ?
  10523. if (texture.references === 0) {
  10524. var texturesCache = this.getLoadedTexturesCache();
  10525. var index = texturesCache.indexOf(texture);
  10526. if (index > -1) {
  10527. texturesCache.splice(index, 1);
  10528. }
  10529. this._releaseTexture(texture);
  10530. }
  10531. };
  10532. Engine.prototype.unbindAllAttributes = function () {
  10533. if (this._mustWipeVertexAttributes) {
  10534. this._mustWipeVertexAttributes = false;
  10535. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10536. this._gl.disableVertexAttribArray(i);
  10537. this._vertexAttribArraysEnabled[i] = false;
  10538. this._currentBufferPointers[i] = null;
  10539. }
  10540. return;
  10541. }
  10542. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10543. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10544. continue;
  10545. }
  10546. this._gl.disableVertexAttribArray(i);
  10547. this._vertexAttribArraysEnabled[i] = false;
  10548. this._currentBufferPointers[i] = null;
  10549. }
  10550. };
  10551. // Dispose
  10552. Engine.prototype.dispose = function () {
  10553. this.hideLoadingUI();
  10554. this.stopRenderLoop();
  10555. // Release scenes
  10556. while (this.scenes.length) {
  10557. this.scenes[0].dispose();
  10558. }
  10559. // Release audio engine
  10560. Engine.audioEngine.dispose();
  10561. // Release effects
  10562. for (var name in this._compiledEffects) {
  10563. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10564. }
  10565. // Unbind
  10566. this.unbindAllAttributes();
  10567. this._gl = null;
  10568. //WebVR
  10569. this.disableVR();
  10570. // Events
  10571. window.removeEventListener("blur", this._onBlur);
  10572. window.removeEventListener("focus", this._onFocus);
  10573. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10574. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10575. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10576. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10577. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10578. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10579. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10580. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10581. // Remove from Instances
  10582. var index = Engine.Instances.indexOf(this);
  10583. if (index >= 0) {
  10584. Engine.Instances.splice(index, 1);
  10585. }
  10586. };
  10587. // Loading screen
  10588. Engine.prototype.displayLoadingUI = function () {
  10589. this._loadingScreen.displayLoadingUI();
  10590. };
  10591. Engine.prototype.hideLoadingUI = function () {
  10592. this._loadingScreen.hideLoadingUI();
  10593. };
  10594. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10595. get: function () {
  10596. return this._loadingScreen;
  10597. },
  10598. set: function (loadingScreen) {
  10599. this._loadingScreen = loadingScreen;
  10600. },
  10601. enumerable: true,
  10602. configurable: true
  10603. });
  10604. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10605. set: function (text) {
  10606. this._loadingScreen.loadingUIText = text;
  10607. },
  10608. enumerable: true,
  10609. configurable: true
  10610. });
  10611. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10612. set: function (color) {
  10613. this._loadingScreen.loadingUIBackgroundColor = color;
  10614. },
  10615. enumerable: true,
  10616. configurable: true
  10617. });
  10618. Engine.prototype.attachContextLostEvent = function (callback) {
  10619. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10620. };
  10621. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10622. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10623. };
  10624. Engine.prototype.getVertexShaderSource = function (program) {
  10625. var shaders = this._gl.getAttachedShaders(program);
  10626. return this._gl.getShaderSource(shaders[0]);
  10627. };
  10628. Engine.prototype.getFragmentShaderSource = function (program) {
  10629. var shaders = this._gl.getAttachedShaders(program);
  10630. return this._gl.getShaderSource(shaders[1]);
  10631. };
  10632. // FPS
  10633. Engine.prototype.getFps = function () {
  10634. return this.fps;
  10635. };
  10636. Engine.prototype.getDeltaTime = function () {
  10637. return this.deltaTime;
  10638. };
  10639. Engine.prototype._measureFps = function () {
  10640. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10641. var length = this.previousFramesDuration.length;
  10642. if (length >= 2) {
  10643. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10644. }
  10645. if (length >= this.fpsRange) {
  10646. if (length > this.fpsRange) {
  10647. this.previousFramesDuration.splice(0, 1);
  10648. length = this.previousFramesDuration.length;
  10649. }
  10650. var sum = 0;
  10651. for (var id = 0; id < length - 1; id++) {
  10652. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10653. }
  10654. this.fps = 1000.0 / (sum / (length - 1));
  10655. }
  10656. };
  10657. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10658. if (this._webGLVersion > 1) {
  10659. return this._caps.colorBufferFloat;
  10660. }
  10661. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10662. };
  10663. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10664. if (this._webGLVersion > 1) {
  10665. return this._caps.colorBufferFloat;
  10666. }
  10667. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10668. };
  10669. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10670. Engine.prototype._canRenderToFramebuffer = function (type) {
  10671. var gl = this._gl;
  10672. //clear existing errors
  10673. while (gl.getError() !== gl.NO_ERROR) { }
  10674. var successful = true;
  10675. var texture = gl.createTexture();
  10676. gl.bindTexture(gl.TEXTURE_2D, texture);
  10677. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10678. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10679. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10680. var fb = gl.createFramebuffer();
  10681. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10682. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10683. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10684. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10685. successful = successful && (gl.getError() === gl.NO_ERROR);
  10686. //try render by clearing frame buffer's color buffer
  10687. if (successful) {
  10688. gl.clear(gl.COLOR_BUFFER_BIT);
  10689. successful = successful && (gl.getError() === gl.NO_ERROR);
  10690. }
  10691. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10692. if (successful) {
  10693. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10694. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10695. var readFormat = gl.RGBA;
  10696. var readType = gl.UNSIGNED_BYTE;
  10697. var buffer = new Uint8Array(4);
  10698. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10699. successful = successful && (gl.getError() === gl.NO_ERROR);
  10700. }
  10701. //clean up
  10702. gl.deleteTexture(texture);
  10703. gl.deleteFramebuffer(fb);
  10704. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10705. //clear accumulated errors
  10706. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10707. return successful;
  10708. };
  10709. Engine.prototype._getWebGLTextureType = function (type) {
  10710. if (type === Engine.TEXTURETYPE_FLOAT) {
  10711. return this._gl.FLOAT;
  10712. }
  10713. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10714. // Add Half Float Constant.
  10715. return Engine.HALF_FLOAT_OES;
  10716. }
  10717. return this._gl.UNSIGNED_BYTE;
  10718. };
  10719. ;
  10720. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10721. if (this._webGLVersion === 1) {
  10722. return this._gl.RGBA;
  10723. }
  10724. if (type === Engine.TEXTURETYPE_FLOAT) {
  10725. return Engine.RGBA32F;
  10726. }
  10727. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10728. return Engine.RGBA16F;
  10729. }
  10730. return this._gl.RGBA;
  10731. };
  10732. ;
  10733. // Statics
  10734. Engine.isSupported = function () {
  10735. try {
  10736. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10737. if (navigator.isCocoonJS) {
  10738. return true;
  10739. }
  10740. var tempcanvas = document.createElement("canvas");
  10741. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10742. return gl != null && !!window.WebGLRenderingContext;
  10743. }
  10744. catch (e) {
  10745. return false;
  10746. }
  10747. };
  10748. return Engine;
  10749. }());
  10750. Engine.Instances = new Array();
  10751. // Const statics
  10752. Engine._ALPHA_DISABLE = 0;
  10753. Engine._ALPHA_ADD = 1;
  10754. Engine._ALPHA_COMBINE = 2;
  10755. Engine._ALPHA_SUBTRACT = 3;
  10756. Engine._ALPHA_MULTIPLY = 4;
  10757. Engine._ALPHA_MAXIMIZED = 5;
  10758. Engine._ALPHA_ONEONE = 6;
  10759. Engine._ALPHA_PREMULTIPLIED = 7;
  10760. Engine._DELAYLOADSTATE_NONE = 0;
  10761. Engine._DELAYLOADSTATE_LOADED = 1;
  10762. Engine._DELAYLOADSTATE_LOADING = 2;
  10763. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10764. Engine._TEXTUREFORMAT_ALPHA = 0;
  10765. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10766. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10767. Engine._TEXTUREFORMAT_RGB = 4;
  10768. Engine._TEXTUREFORMAT_RGBA = 5;
  10769. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10770. Engine._TEXTURETYPE_FLOAT = 1;
  10771. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10772. // Depht or Stencil test Constants.
  10773. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10774. 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.
  10775. 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.
  10776. 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.
  10777. 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.
  10778. 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.
  10779. 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.
  10780. 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.
  10781. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10782. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10783. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10784. // Stencil Actions Constants.
  10785. Engine._KEEP = 0x1E00;
  10786. Engine._REPLACE = 0x1E01;
  10787. Engine._INCR = 0x1E02;
  10788. Engine._DECR = 0x1E03;
  10789. Engine._INVERT = 0x150A;
  10790. Engine._INCR_WRAP = 0x8507;
  10791. Engine._DECR_WRAP = 0x8508;
  10792. // Updatable statics so stick with vars here
  10793. Engine.CollisionsEpsilon = 0.001;
  10794. Engine.CodeRepository = "src/";
  10795. Engine.ShadersRepository = "src/Shaders/";
  10796. BABYLON.Engine = Engine;
  10797. })(BABYLON || (BABYLON = {}));
  10798. //# sourceMappingURL=babylon.engine.js.map
  10799. /// <reference path="Tools\babylon.decorators.ts" />
  10800. var BABYLON;
  10801. (function (BABYLON) {
  10802. /**
  10803. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10804. */
  10805. var Node = (function () {
  10806. /**
  10807. * @constructor
  10808. * @param {string} name - the name and id to be given to this node
  10809. * @param {BABYLON.Scene} the scene this node will be added to
  10810. */
  10811. function Node(name, scene) {
  10812. this.state = "";
  10813. this.metadata = null;
  10814. this.doNotSerialize = false;
  10815. this.animations = new Array();
  10816. this._ranges = {};
  10817. this._childrenFlag = -1;
  10818. this._isEnabled = true;
  10819. this._isReady = true;
  10820. this._currentRenderId = -1;
  10821. this._parentRenderId = -1;
  10822. /**
  10823. * An event triggered when the mesh is disposed.
  10824. * @type {BABYLON.Observable}
  10825. */
  10826. this.onDisposeObservable = new BABYLON.Observable();
  10827. this.name = name;
  10828. this.id = name;
  10829. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10830. this._initCache();
  10831. }
  10832. Object.defineProperty(Node.prototype, "parent", {
  10833. get: function () {
  10834. return this._parentNode;
  10835. },
  10836. set: function (parent) {
  10837. if (this._parentNode === parent) {
  10838. return;
  10839. }
  10840. if (this._parentNode) {
  10841. var index = this._parentNode._children.indexOf(this);
  10842. if (index !== -1) {
  10843. this._parentNode._children.splice(index, 1);
  10844. }
  10845. }
  10846. this._parentNode = parent;
  10847. if (this._parentNode) {
  10848. if (!this._parentNode._children) {
  10849. this._parentNode._children = new Array();
  10850. }
  10851. this._parentNode._children.push(this);
  10852. }
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Node.prototype.getClassName = function () {
  10858. return "Node";
  10859. };
  10860. Object.defineProperty(Node.prototype, "onDispose", {
  10861. set: function (callback) {
  10862. if (this._onDisposeObserver) {
  10863. this.onDisposeObservable.remove(this._onDisposeObserver);
  10864. }
  10865. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10866. },
  10867. enumerable: true,
  10868. configurable: true
  10869. });
  10870. Node.prototype.getScene = function () {
  10871. return this._scene;
  10872. };
  10873. Node.prototype.getEngine = function () {
  10874. return this._scene.getEngine();
  10875. };
  10876. // override it in derived class
  10877. Node.prototype.getWorldMatrix = function () {
  10878. return BABYLON.Matrix.Identity();
  10879. };
  10880. // override it in derived class if you add new variables to the cache
  10881. // and call the parent class method
  10882. Node.prototype._initCache = function () {
  10883. this._cache = {};
  10884. this._cache.parent = undefined;
  10885. };
  10886. Node.prototype.updateCache = function (force) {
  10887. if (!force && this.isSynchronized())
  10888. return;
  10889. this._cache.parent = this.parent;
  10890. this._updateCache();
  10891. };
  10892. // override it in derived class if you add new variables to the cache
  10893. // and call the parent class method if !ignoreParentClass
  10894. Node.prototype._updateCache = function (ignoreParentClass) {
  10895. };
  10896. // override it in derived class if you add new variables to the cache
  10897. Node.prototype._isSynchronized = function () {
  10898. return true;
  10899. };
  10900. Node.prototype._markSyncedWithParent = function () {
  10901. this._parentRenderId = this.parent._currentRenderId;
  10902. };
  10903. Node.prototype.isSynchronizedWithParent = function () {
  10904. if (!this.parent) {
  10905. return true;
  10906. }
  10907. if (this._parentRenderId !== this.parent._currentRenderId) {
  10908. return false;
  10909. }
  10910. return this.parent.isSynchronized();
  10911. };
  10912. Node.prototype.isSynchronized = function (updateCache) {
  10913. var check = this.hasNewParent();
  10914. check = check || !this.isSynchronizedWithParent();
  10915. check = check || !this._isSynchronized();
  10916. if (updateCache)
  10917. this.updateCache(true);
  10918. return !check;
  10919. };
  10920. Node.prototype.hasNewParent = function (update) {
  10921. if (this._cache.parent === this.parent)
  10922. return false;
  10923. if (update)
  10924. this._cache.parent = this.parent;
  10925. return true;
  10926. };
  10927. /**
  10928. * Is this node ready to be used/rendered
  10929. * @return {boolean} is it ready
  10930. */
  10931. Node.prototype.isReady = function () {
  10932. return this._isReady;
  10933. };
  10934. /**
  10935. * Is this node enabled.
  10936. * If the node has a parent and is enabled, the parent will be inspected as well.
  10937. * @return {boolean} whether this node (and its parent) is enabled.
  10938. * @see setEnabled
  10939. */
  10940. Node.prototype.isEnabled = function () {
  10941. if (!this._isEnabled) {
  10942. return false;
  10943. }
  10944. if (this.parent) {
  10945. return this.parent.isEnabled();
  10946. }
  10947. return true;
  10948. };
  10949. /**
  10950. * Set the enabled state of this node.
  10951. * @param {boolean} value - the new enabled state
  10952. * @see isEnabled
  10953. */
  10954. Node.prototype.setEnabled = function (value) {
  10955. this._isEnabled = value;
  10956. };
  10957. /**
  10958. * Is this node a descendant of the given node.
  10959. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10960. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10961. * @see parent
  10962. */
  10963. Node.prototype.isDescendantOf = function (ancestor) {
  10964. if (this.parent) {
  10965. if (this.parent === ancestor) {
  10966. return true;
  10967. }
  10968. return this.parent.isDescendantOf(ancestor);
  10969. }
  10970. return false;
  10971. };
  10972. /**
  10973. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10974. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10975. * @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.
  10976. * @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.
  10977. */
  10978. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10979. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10980. if (!this._children) {
  10981. return;
  10982. }
  10983. for (var index = 0; index < this._children.length; index++) {
  10984. var item = this._children[index];
  10985. if (!predicate || predicate(item)) {
  10986. results.push(item);
  10987. }
  10988. if (!directDescendantsOnly) {
  10989. item._getDescendants(results, false, predicate);
  10990. }
  10991. }
  10992. };
  10993. /**
  10994. * Will return all nodes that have this node as ascendant.
  10995. * @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.
  10996. * @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.
  10997. * @return {BABYLON.Node[]} all children nodes of all types.
  10998. */
  10999. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11000. var results = [];
  11001. this._getDescendants(results, directDescendantsOnly, predicate);
  11002. return results;
  11003. };
  11004. /**
  11005. * Get all child-meshes of this node.
  11006. */
  11007. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11008. var results = [];
  11009. this._getDescendants(results, directDecendantsOnly, function (node) {
  11010. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11011. });
  11012. return results;
  11013. };
  11014. /**
  11015. * Get all direct children of this node.
  11016. */
  11017. Node.prototype.getChildren = function (predicate) {
  11018. return this.getDescendants(true, predicate);
  11019. };
  11020. Node.prototype._setReady = function (state) {
  11021. if (state === this._isReady) {
  11022. return;
  11023. }
  11024. if (!state) {
  11025. this._isReady = false;
  11026. return;
  11027. }
  11028. this._isReady = true;
  11029. if (this.onReady) {
  11030. this.onReady(this);
  11031. }
  11032. };
  11033. Node.prototype.getAnimationByName = function (name) {
  11034. for (var i = 0; i < this.animations.length; i++) {
  11035. var animation = this.animations[i];
  11036. if (animation.name === name) {
  11037. return animation;
  11038. }
  11039. }
  11040. return null;
  11041. };
  11042. Node.prototype.createAnimationRange = function (name, from, to) {
  11043. // check name not already in use
  11044. if (!this._ranges[name]) {
  11045. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11046. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11047. if (this.animations[i]) {
  11048. this.animations[i].createRange(name, from, to);
  11049. }
  11050. }
  11051. }
  11052. };
  11053. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11054. if (deleteFrames === void 0) { deleteFrames = true; }
  11055. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11056. if (this.animations[i]) {
  11057. this.animations[i].deleteRange(name, deleteFrames);
  11058. }
  11059. }
  11060. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11061. };
  11062. Node.prototype.getAnimationRange = function (name) {
  11063. return this._ranges[name];
  11064. };
  11065. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11066. var range = this.getAnimationRange(name);
  11067. if (!range) {
  11068. return null;
  11069. }
  11070. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11071. };
  11072. Node.prototype.serializeAnimationRanges = function () {
  11073. var serializationRanges = [];
  11074. for (var name in this._ranges) {
  11075. var range = {};
  11076. range.name = name;
  11077. range.from = this._ranges[name].from;
  11078. range.to = this._ranges[name].to;
  11079. serializationRanges.push(range);
  11080. }
  11081. return serializationRanges;
  11082. };
  11083. Node.prototype.dispose = function () {
  11084. this.parent = null;
  11085. // Callback
  11086. this.onDisposeObservable.notifyObservers(this);
  11087. this.onDisposeObservable.clear();
  11088. };
  11089. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11090. if (parsedNode.ranges) {
  11091. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11092. var data = parsedNode.ranges[index];
  11093. node.createAnimationRange(data.name, data.from, data.to);
  11094. }
  11095. }
  11096. };
  11097. return Node;
  11098. }());
  11099. __decorate([
  11100. BABYLON.serialize()
  11101. ], Node.prototype, "name", void 0);
  11102. __decorate([
  11103. BABYLON.serialize()
  11104. ], Node.prototype, "id", void 0);
  11105. __decorate([
  11106. BABYLON.serialize()
  11107. ], Node.prototype, "uniqueId", void 0);
  11108. __decorate([
  11109. BABYLON.serialize()
  11110. ], Node.prototype, "state", void 0);
  11111. __decorate([
  11112. BABYLON.serialize()
  11113. ], Node.prototype, "metadata", void 0);
  11114. BABYLON.Node = Node;
  11115. })(BABYLON || (BABYLON = {}));
  11116. //# sourceMappingURL=babylon.node.js.map
  11117. var BABYLON;
  11118. (function (BABYLON) {
  11119. var FilesInput = (function () {
  11120. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  11121. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  11122. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  11123. this._engine = p_engine;
  11124. this._canvas = p_canvas;
  11125. this._currentScene = p_scene;
  11126. this._sceneLoadedCallback = p_sceneLoadedCallback;
  11127. this._progressCallback = p_progressCallback;
  11128. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  11129. this._textureLoadingCallback = p_textureLoadingCallback;
  11130. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  11131. }
  11132. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  11133. var _this = this;
  11134. if (p_elementToMonitor) {
  11135. this._elementToMonitor = p_elementToMonitor;
  11136. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  11137. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  11138. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  11139. }
  11140. };
  11141. FilesInput.prototype.renderFunction = function () {
  11142. if (this._additionnalRenderLoopLogicCallback) {
  11143. this._additionnalRenderLoopLogicCallback();
  11144. }
  11145. if (this._currentScene) {
  11146. if (this._textureLoadingCallback) {
  11147. var remaining = this._currentScene.getWaitingItemsCount();
  11148. if (remaining > 0) {
  11149. this._textureLoadingCallback(remaining);
  11150. }
  11151. }
  11152. this._currentScene.render();
  11153. }
  11154. };
  11155. FilesInput.prototype.drag = function (e) {
  11156. e.stopPropagation();
  11157. e.preventDefault();
  11158. };
  11159. FilesInput.prototype.drop = function (eventDrop) {
  11160. eventDrop.stopPropagation();
  11161. eventDrop.preventDefault();
  11162. this.loadFiles(eventDrop);
  11163. };
  11164. FilesInput.prototype.loadFiles = function (event) {
  11165. if (this._startingProcessingFilesCallback)
  11166. this._startingProcessingFilesCallback();
  11167. // Handling data transfer via drag'n'drop
  11168. if (event && event.dataTransfer && event.dataTransfer.files) {
  11169. this._filesToLoad = event.dataTransfer.files;
  11170. }
  11171. // Handling files from input files
  11172. if (event && event.target && event.target.files) {
  11173. this._filesToLoad = event.target.files;
  11174. }
  11175. if (this._filesToLoad && this._filesToLoad.length > 0) {
  11176. for (var i = 0; i < this._filesToLoad.length; i++) {
  11177. var name_1 = this._filesToLoad[i].name.toLowerCase();
  11178. var extension = name_1.split('.').pop();
  11179. var type = this._filesToLoad[i].type;
  11180. if (extension === "jpg" || extension === "png" || extension === "bmp" || extension === "jpeg" ||
  11181. type === "image/jpeg" || type === "image/png" || type === "image/bmp") {
  11182. FilesInput.FilesTextures[name_1] = this._filesToLoad[i];
  11183. }
  11184. else {
  11185. if ((extension === "babylon" || extension === "stl" || extension === "obj")
  11186. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  11187. this._sceneFileToLoad = this._filesToLoad[i];
  11188. }
  11189. else {
  11190. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  11191. }
  11192. }
  11193. }
  11194. this.reload();
  11195. }
  11196. };
  11197. FilesInput.prototype.reload = function () {
  11198. var _this = this;
  11199. var that = this;
  11200. // If a ".babylon" file has been provided
  11201. if (this._sceneFileToLoad) {
  11202. if (this._currentScene) {
  11203. if (BABYLON.Tools.errorsCount > 0) {
  11204. BABYLON.Tools.ClearLogCache();
  11205. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  11206. }
  11207. this._engine.stopRenderLoop();
  11208. this._currentScene.dispose();
  11209. }
  11210. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  11211. that._currentScene = newScene;
  11212. // Wait for textures and shaders to be ready
  11213. that._currentScene.executeWhenReady(function () {
  11214. // Attach camera to canvas inputs
  11215. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  11216. that._currentScene.createDefaultCameraOrLight();
  11217. }
  11218. that._currentScene.activeCamera.attachControl(that._canvas);
  11219. if (that._sceneLoadedCallback) {
  11220. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  11221. }
  11222. that._engine.runRenderLoop(function () { that.renderFunction(); });
  11223. });
  11224. }, function (progress) {
  11225. if (_this._progressCallback) {
  11226. _this._progressCallback(progress);
  11227. }
  11228. });
  11229. }
  11230. else {
  11231. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  11232. }
  11233. };
  11234. return FilesInput;
  11235. }());
  11236. FilesInput.FilesTextures = new Array();
  11237. FilesInput.FilesToLoad = new Array();
  11238. BABYLON.FilesInput = FilesInput;
  11239. })(BABYLON || (BABYLON = {}));
  11240. //# sourceMappingURL=babylon.filesInput.js.map
  11241. var BABYLON;
  11242. (function (BABYLON) {
  11243. var IntersectionInfo = (function () {
  11244. function IntersectionInfo(bu, bv, distance) {
  11245. this.bu = bu;
  11246. this.bv = bv;
  11247. this.distance = distance;
  11248. this.faceId = 0;
  11249. this.subMeshId = 0;
  11250. }
  11251. return IntersectionInfo;
  11252. }());
  11253. BABYLON.IntersectionInfo = IntersectionInfo;
  11254. var PickingInfo = (function () {
  11255. function PickingInfo() {
  11256. this.hit = false;
  11257. this.distance = 0;
  11258. this.pickedPoint = null;
  11259. this.pickedMesh = null;
  11260. this.bu = 0;
  11261. this.bv = 0;
  11262. this.faceId = -1;
  11263. this.subMeshId = 0;
  11264. this.pickedSprite = null;
  11265. }
  11266. // Methods
  11267. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  11268. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  11269. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  11270. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11271. return null;
  11272. }
  11273. var indices = this.pickedMesh.getIndices();
  11274. var result;
  11275. if (useVerticesNormals) {
  11276. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11277. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  11278. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  11279. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  11280. normal0 = normal0.scale(this.bu);
  11281. normal1 = normal1.scale(this.bv);
  11282. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  11283. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  11284. }
  11285. else {
  11286. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11287. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  11288. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  11289. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  11290. var p1p2 = vertex1.subtract(vertex2);
  11291. var p3p2 = vertex3.subtract(vertex2);
  11292. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  11293. }
  11294. if (useWorldCoordinates) {
  11295. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  11296. }
  11297. return BABYLON.Vector3.Normalize(result);
  11298. };
  11299. PickingInfo.prototype.getTextureCoordinates = function () {
  11300. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11301. return null;
  11302. }
  11303. var indices = this.pickedMesh.getIndices();
  11304. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11305. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  11306. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  11307. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  11308. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  11309. uv1 = uv1.scale(this.bu);
  11310. uv2 = uv2.scale(this.bv);
  11311. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  11312. };
  11313. return PickingInfo;
  11314. }());
  11315. BABYLON.PickingInfo = PickingInfo;
  11316. })(BABYLON || (BABYLON = {}));
  11317. //# sourceMappingURL=babylon.pickingInfo.js.map
  11318. var BABYLON;
  11319. (function (BABYLON) {
  11320. var BoundingSphere = (function () {
  11321. function BoundingSphere(minimum, maximum) {
  11322. this.minimum = minimum;
  11323. this.maximum = maximum;
  11324. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11325. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11326. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11327. this.radius = distance * 0.5;
  11328. this.centerWorld = BABYLON.Vector3.Zero();
  11329. this._update(BABYLON.Matrix.Identity());
  11330. }
  11331. // Methods
  11332. BoundingSphere.prototype._update = function (world) {
  11333. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11334. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11335. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11336. };
  11337. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11338. for (var i = 0; i < 6; i++) {
  11339. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11340. return false;
  11341. }
  11342. return true;
  11343. };
  11344. BoundingSphere.prototype.intersectsPoint = function (point) {
  11345. var x = this.centerWorld.x - point.x;
  11346. var y = this.centerWorld.y - point.y;
  11347. var z = this.centerWorld.z - point.z;
  11348. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11349. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11350. return false;
  11351. return true;
  11352. };
  11353. // Statics
  11354. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11355. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11356. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11357. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11358. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11359. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11360. return false;
  11361. return true;
  11362. };
  11363. return BoundingSphere;
  11364. }());
  11365. BABYLON.BoundingSphere = BoundingSphere;
  11366. })(BABYLON || (BABYLON = {}));
  11367. //# sourceMappingURL=babylon.boundingSphere.js.map
  11368. var BABYLON;
  11369. (function (BABYLON) {
  11370. var BoundingBox = (function () {
  11371. function BoundingBox(minimum, maximum) {
  11372. this.minimum = minimum;
  11373. this.maximum = maximum;
  11374. this.vectors = new Array();
  11375. this.vectorsWorld = new Array();
  11376. // Bounding vectors
  11377. this.vectors.push(this.minimum.clone());
  11378. this.vectors.push(this.maximum.clone());
  11379. this.vectors.push(this.minimum.clone());
  11380. this.vectors[2].x = this.maximum.x;
  11381. this.vectors.push(this.minimum.clone());
  11382. this.vectors[3].y = this.maximum.y;
  11383. this.vectors.push(this.minimum.clone());
  11384. this.vectors[4].z = this.maximum.z;
  11385. this.vectors.push(this.maximum.clone());
  11386. this.vectors[5].z = this.minimum.z;
  11387. this.vectors.push(this.maximum.clone());
  11388. this.vectors[6].x = this.minimum.x;
  11389. this.vectors.push(this.maximum.clone());
  11390. this.vectors[7].y = this.minimum.y;
  11391. // OBB
  11392. this.center = this.maximum.add(this.minimum).scale(0.5);
  11393. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11394. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11395. // World
  11396. for (var index = 0; index < this.vectors.length; index++) {
  11397. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11398. }
  11399. this.minimumWorld = BABYLON.Vector3.Zero();
  11400. this.maximumWorld = BABYLON.Vector3.Zero();
  11401. this.centerWorld = BABYLON.Vector3.Zero();
  11402. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11403. this._update(BABYLON.Matrix.Identity());
  11404. }
  11405. // Methods
  11406. BoundingBox.prototype.getWorldMatrix = function () {
  11407. return this._worldMatrix;
  11408. };
  11409. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11410. this._worldMatrix.copyFrom(matrix);
  11411. return this;
  11412. };
  11413. BoundingBox.prototype._update = function (world) {
  11414. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11415. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11416. for (var index = 0; index < this.vectors.length; index++) {
  11417. var v = this.vectorsWorld[index];
  11418. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11419. if (v.x < this.minimumWorld.x)
  11420. this.minimumWorld.x = v.x;
  11421. if (v.y < this.minimumWorld.y)
  11422. this.minimumWorld.y = v.y;
  11423. if (v.z < this.minimumWorld.z)
  11424. this.minimumWorld.z = v.z;
  11425. if (v.x > this.maximumWorld.x)
  11426. this.maximumWorld.x = v.x;
  11427. if (v.y > this.maximumWorld.y)
  11428. this.maximumWorld.y = v.y;
  11429. if (v.z > this.maximumWorld.z)
  11430. this.maximumWorld.z = v.z;
  11431. }
  11432. // Extend
  11433. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11434. this.extendSizeWorld.scaleInPlace(0.5);
  11435. // OBB
  11436. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11437. this.centerWorld.scaleInPlace(0.5);
  11438. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11439. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11440. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11441. this._worldMatrix = world;
  11442. };
  11443. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11444. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11445. };
  11446. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11447. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11448. };
  11449. BoundingBox.prototype.intersectsPoint = function (point) {
  11450. var delta = -BABYLON.Epsilon;
  11451. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11452. return false;
  11453. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11454. return false;
  11455. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11456. return false;
  11457. return true;
  11458. };
  11459. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11460. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11461. };
  11462. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11463. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11464. return false;
  11465. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11466. return false;
  11467. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11468. return false;
  11469. return true;
  11470. };
  11471. // Statics
  11472. BoundingBox.Intersects = function (box0, box1) {
  11473. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11474. return false;
  11475. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11476. return false;
  11477. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11478. return false;
  11479. return true;
  11480. };
  11481. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11482. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11483. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11484. return (num <= (sphereRadius * sphereRadius));
  11485. };
  11486. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11487. for (var p = 0; p < 6; p++) {
  11488. for (var i = 0; i < 8; i++) {
  11489. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11490. return false;
  11491. }
  11492. }
  11493. }
  11494. return true;
  11495. };
  11496. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11497. for (var p = 0; p < 6; p++) {
  11498. var inCount = 8;
  11499. for (var i = 0; i < 8; i++) {
  11500. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11501. --inCount;
  11502. }
  11503. else {
  11504. break;
  11505. }
  11506. }
  11507. if (inCount === 0)
  11508. return false;
  11509. }
  11510. return true;
  11511. };
  11512. return BoundingBox;
  11513. }());
  11514. BABYLON.BoundingBox = BoundingBox;
  11515. })(BABYLON || (BABYLON = {}));
  11516. //# sourceMappingURL=babylon.boundingBox.js.map
  11517. var BABYLON;
  11518. (function (BABYLON) {
  11519. var computeBoxExtents = function (axis, box) {
  11520. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11521. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11522. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11523. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11524. var r = r0 + r1 + r2;
  11525. return {
  11526. min: p - r,
  11527. max: p + r
  11528. };
  11529. };
  11530. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11531. var axisOverlap = function (axis, box0, box1) {
  11532. var result0 = computeBoxExtents(axis, box0);
  11533. var result1 = computeBoxExtents(axis, box1);
  11534. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11535. };
  11536. var BoundingInfo = (function () {
  11537. function BoundingInfo(minimum, maximum) {
  11538. this.minimum = minimum;
  11539. this.maximum = maximum;
  11540. this._isLocked = false;
  11541. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11542. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11543. }
  11544. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11545. get: function () {
  11546. return this._isLocked;
  11547. },
  11548. set: function (value) {
  11549. this._isLocked = value;
  11550. },
  11551. enumerable: true,
  11552. configurable: true
  11553. });
  11554. // Methods
  11555. BoundingInfo.prototype.update = function (world) {
  11556. if (this._isLocked) {
  11557. return;
  11558. }
  11559. this.boundingBox._update(world);
  11560. this.boundingSphere._update(world);
  11561. };
  11562. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11563. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11564. return false;
  11565. return this.boundingBox.isInFrustum(frustumPlanes);
  11566. };
  11567. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11568. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11569. };
  11570. BoundingInfo.prototype._checkCollision = function (collider) {
  11571. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11572. };
  11573. BoundingInfo.prototype.intersectsPoint = function (point) {
  11574. if (!this.boundingSphere.centerWorld) {
  11575. return false;
  11576. }
  11577. if (!this.boundingSphere.intersectsPoint(point)) {
  11578. return false;
  11579. }
  11580. if (!this.boundingBox.intersectsPoint(point)) {
  11581. return false;
  11582. }
  11583. return true;
  11584. };
  11585. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11586. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11587. return false;
  11588. }
  11589. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11590. return false;
  11591. }
  11592. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11593. return false;
  11594. }
  11595. if (!precise) {
  11596. return true;
  11597. }
  11598. var box0 = this.boundingBox;
  11599. var box1 = boundingInfo.boundingBox;
  11600. if (!axisOverlap(box0.directions[0], box0, box1))
  11601. return false;
  11602. if (!axisOverlap(box0.directions[1], box0, box1))
  11603. return false;
  11604. if (!axisOverlap(box0.directions[2], box0, box1))
  11605. return false;
  11606. if (!axisOverlap(box1.directions[0], box0, box1))
  11607. return false;
  11608. if (!axisOverlap(box1.directions[1], box0, box1))
  11609. return false;
  11610. if (!axisOverlap(box1.directions[2], box0, box1))
  11611. return false;
  11612. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11613. return false;
  11614. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11615. return false;
  11616. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11617. return false;
  11618. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11619. return false;
  11620. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11621. return false;
  11622. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11623. return false;
  11624. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11625. return false;
  11626. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11627. return false;
  11628. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11629. return false;
  11630. return true;
  11631. };
  11632. return BoundingInfo;
  11633. }());
  11634. BABYLON.BoundingInfo = BoundingInfo;
  11635. })(BABYLON || (BABYLON = {}));
  11636. //# sourceMappingURL=babylon.boundingInfo.js.map
  11637. var BABYLON;
  11638. (function (BABYLON) {
  11639. var Ray = (function () {
  11640. function Ray(origin, direction, length) {
  11641. if (length === void 0) { length = Number.MAX_VALUE; }
  11642. this.origin = origin;
  11643. this.direction = direction;
  11644. this.length = length;
  11645. }
  11646. // Methods
  11647. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  11648. var d = 0.0;
  11649. var maxValue = Number.MAX_VALUE;
  11650. var inv;
  11651. var min;
  11652. var max;
  11653. var temp;
  11654. if (Math.abs(this.direction.x) < 0.0000001) {
  11655. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  11656. return false;
  11657. }
  11658. }
  11659. else {
  11660. inv = 1.0 / this.direction.x;
  11661. min = (minimum.x - this.origin.x) * inv;
  11662. max = (maximum.x - this.origin.x) * inv;
  11663. if (max === -Infinity) {
  11664. max = Infinity;
  11665. }
  11666. if (min > max) {
  11667. temp = min;
  11668. min = max;
  11669. max = temp;
  11670. }
  11671. d = Math.max(min, d);
  11672. maxValue = Math.min(max, maxValue);
  11673. if (d > maxValue) {
  11674. return false;
  11675. }
  11676. }
  11677. if (Math.abs(this.direction.y) < 0.0000001) {
  11678. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  11679. return false;
  11680. }
  11681. }
  11682. else {
  11683. inv = 1.0 / this.direction.y;
  11684. min = (minimum.y - this.origin.y) * inv;
  11685. max = (maximum.y - this.origin.y) * inv;
  11686. if (max === -Infinity) {
  11687. max = Infinity;
  11688. }
  11689. if (min > max) {
  11690. temp = min;
  11691. min = max;
  11692. max = temp;
  11693. }
  11694. d = Math.max(min, d);
  11695. maxValue = Math.min(max, maxValue);
  11696. if (d > maxValue) {
  11697. return false;
  11698. }
  11699. }
  11700. if (Math.abs(this.direction.z) < 0.0000001) {
  11701. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  11702. return false;
  11703. }
  11704. }
  11705. else {
  11706. inv = 1.0 / this.direction.z;
  11707. min = (minimum.z - this.origin.z) * inv;
  11708. max = (maximum.z - this.origin.z) * inv;
  11709. if (max === -Infinity) {
  11710. max = Infinity;
  11711. }
  11712. if (min > max) {
  11713. temp = min;
  11714. min = max;
  11715. max = temp;
  11716. }
  11717. d = Math.max(min, d);
  11718. maxValue = Math.min(max, maxValue);
  11719. if (d > maxValue) {
  11720. return false;
  11721. }
  11722. }
  11723. return true;
  11724. };
  11725. Ray.prototype.intersectsBox = function (box) {
  11726. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  11727. };
  11728. Ray.prototype.intersectsSphere = function (sphere) {
  11729. var x = sphere.center.x - this.origin.x;
  11730. var y = sphere.center.y - this.origin.y;
  11731. var z = sphere.center.z - this.origin.z;
  11732. var pyth = (x * x) + (y * y) + (z * z);
  11733. var rr = sphere.radius * sphere.radius;
  11734. if (pyth <= rr) {
  11735. return true;
  11736. }
  11737. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  11738. if (dot < 0.0) {
  11739. return false;
  11740. }
  11741. var temp = pyth - (dot * dot);
  11742. return temp <= rr;
  11743. };
  11744. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  11745. if (!this._edge1) {
  11746. this._edge1 = BABYLON.Vector3.Zero();
  11747. this._edge2 = BABYLON.Vector3.Zero();
  11748. this._pvec = BABYLON.Vector3.Zero();
  11749. this._tvec = BABYLON.Vector3.Zero();
  11750. this._qvec = BABYLON.Vector3.Zero();
  11751. }
  11752. vertex1.subtractToRef(vertex0, this._edge1);
  11753. vertex2.subtractToRef(vertex0, this._edge2);
  11754. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  11755. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  11756. if (det === 0) {
  11757. return null;
  11758. }
  11759. var invdet = 1 / det;
  11760. this.origin.subtractToRef(vertex0, this._tvec);
  11761. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  11762. if (bu < 0 || bu > 1.0) {
  11763. return null;
  11764. }
  11765. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  11766. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  11767. if (bv < 0 || bu + bv > 1.0) {
  11768. return null;
  11769. }
  11770. //check if the distance is longer than the predefined length.
  11771. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  11772. if (distance > this.length) {
  11773. return null;
  11774. }
  11775. return new BABYLON.IntersectionInfo(bu, bv, distance);
  11776. };
  11777. Ray.prototype.intersectsPlane = function (plane) {
  11778. var distance;
  11779. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  11780. if (Math.abs(result1) < 9.99999997475243E-07) {
  11781. return null;
  11782. }
  11783. else {
  11784. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  11785. distance = (-plane.d - result2) / result1;
  11786. if (distance < 0.0) {
  11787. if (distance < -9.99999997475243E-07) {
  11788. return null;
  11789. }
  11790. else {
  11791. return 0;
  11792. }
  11793. }
  11794. return distance;
  11795. }
  11796. };
  11797. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  11798. var tm = BABYLON.Tmp.Matrix[0];
  11799. mesh.getWorldMatrix().invertToRef(tm);
  11800. if (this._tmpRay) {
  11801. Ray.TransformToRef(this, tm, this._tmpRay);
  11802. }
  11803. else {
  11804. this._tmpRay = Ray.Transform(this, tm);
  11805. }
  11806. return mesh.intersects(this._tmpRay, fastCheck);
  11807. };
  11808. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  11809. if (results) {
  11810. results.length = 0;
  11811. }
  11812. else {
  11813. results = [];
  11814. }
  11815. for (var i = 0; i < meshes.length; i++) {
  11816. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  11817. if (pickInfo.hit) {
  11818. results.push(pickInfo);
  11819. }
  11820. }
  11821. results.sort(this._comparePickingInfo);
  11822. return results;
  11823. };
  11824. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  11825. if (pickingInfoA.distance < pickingInfoB.distance) {
  11826. return -1;
  11827. }
  11828. else if (pickingInfoA.distance > pickingInfoB.distance) {
  11829. return 1;
  11830. }
  11831. else {
  11832. return 0;
  11833. }
  11834. };
  11835. /**
  11836. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  11837. * @param sega the first point of the segment to test the intersection against
  11838. * @param segb the second point of the segment to test the intersection against
  11839. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  11840. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  11841. */
  11842. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  11843. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  11844. var u = segb.subtract(sega);
  11845. var v = rsegb.subtract(this.origin);
  11846. var w = sega.subtract(this.origin);
  11847. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  11848. var b = BABYLON.Vector3.Dot(u, v);
  11849. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  11850. var d = BABYLON.Vector3.Dot(u, w);
  11851. var e = BABYLON.Vector3.Dot(v, w);
  11852. var D = a * c - b * b; // always >= 0
  11853. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  11854. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  11855. // compute the line parameters of the two closest points
  11856. if (D < Ray.smallnum) {
  11857. sN = 0.0; // force using point P0 on segment S1
  11858. sD = 1.0; // to prevent possible division by 0.0 later
  11859. tN = e;
  11860. tD = c;
  11861. }
  11862. else {
  11863. sN = (b * e - c * d);
  11864. tN = (a * e - b * d);
  11865. if (sN < 0.0) {
  11866. sN = 0.0;
  11867. tN = e;
  11868. tD = c;
  11869. }
  11870. else if (sN > sD) {
  11871. sN = sD;
  11872. tN = e + b;
  11873. tD = c;
  11874. }
  11875. }
  11876. if (tN < 0.0) {
  11877. tN = 0.0;
  11878. // recompute sc for this edge
  11879. if (-d < 0.0) {
  11880. sN = 0.0;
  11881. }
  11882. else if (-d > a)
  11883. sN = sD;
  11884. else {
  11885. sN = -d;
  11886. sD = a;
  11887. }
  11888. }
  11889. else if (tN > tD) {
  11890. tN = tD;
  11891. // recompute sc for this edge
  11892. if ((-d + b) < 0.0) {
  11893. sN = 0;
  11894. }
  11895. else if ((-d + b) > a) {
  11896. sN = sD;
  11897. }
  11898. else {
  11899. sN = (-d + b);
  11900. sD = a;
  11901. }
  11902. }
  11903. // finally do the division to get sc and tc
  11904. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  11905. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  11906. // get the difference of the two closest points
  11907. var qtc = v.multiplyByFloats(tc, tc, tc);
  11908. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  11909. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  11910. if (isIntersected) {
  11911. return qtc.length();
  11912. }
  11913. return -1;
  11914. };
  11915. // Statics
  11916. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  11917. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  11918. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  11919. var direction = end.subtract(start);
  11920. direction.normalize();
  11921. return new Ray(start, direction);
  11922. };
  11923. /**
  11924. * 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
  11925. * transformed to the given world matrix.
  11926. * @param origin The origin point
  11927. * @param end The end point
  11928. * @param world a matrix to transform the ray to. Default is the identity matrix.
  11929. */
  11930. Ray.CreateNewFromTo = function (origin, end, world) {
  11931. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  11932. var direction = end.subtract(origin);
  11933. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  11934. direction.normalize();
  11935. return Ray.Transform(new Ray(origin, direction, length), world);
  11936. };
  11937. Ray.Transform = function (ray, matrix) {
  11938. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  11939. Ray.TransformToRef(ray, matrix, result);
  11940. return result;
  11941. };
  11942. Ray.TransformToRef = function (ray, matrix, result) {
  11943. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  11944. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  11945. result.length = ray.length;
  11946. var dir = result.direction;
  11947. var len = dir.length();
  11948. if (!(len === 0 || len === 1)) {
  11949. var num = 1.0 / len;
  11950. dir.x *= num;
  11951. dir.y *= num;
  11952. dir.z *= num;
  11953. result.length *= len;
  11954. }
  11955. };
  11956. return Ray;
  11957. }());
  11958. Ray.smallnum = 0.00000001;
  11959. Ray.rayl = 10e8;
  11960. BABYLON.Ray = Ray;
  11961. })(BABYLON || (BABYLON = {}));
  11962. //# sourceMappingURL=babylon.ray.js.map
  11963. var BABYLON;
  11964. (function (BABYLON) {
  11965. var RayHelper = (function () {
  11966. function RayHelper(ray) {
  11967. this.ray = ray;
  11968. }
  11969. RayHelper.CreateAndShow = function (ray, scene, color) {
  11970. var helper = new RayHelper(ray);
  11971. helper.show(scene, color);
  11972. return helper;
  11973. };
  11974. RayHelper.prototype.show = function (scene, color) {
  11975. if (!this._renderFunction) {
  11976. var ray = this.ray;
  11977. this._renderFunction = this._render.bind(this);
  11978. this._scene = scene;
  11979. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  11980. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  11981. this._scene.registerBeforeRender(this._renderFunction);
  11982. }
  11983. if (color) {
  11984. this._renderLine.color.copyFrom(color);
  11985. }
  11986. };
  11987. RayHelper.prototype.hide = function () {
  11988. if (this._renderFunction) {
  11989. this._scene.unregisterBeforeRender(this._renderFunction);
  11990. this._scene = null;
  11991. this._renderFunction = null;
  11992. this._renderLine.dispose();
  11993. this._renderLine = null;
  11994. this._renderPoints = null;
  11995. }
  11996. };
  11997. RayHelper.prototype._render = function () {
  11998. var ray = this.ray;
  11999. var point = this._renderPoints[1];
  12000. var len = Math.min(ray.length, 1000000);
  12001. point.copyFrom(ray.direction);
  12002. point.scaleInPlace(len);
  12003. point.addInPlace(ray.origin);
  12004. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  12005. };
  12006. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  12007. this._attachedToMesh = mesh;
  12008. var ray = this.ray;
  12009. if (!ray.direction) {
  12010. ray.direction = BABYLON.Vector3.Zero();
  12011. }
  12012. if (!ray.origin) {
  12013. ray.origin = BABYLON.Vector3.Zero();
  12014. }
  12015. if (length) {
  12016. ray.length = length;
  12017. }
  12018. if (!meshSpaceOrigin) {
  12019. meshSpaceOrigin = BABYLON.Vector3.Zero();
  12020. }
  12021. if (!meshSpaceDirection) {
  12022. // -1 so that this will work with Mesh.lookAt
  12023. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  12024. }
  12025. if (!this._meshSpaceDirection) {
  12026. this._meshSpaceDirection = meshSpaceDirection.clone();
  12027. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  12028. }
  12029. else {
  12030. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  12031. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  12032. }
  12033. if (!this._updateToMeshFunction) {
  12034. this._updateToMeshFunction = this._updateToMesh.bind(this);
  12035. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  12036. }
  12037. this._updateToMesh();
  12038. };
  12039. RayHelper.prototype.detachFromMesh = function () {
  12040. if (this._attachedToMesh) {
  12041. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  12042. this._attachedToMesh = null;
  12043. this._updateToMeshFunction = null;
  12044. }
  12045. };
  12046. RayHelper.prototype._updateToMesh = function () {
  12047. var ray = this.ray;
  12048. if (this._attachedToMesh._isDisposed) {
  12049. this.detachFromMesh();
  12050. return;
  12051. }
  12052. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  12053. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  12054. };
  12055. RayHelper.prototype.dispose = function () {
  12056. this.hide();
  12057. this.detachFromMesh();
  12058. this.ray = null;
  12059. };
  12060. return RayHelper;
  12061. }());
  12062. BABYLON.RayHelper = RayHelper;
  12063. })(BABYLON || (BABYLON = {}));
  12064. //# sourceMappingURL=babylon.rayHelper.js.map
  12065. var BABYLON;
  12066. (function (BABYLON) {
  12067. var AbstractMesh = (function (_super) {
  12068. __extends(AbstractMesh, _super);
  12069. // Constructor
  12070. function AbstractMesh(name, scene) {
  12071. var _this = _super.call(this, name, scene) || this;
  12072. _this._facetNb = 0; // facet number
  12073. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12074. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12075. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12076. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12077. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12078. _this._subDiv = {
  12079. max: 1,
  12080. X: 1,
  12081. Y: 1,
  12082. Z: 1
  12083. };
  12084. // Events
  12085. /**
  12086. * An event triggered when this mesh collides with another one
  12087. * @type {BABYLON.Observable}
  12088. */
  12089. _this.onCollideObservable = new BABYLON.Observable();
  12090. /**
  12091. * An event triggered when the collision's position changes
  12092. * @type {BABYLON.Observable}
  12093. */
  12094. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12095. /**
  12096. * An event triggered after the world matrix is updated
  12097. * @type {BABYLON.Observable}
  12098. */
  12099. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12100. // Properties
  12101. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12102. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  12103. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  12104. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  12105. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12106. _this.visibility = 1.0;
  12107. _this.alphaIndex = Number.MAX_VALUE;
  12108. _this.infiniteDistance = false;
  12109. _this.isVisible = true;
  12110. _this.isPickable = true;
  12111. _this.showBoundingBox = false;
  12112. _this.showSubMeshesBoundingBox = false;
  12113. _this.isBlocker = false;
  12114. _this.renderingGroupId = 0;
  12115. _this._receiveShadows = false;
  12116. _this.renderOutline = false;
  12117. _this.outlineColor = BABYLON.Color3.Red();
  12118. _this.outlineWidth = 0.02;
  12119. _this.renderOverlay = false;
  12120. _this.overlayColor = BABYLON.Color3.Red();
  12121. _this.overlayAlpha = 0.5;
  12122. _this._hasVertexAlpha = false;
  12123. _this._useVertexColors = true;
  12124. _this._computeBonesUsingShaders = true;
  12125. _this._numBoneInfluencers = 4;
  12126. _this._applyFog = true;
  12127. _this.scalingDeterminant = 1;
  12128. _this.useOctreeForRenderingSelection = true;
  12129. _this.useOctreeForPicking = true;
  12130. _this.useOctreeForCollisions = true;
  12131. _this.layerMask = 0x0FFFFFFF;
  12132. /**
  12133. * True if the mesh must be rendered in any case.
  12134. */
  12135. _this.alwaysSelectAsActiveMesh = false;
  12136. // Collisions
  12137. _this._checkCollisions = false;
  12138. _this._collisionMask = -1;
  12139. _this._collisionGroup = -1;
  12140. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12141. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12142. _this._collider = new BABYLON.Collider();
  12143. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12144. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12145. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12146. // Edges
  12147. _this.edgesWidth = 1;
  12148. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12149. // Cache
  12150. _this._localWorld = BABYLON.Matrix.Zero();
  12151. _this._worldMatrix = BABYLON.Matrix.Zero();
  12152. _this._absolutePosition = BABYLON.Vector3.Zero();
  12153. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12154. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12155. _this._isDirty = false;
  12156. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12157. _this._isDisposed = false;
  12158. _this._renderId = 0;
  12159. _this._intersectionsInProgress = new Array();
  12160. _this._isWorldMatrixFrozen = false;
  12161. _this._unIndexed = false;
  12162. _this._lightSources = new Array();
  12163. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12164. if (collidedMesh === void 0) { collidedMesh = null; }
  12165. //TODO move this to the collision coordinator!
  12166. if (_this.getScene().workerCollisions)
  12167. newPosition.multiplyInPlace(_this._collider.radius);
  12168. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12169. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12170. _this.position.addInPlace(_this._diffPositionForCollisions);
  12171. }
  12172. if (collidedMesh) {
  12173. _this.onCollideObservable.notifyObservers(collidedMesh);
  12174. }
  12175. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12176. };
  12177. _this.getScene().addMesh(_this);
  12178. _this._resyncLightSources();
  12179. return _this;
  12180. }
  12181. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12182. get: function () {
  12183. return AbstractMesh._BILLBOARDMODE_NONE;
  12184. },
  12185. enumerable: true,
  12186. configurable: true
  12187. });
  12188. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12189. get: function () {
  12190. return AbstractMesh._BILLBOARDMODE_X;
  12191. },
  12192. enumerable: true,
  12193. configurable: true
  12194. });
  12195. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12196. get: function () {
  12197. return AbstractMesh._BILLBOARDMODE_Y;
  12198. },
  12199. enumerable: true,
  12200. configurable: true
  12201. });
  12202. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12203. get: function () {
  12204. return AbstractMesh._BILLBOARDMODE_Z;
  12205. },
  12206. enumerable: true,
  12207. configurable: true
  12208. });
  12209. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12210. get: function () {
  12211. return AbstractMesh._BILLBOARDMODE_ALL;
  12212. },
  12213. enumerable: true,
  12214. configurable: true
  12215. });
  12216. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12217. /**
  12218. * Read-only : the number of facets in the mesh
  12219. */
  12220. get: function () {
  12221. return this._facetNb;
  12222. },
  12223. enumerable: true,
  12224. configurable: true
  12225. });
  12226. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12227. /**
  12228. * The number (integer) of subdivisions per axis in the partioning space
  12229. */
  12230. get: function () {
  12231. return this._partitioningSubdivisions;
  12232. },
  12233. set: function (nb) {
  12234. this._partitioningSubdivisions = nb;
  12235. },
  12236. enumerable: true,
  12237. configurable: true
  12238. });
  12239. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12240. /**
  12241. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12242. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12243. */
  12244. get: function () {
  12245. return this._partitioningBBoxRatio;
  12246. },
  12247. set: function (ratio) {
  12248. this._partitioningBBoxRatio = ratio;
  12249. },
  12250. enumerable: true,
  12251. configurable: true
  12252. });
  12253. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12254. /**
  12255. * Read-only boolean : is the feature facetData enabled ?
  12256. */
  12257. get: function () {
  12258. return this._facetDataEnabled;
  12259. },
  12260. enumerable: true,
  12261. configurable: true
  12262. });
  12263. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12264. set: function (callback) {
  12265. if (this._onCollideObserver) {
  12266. this.onCollideObservable.remove(this._onCollideObserver);
  12267. }
  12268. this._onCollideObserver = this.onCollideObservable.add(callback);
  12269. },
  12270. enumerable: true,
  12271. configurable: true
  12272. });
  12273. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12274. set: function (callback) {
  12275. if (this._onCollisionPositionChangeObserver) {
  12276. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12277. }
  12278. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12279. },
  12280. enumerable: true,
  12281. configurable: true
  12282. });
  12283. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12284. get: function () {
  12285. return this._receiveShadows;
  12286. },
  12287. set: function (value) {
  12288. if (this._receiveShadows === value) {
  12289. return;
  12290. }
  12291. this._receiveShadows = value;
  12292. this._markSubMeshesAsLightDirty();
  12293. },
  12294. enumerable: true,
  12295. configurable: true
  12296. });
  12297. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12298. get: function () {
  12299. return this._hasVertexAlpha;
  12300. },
  12301. set: function (value) {
  12302. if (this._hasVertexAlpha === value) {
  12303. return;
  12304. }
  12305. this._hasVertexAlpha = value;
  12306. this._markSubMeshesAsAttributesDirty();
  12307. },
  12308. enumerable: true,
  12309. configurable: true
  12310. });
  12311. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12312. get: function () {
  12313. return this._useVertexColors;
  12314. },
  12315. set: function (value) {
  12316. if (this._useVertexColors === value) {
  12317. return;
  12318. }
  12319. this._useVertexColors = value;
  12320. this._markSubMeshesAsAttributesDirty();
  12321. },
  12322. enumerable: true,
  12323. configurable: true
  12324. });
  12325. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12326. get: function () {
  12327. return this._computeBonesUsingShaders;
  12328. },
  12329. set: function (value) {
  12330. if (this._computeBonesUsingShaders === value) {
  12331. return;
  12332. }
  12333. this._computeBonesUsingShaders = value;
  12334. this._markSubMeshesAsAttributesDirty();
  12335. },
  12336. enumerable: true,
  12337. configurable: true
  12338. });
  12339. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12340. get: function () {
  12341. return this._numBoneInfluencers;
  12342. },
  12343. set: function (value) {
  12344. if (this._numBoneInfluencers === value) {
  12345. return;
  12346. }
  12347. this._numBoneInfluencers = value;
  12348. this._markSubMeshesAsAttributesDirty();
  12349. },
  12350. enumerable: true,
  12351. configurable: true
  12352. });
  12353. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12354. get: function () {
  12355. return this._applyFog;
  12356. },
  12357. set: function (value) {
  12358. if (this._applyFog === value) {
  12359. return;
  12360. }
  12361. this._applyFog = value;
  12362. this._markSubMeshesAsMiscDirty();
  12363. },
  12364. enumerable: true,
  12365. configurable: true
  12366. });
  12367. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12368. get: function () {
  12369. return this._collisionMask;
  12370. },
  12371. set: function (mask) {
  12372. this._collisionMask = !isNaN(mask) ? mask : -1;
  12373. },
  12374. enumerable: true,
  12375. configurable: true
  12376. });
  12377. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12378. get: function () {
  12379. return this._collisionGroup;
  12380. },
  12381. set: function (mask) {
  12382. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12383. },
  12384. enumerable: true,
  12385. configurable: true
  12386. });
  12387. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12388. get: function () {
  12389. return this._skeleton;
  12390. },
  12391. set: function (value) {
  12392. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12393. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12394. }
  12395. if (value && value.needInitialSkinMatrix) {
  12396. value._registerMeshWithPoseMatrix(this);
  12397. }
  12398. this._skeleton = value;
  12399. if (!this._skeleton) {
  12400. this._bonesTransformMatrices = null;
  12401. }
  12402. this._markSubMeshesAsAttributesDirty();
  12403. },
  12404. enumerable: true,
  12405. configurable: true
  12406. });
  12407. /**
  12408. * Returns the string "AbstractMesh"
  12409. */
  12410. AbstractMesh.prototype.getClassName = function () {
  12411. return "AbstractMesh";
  12412. };
  12413. /**
  12414. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12415. */
  12416. AbstractMesh.prototype.toString = function (fullDetails) {
  12417. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12418. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12419. if (this._skeleton) {
  12420. ret += ", skeleton: " + this._skeleton.name;
  12421. }
  12422. if (fullDetails) {
  12423. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12424. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12425. }
  12426. return ret;
  12427. };
  12428. AbstractMesh.prototype._resyncLightSources = function () {
  12429. this._lightSources.length = 0;
  12430. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12431. var light = _a[_i];
  12432. if (!light.isEnabled()) {
  12433. continue;
  12434. }
  12435. if (light.canAffectMesh(this)) {
  12436. this._lightSources.push(light);
  12437. }
  12438. }
  12439. this._markSubMeshesAsLightDirty();
  12440. };
  12441. AbstractMesh.prototype._resyncLighSource = function (light) {
  12442. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12443. var index = this._lightSources.indexOf(light);
  12444. if (index === -1) {
  12445. if (!isIn) {
  12446. return;
  12447. }
  12448. this._lightSources.push(light);
  12449. }
  12450. else {
  12451. if (isIn) {
  12452. return;
  12453. }
  12454. this._lightSources.splice(index, 1);
  12455. }
  12456. this._markSubMeshesAsLightDirty();
  12457. };
  12458. AbstractMesh.prototype._removeLightSource = function (light) {
  12459. var index = this._lightSources.indexOf(light);
  12460. if (index === -1) {
  12461. return;
  12462. }
  12463. this._lightSources.slice(index, 1);
  12464. };
  12465. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12466. if (!this.subMeshes) {
  12467. return;
  12468. }
  12469. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12470. var subMesh = _a[_i];
  12471. if (subMesh._materialDefines) {
  12472. func(subMesh._materialDefines);
  12473. }
  12474. }
  12475. };
  12476. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12477. this._markSubMeshesAsDirty(function (defines) { return defines._areLightsDirty = true; });
  12478. };
  12479. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12480. this._markSubMeshesAsDirty(function (defines) { return defines._areAttributesDirty = true; });
  12481. };
  12482. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12483. if (!this.subMeshes) {
  12484. return;
  12485. }
  12486. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12487. var subMesh = _a[_i];
  12488. var material = subMesh.getMaterial();
  12489. if (material) {
  12490. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12491. }
  12492. }
  12493. };
  12494. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12495. /**
  12496. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12497. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12498. * Default : (0.0, 0.0, 0.0)
  12499. */
  12500. get: function () {
  12501. return this._rotation;
  12502. },
  12503. set: function (newRotation) {
  12504. this._rotation = newRotation;
  12505. },
  12506. enumerable: true,
  12507. configurable: true
  12508. });
  12509. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12510. /**
  12511. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12512. * Default : (1.0, 1.0, 1.0)
  12513. */
  12514. get: function () {
  12515. return this._scaling;
  12516. },
  12517. set: function (newScaling) {
  12518. this._scaling = newScaling;
  12519. if (this.physicsImpostor) {
  12520. this.physicsImpostor.forceUpdate();
  12521. }
  12522. },
  12523. enumerable: true,
  12524. configurable: true
  12525. });
  12526. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12527. /**
  12528. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12529. * It's null by default.
  12530. * 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)
  12531. */
  12532. get: function () {
  12533. return this._rotationQuaternion;
  12534. },
  12535. set: function (quaternion) {
  12536. this._rotationQuaternion = quaternion;
  12537. //reset the rotation vector.
  12538. if (quaternion && this.rotation.length()) {
  12539. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12540. }
  12541. },
  12542. enumerable: true,
  12543. configurable: true
  12544. });
  12545. // Methods
  12546. /**
  12547. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12548. * Returns the AbstractMesh.
  12549. */
  12550. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12551. this._poseMatrix.copyFrom(matrix);
  12552. return this;
  12553. };
  12554. /**
  12555. * Returns the mesh Pose matrix.
  12556. * Returned object : Matrix
  12557. */
  12558. AbstractMesh.prototype.getPoseMatrix = function () {
  12559. return this._poseMatrix;
  12560. };
  12561. /**
  12562. * Disables the mesh edger rendering mode.
  12563. * Returns the AbstractMesh.
  12564. */
  12565. AbstractMesh.prototype.disableEdgesRendering = function () {
  12566. if (this._edgesRenderer !== undefined) {
  12567. this._edgesRenderer.dispose();
  12568. this._edgesRenderer = undefined;
  12569. }
  12570. return this;
  12571. };
  12572. /**
  12573. * Enables the edge rendering mode on the mesh.
  12574. * This mode makes the mesh edges visible.
  12575. * Returns the AbstractMesh.
  12576. */
  12577. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12578. if (epsilon === void 0) { epsilon = 0.95; }
  12579. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12580. this.disableEdgesRendering();
  12581. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12582. return this;
  12583. };
  12584. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12585. /**
  12586. * Returns true if the mesh is blocked. Used by the class Mesh.
  12587. * Returns the boolean `false` by default.
  12588. */
  12589. get: function () {
  12590. return false;
  12591. },
  12592. enumerable: true,
  12593. configurable: true
  12594. });
  12595. /**
  12596. * Returns the mesh itself by default, used by the class Mesh.
  12597. * Returned type : AbstractMesh
  12598. */
  12599. AbstractMesh.prototype.getLOD = function (camera) {
  12600. return this;
  12601. };
  12602. /**
  12603. * Returns 0 by default, used by the class Mesh.
  12604. * Returns an integer.
  12605. */
  12606. AbstractMesh.prototype.getTotalVertices = function () {
  12607. return 0;
  12608. };
  12609. /**
  12610. * Returns null by default, used by the class Mesh.
  12611. * Returned type : integer array
  12612. */
  12613. AbstractMesh.prototype.getIndices = function () {
  12614. return null;
  12615. };
  12616. /**
  12617. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12618. * Returned type : float array or Float32Array
  12619. */
  12620. AbstractMesh.prototype.getVerticesData = function (kind) {
  12621. return null;
  12622. };
  12623. /** Returns false by default, used by the class Mesh.
  12624. * Returns a boolean
  12625. */
  12626. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12627. return false;
  12628. };
  12629. /**
  12630. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12631. * Returns a BoundingInfo
  12632. */
  12633. AbstractMesh.prototype.getBoundingInfo = function () {
  12634. if (this._masterMesh) {
  12635. return this._masterMesh.getBoundingInfo();
  12636. }
  12637. if (!this._boundingInfo) {
  12638. this._updateBoundingInfo();
  12639. }
  12640. return this._boundingInfo;
  12641. };
  12642. /**
  12643. * Sets a mesh new object BoundingInfo.
  12644. * Returns the AbstractMesh.
  12645. */
  12646. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12647. this._boundingInfo = boundingInfo;
  12648. return this;
  12649. };
  12650. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12651. get: function () {
  12652. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12653. },
  12654. enumerable: true,
  12655. configurable: true
  12656. });
  12657. AbstractMesh.prototype._preActivate = function () {
  12658. };
  12659. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12660. };
  12661. AbstractMesh.prototype._activate = function (renderId) {
  12662. this._renderId = renderId;
  12663. };
  12664. /**
  12665. * Returns the last update of the World matrix
  12666. * Returns a Matrix.
  12667. */
  12668. AbstractMesh.prototype.getWorldMatrix = function () {
  12669. if (this._masterMesh) {
  12670. return this._masterMesh.getWorldMatrix();
  12671. }
  12672. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12673. this.computeWorldMatrix();
  12674. }
  12675. return this._worldMatrix;
  12676. };
  12677. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12678. /**
  12679. * Returns directly the last state of the mesh World matrix.
  12680. * A Matrix is returned.
  12681. */
  12682. get: function () {
  12683. return this._worldMatrix;
  12684. },
  12685. enumerable: true,
  12686. configurable: true
  12687. });
  12688. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12689. /**
  12690. * Returns the current mesh absolute position.
  12691. * Retuns a Vector3.
  12692. */
  12693. get: function () {
  12694. return this._absolutePosition;
  12695. },
  12696. enumerable: true,
  12697. configurable: true
  12698. });
  12699. /**
  12700. * Prevents the World matrix to be computed any longer.
  12701. * Returns the AbstractMesh.
  12702. */
  12703. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12704. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12705. this.computeWorldMatrix(true);
  12706. this._isWorldMatrixFrozen = true;
  12707. return this;
  12708. };
  12709. /**
  12710. * Allows back the World matrix computation.
  12711. * Returns the AbstractMesh.
  12712. */
  12713. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12714. this._isWorldMatrixFrozen = false;
  12715. this.computeWorldMatrix(true);
  12716. return this;
  12717. };
  12718. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12719. /**
  12720. * True if the World matrix has been frozen.
  12721. * Returns a boolean.
  12722. */
  12723. get: function () {
  12724. return this._isWorldMatrixFrozen;
  12725. },
  12726. enumerable: true,
  12727. configurable: true
  12728. });
  12729. /**
  12730. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12731. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12732. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12733. * The passed axis is also normalized.
  12734. * Returns the AbstractMesh.
  12735. */
  12736. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12737. axis.normalize();
  12738. if (!this.rotationQuaternion) {
  12739. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12740. this.rotation = BABYLON.Vector3.Zero();
  12741. }
  12742. var rotationQuaternion;
  12743. if (!space || space === BABYLON.Space.LOCAL) {
  12744. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12745. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12746. }
  12747. else {
  12748. if (this.parent) {
  12749. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12750. invertParentWorldMatrix.invert();
  12751. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12752. }
  12753. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12754. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12755. }
  12756. return this;
  12757. };
  12758. /**
  12759. * Translates the mesh along the axis vector for the passed distance in the given space.
  12760. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12761. * Returns the AbstractMesh.
  12762. */
  12763. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12764. var displacementVector = axis.scale(distance);
  12765. if (!space || space === BABYLON.Space.LOCAL) {
  12766. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12767. this.setPositionWithLocalVector(tempV3);
  12768. }
  12769. else {
  12770. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12771. }
  12772. return this;
  12773. };
  12774. /**
  12775. * Adds a rotation step to the mesh current rotation.
  12776. * x, y, z are Euler angles expressed in radians.
  12777. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12778. * This means this rotation is made in the mesh local space only.
  12779. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12780. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12781. * ```javascript
  12782. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12783. * ```
  12784. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12785. * 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.
  12786. * Returns the AbstractMesh.
  12787. */
  12788. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12789. var rotationQuaternion;
  12790. if (this.rotationQuaternion) {
  12791. rotationQuaternion = this.rotationQuaternion;
  12792. }
  12793. else {
  12794. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12795. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12796. }
  12797. var accumulation = BABYLON.Tmp.Quaternion[0];
  12798. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12799. rotationQuaternion.multiplyInPlace(accumulation);
  12800. if (!this.rotationQuaternion) {
  12801. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12802. }
  12803. return this;
  12804. };
  12805. /**
  12806. * Retuns the mesh absolute position in the World.
  12807. * Returns a Vector3.
  12808. */
  12809. AbstractMesh.prototype.getAbsolutePosition = function () {
  12810. this.computeWorldMatrix();
  12811. return this._absolutePosition;
  12812. };
  12813. /**
  12814. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12815. * Returns the AbstractMesh.
  12816. */
  12817. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12818. if (!absolutePosition) {
  12819. return;
  12820. }
  12821. var absolutePositionX;
  12822. var absolutePositionY;
  12823. var absolutePositionZ;
  12824. if (absolutePosition.x === undefined) {
  12825. if (arguments.length < 3) {
  12826. return;
  12827. }
  12828. absolutePositionX = arguments[0];
  12829. absolutePositionY = arguments[1];
  12830. absolutePositionZ = arguments[2];
  12831. }
  12832. else {
  12833. absolutePositionX = absolutePosition.x;
  12834. absolutePositionY = absolutePosition.y;
  12835. absolutePositionZ = absolutePosition.z;
  12836. }
  12837. if (this.parent) {
  12838. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12839. invertParentWorldMatrix.invert();
  12840. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12841. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12842. }
  12843. else {
  12844. this.position.x = absolutePositionX;
  12845. this.position.y = absolutePositionY;
  12846. this.position.z = absolutePositionZ;
  12847. }
  12848. return this;
  12849. };
  12850. // ================================== Point of View Movement =================================
  12851. /**
  12852. * Perform relative position change from the point of view of behind the front of the mesh.
  12853. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12854. * Supports definition of mesh facing forward or backward.
  12855. * @param {number} amountRight
  12856. * @param {number} amountUp
  12857. * @param {number} amountForward
  12858. *
  12859. * Returns the AbstractMesh.
  12860. */
  12861. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12862. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12863. return this;
  12864. };
  12865. /**
  12866. * Calculate relative position change from the point of view of behind the front of the mesh.
  12867. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12868. * Supports definition of mesh facing forward or backward.
  12869. * @param {number} amountRight
  12870. * @param {number} amountUp
  12871. * @param {number} amountForward
  12872. *
  12873. * Returns a new Vector3.
  12874. */
  12875. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12876. var rotMatrix = new BABYLON.Matrix();
  12877. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12878. rotQuaternion.toRotationMatrix(rotMatrix);
  12879. var translationDelta = BABYLON.Vector3.Zero();
  12880. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12881. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12882. return translationDelta;
  12883. };
  12884. // ================================== Point of View Rotation =================================
  12885. /**
  12886. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12887. * Supports definition of mesh facing forward or backward.
  12888. * @param {number} flipBack
  12889. * @param {number} twirlClockwise
  12890. * @param {number} tiltRight
  12891. *
  12892. * Returns the AbstractMesh.
  12893. */
  12894. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12895. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12896. return this;
  12897. };
  12898. /**
  12899. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12900. * Supports definition of mesh facing forward or backward.
  12901. * @param {number} flipBack
  12902. * @param {number} twirlClockwise
  12903. * @param {number} tiltRight
  12904. *
  12905. * Returns a new Vector3.
  12906. */
  12907. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12908. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12909. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12910. };
  12911. /**
  12912. * Sets a new pivot matrix to the mesh.
  12913. * Returns the AbstractMesh.
  12914. */
  12915. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12916. this._pivotMatrix = matrix;
  12917. this._cache.pivotMatrixUpdated = true;
  12918. return this;
  12919. };
  12920. /**
  12921. * Returns the mesh pivot matrix.
  12922. * Default : Identity.
  12923. * A Matrix is returned.
  12924. */
  12925. AbstractMesh.prototype.getPivotMatrix = function () {
  12926. return this._pivotMatrix;
  12927. };
  12928. AbstractMesh.prototype._isSynchronized = function () {
  12929. if (this._isDirty) {
  12930. return false;
  12931. }
  12932. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12933. return false;
  12934. if (this._cache.pivotMatrixUpdated) {
  12935. return false;
  12936. }
  12937. if (this.infiniteDistance) {
  12938. return false;
  12939. }
  12940. if (!this._cache.position.equals(this.position))
  12941. return false;
  12942. if (this.rotationQuaternion) {
  12943. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12944. return false;
  12945. }
  12946. if (!this._cache.rotation.equals(this.rotation))
  12947. return false;
  12948. if (!this._cache.scaling.equals(this.scaling))
  12949. return false;
  12950. return true;
  12951. };
  12952. AbstractMesh.prototype._initCache = function () {
  12953. _super.prototype._initCache.call(this);
  12954. this._cache.localMatrixUpdated = false;
  12955. this._cache.position = BABYLON.Vector3.Zero();
  12956. this._cache.scaling = BABYLON.Vector3.Zero();
  12957. this._cache.rotation = BABYLON.Vector3.Zero();
  12958. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12959. this._cache.billboardMode = -1;
  12960. };
  12961. AbstractMesh.prototype.markAsDirty = function (property) {
  12962. if (property === "rotation") {
  12963. this.rotationQuaternion = null;
  12964. }
  12965. this._currentRenderId = Number.MAX_VALUE;
  12966. this._isDirty = true;
  12967. return this;
  12968. };
  12969. /**
  12970. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12971. * Returns the AbstractMesh.
  12972. */
  12973. AbstractMesh.prototype._updateBoundingInfo = function () {
  12974. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12975. this._boundingInfo.update(this.worldMatrixFromCache);
  12976. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12977. return this;
  12978. };
  12979. /**
  12980. * Update a mesh's children BoundingInfo objects only.
  12981. * Returns the AbstractMesh.
  12982. */
  12983. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12984. if (!this.subMeshes) {
  12985. return;
  12986. }
  12987. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12988. var subMesh = this.subMeshes[subIndex];
  12989. if (!subMesh.IsGlobal) {
  12990. subMesh.updateBoundingInfo(matrix);
  12991. }
  12992. }
  12993. return this;
  12994. };
  12995. /**
  12996. * Computes the mesh World matrix and returns it.
  12997. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12998. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12999. * If the parameter `force`is set to `true`, the actual computation is done.
  13000. * Returns the mesh World Matrix.
  13001. */
  13002. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13003. if (this._isWorldMatrixFrozen) {
  13004. return this._worldMatrix;
  13005. }
  13006. if (!force && ((this._currentRenderId === this.getScene().getRenderId() && this.isSynchronized(true)))) {
  13007. this._currentRenderId = this.getScene().getRenderId();
  13008. return this._worldMatrix;
  13009. }
  13010. this._cache.position.copyFrom(this.position);
  13011. this._cache.scaling.copyFrom(this.scaling);
  13012. this._cache.pivotMatrixUpdated = false;
  13013. this._cache.billboardMode = this.billboardMode;
  13014. this._currentRenderId = this.getScene().getRenderId();
  13015. this._isDirty = false;
  13016. // Scaling
  13017. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13018. // Rotation
  13019. //rotate, if quaternion is set and rotation was used
  13020. if (this.rotationQuaternion) {
  13021. var len = this.rotation.length();
  13022. if (len) {
  13023. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13024. this.rotation.copyFromFloats(0, 0, 0);
  13025. }
  13026. }
  13027. if (this.rotationQuaternion) {
  13028. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13029. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13030. }
  13031. else {
  13032. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13033. this._cache.rotation.copyFrom(this.rotation);
  13034. }
  13035. // Translation
  13036. if (this.infiniteDistance && !this.parent) {
  13037. var camera = this.getScene().activeCamera;
  13038. if (camera) {
  13039. var cameraWorldMatrix = camera.getWorldMatrix();
  13040. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13041. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13042. }
  13043. }
  13044. else {
  13045. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13046. }
  13047. // Composing transformations
  13048. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13049. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13050. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13051. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13052. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13053. // Need to decompose each rotation here
  13054. var currentPosition = BABYLON.Tmp.Vector3[3];
  13055. if (this.parent && this.parent.getWorldMatrix) {
  13056. if (this._meshToBoneReferal) {
  13057. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13058. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13059. }
  13060. else {
  13061. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13062. }
  13063. }
  13064. else {
  13065. currentPosition.copyFrom(this.position);
  13066. }
  13067. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13068. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13069. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13070. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13071. }
  13072. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13073. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13074. }
  13075. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13076. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13077. }
  13078. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13079. }
  13080. else {
  13081. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13082. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13083. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13084. }
  13085. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13086. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13087. }
  13088. // Local world
  13089. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13090. // Parent
  13091. if (this.parent && this.parent.getWorldMatrix) {
  13092. this._markSyncedWithParent();
  13093. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13094. if (this._meshToBoneReferal) {
  13095. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13096. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13097. }
  13098. else {
  13099. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13100. }
  13101. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13102. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13103. this._worldMatrix.copyFrom(this._localWorld);
  13104. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13105. }
  13106. else {
  13107. if (this._meshToBoneReferal) {
  13108. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13109. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13110. }
  13111. else {
  13112. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13113. }
  13114. }
  13115. }
  13116. else {
  13117. this._worldMatrix.copyFrom(this._localWorld);
  13118. }
  13119. // Bounding info
  13120. this._updateBoundingInfo();
  13121. // Absolute position
  13122. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13123. // Callbacks
  13124. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13125. if (!this._poseMatrix) {
  13126. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13127. }
  13128. return this._worldMatrix;
  13129. };
  13130. /**
  13131. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13132. * @param func: callback function to add
  13133. *
  13134. * Returns the AbstractMesh.
  13135. */
  13136. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13137. this.onAfterWorldMatrixUpdateObservable.add(func);
  13138. return this;
  13139. };
  13140. /**
  13141. * Removes a registered callback function.
  13142. * Returns the AbstractMesh.
  13143. */
  13144. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13145. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13146. return this;
  13147. };
  13148. /**
  13149. * Sets the mesh position in its local space.
  13150. * Returns the AbstractMesh.
  13151. */
  13152. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13153. this.computeWorldMatrix();
  13154. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13155. return this;
  13156. };
  13157. /**
  13158. * Returns the mesh position in the local space from the current World matrix values.
  13159. * Returns a new Vector3.
  13160. */
  13161. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13162. this.computeWorldMatrix();
  13163. var invLocalWorldMatrix = this._localWorld.clone();
  13164. invLocalWorldMatrix.invert();
  13165. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13166. };
  13167. /**
  13168. * Translates the mesh along the passed Vector3 in its local space.
  13169. * Returns the AbstractMesh.
  13170. */
  13171. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13172. this.computeWorldMatrix(true);
  13173. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13174. return this;
  13175. };
  13176. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13177. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13178. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13179. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13180. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13181. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13182. /// <returns>Mesh oriented towards targetMesh</returns>
  13183. if (yawCor === void 0) { yawCor = 0; }
  13184. if (pitchCor === void 0) { pitchCor = 0; }
  13185. if (rollCor === void 0) { rollCor = 0; }
  13186. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13187. var dv = AbstractMesh._lookAtVectorCache;
  13188. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13189. targetPoint.subtractToRef(pos, dv);
  13190. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13191. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13192. var pitch = Math.atan2(dv.y, len);
  13193. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13194. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13195. return this;
  13196. };
  13197. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13198. this._meshToBoneReferal = affectedMesh;
  13199. this.parent = bone;
  13200. if (bone.getWorldMatrix().determinant() < 0) {
  13201. this.scalingDeterminant *= -1;
  13202. }
  13203. return this;
  13204. };
  13205. AbstractMesh.prototype.detachFromBone = function () {
  13206. if (this.parent.getWorldMatrix().determinant() < 0) {
  13207. this.scalingDeterminant *= -1;
  13208. }
  13209. this._meshToBoneReferal = null;
  13210. this.parent = null;
  13211. return this;
  13212. };
  13213. /**
  13214. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13215. * A mesh is in the frustum if its bounding box intersects the frustum.
  13216. * Boolean returned.
  13217. */
  13218. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13219. return this._boundingInfo.isInFrustum(frustumPlanes);
  13220. };
  13221. /**
  13222. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13223. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13224. * Boolean returned.
  13225. */
  13226. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13227. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13228. ;
  13229. };
  13230. /**
  13231. * True if the mesh intersects another mesh or a SolidParticle object.
  13232. * 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)
  13233. * Returns a boolean.
  13234. */
  13235. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13236. if (!this._boundingInfo || !mesh._boundingInfo) {
  13237. return false;
  13238. }
  13239. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13240. };
  13241. /**
  13242. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13243. * Returns a boolean.
  13244. */
  13245. AbstractMesh.prototype.intersectsPoint = function (point) {
  13246. if (!this._boundingInfo) {
  13247. return false;
  13248. }
  13249. return this._boundingInfo.intersectsPoint(point);
  13250. };
  13251. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13252. return this.physicsImpostor;
  13253. };
  13254. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13255. if (!camera) {
  13256. camera = this.getScene().activeCamera;
  13257. }
  13258. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13259. };
  13260. /**
  13261. * Returns the distance from the mesh to the active camera.
  13262. * Returns a float.
  13263. */
  13264. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13265. if (!camera) {
  13266. camera = this.getScene().activeCamera;
  13267. }
  13268. return this.absolutePosition.subtract(camera.position).length();
  13269. };
  13270. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13271. if (!this.physicsImpostor) {
  13272. return;
  13273. }
  13274. this.physicsImpostor.applyImpulse(force, contactPoint);
  13275. return this;
  13276. };
  13277. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13278. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13279. return;
  13280. }
  13281. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13282. mainPivot: pivot1,
  13283. connectedPivot: pivot2,
  13284. nativeParams: options
  13285. });
  13286. return this;
  13287. };
  13288. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13289. // Collisions
  13290. /**
  13291. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13292. * Default `false`.
  13293. */
  13294. get: function () {
  13295. return this._checkCollisions;
  13296. },
  13297. set: function (collisionEnabled) {
  13298. this._checkCollisions = collisionEnabled;
  13299. if (this.getScene().workerCollisions) {
  13300. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13301. }
  13302. },
  13303. enumerable: true,
  13304. configurable: true
  13305. });
  13306. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  13307. var globalPosition = this.getAbsolutePosition();
  13308. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13309. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13310. this._collider.radius = this.ellipsoid;
  13311. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13312. return this;
  13313. };
  13314. // Submeshes octree
  13315. /**
  13316. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13317. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13318. * Returns an Octree of submeshes.
  13319. */
  13320. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13321. if (maxCapacity === void 0) { maxCapacity = 64; }
  13322. if (maxDepth === void 0) { maxDepth = 2; }
  13323. if (!this._submeshesOctree) {
  13324. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13325. }
  13326. this.computeWorldMatrix(true);
  13327. // Update octree
  13328. var bbox = this.getBoundingInfo().boundingBox;
  13329. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13330. return this._submeshesOctree;
  13331. };
  13332. // Collisions
  13333. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13334. this._generatePointsArray();
  13335. // Transformation
  13336. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13337. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13338. subMesh._lastColliderWorldVertices = [];
  13339. subMesh._trianglePlanes = [];
  13340. var start = subMesh.verticesStart;
  13341. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13342. for (var i = start; i < end; i++) {
  13343. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13344. }
  13345. }
  13346. // Collide
  13347. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13348. if (collider.collisionFound) {
  13349. collider.collidedMesh = this;
  13350. }
  13351. return this;
  13352. };
  13353. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13354. var subMeshes;
  13355. var len;
  13356. // Octrees
  13357. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13358. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13359. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13360. len = intersections.length;
  13361. subMeshes = intersections.data;
  13362. }
  13363. else {
  13364. subMeshes = this.subMeshes;
  13365. len = subMeshes.length;
  13366. }
  13367. for (var index = 0; index < len; index++) {
  13368. var subMesh = subMeshes[index];
  13369. // Bounding test
  13370. if (len > 1 && !subMesh._checkCollision(collider))
  13371. continue;
  13372. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13373. }
  13374. return this;
  13375. };
  13376. AbstractMesh.prototype._checkCollision = function (collider) {
  13377. // Bounding box test
  13378. if (!this._boundingInfo._checkCollision(collider))
  13379. return this;
  13380. // Transformation matrix
  13381. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13382. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13383. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13384. return this;
  13385. };
  13386. // Picking
  13387. AbstractMesh.prototype._generatePointsArray = function () {
  13388. return false;
  13389. };
  13390. /**
  13391. * Checks if the passed Ray intersects with the mesh.
  13392. * Returns an object PickingInfo.
  13393. */
  13394. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13395. var pickingInfo = new BABYLON.PickingInfo();
  13396. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13397. return pickingInfo;
  13398. }
  13399. if (!this._generatePointsArray()) {
  13400. return pickingInfo;
  13401. }
  13402. var intersectInfo = null;
  13403. // Octrees
  13404. var subMeshes;
  13405. var len;
  13406. if (this._submeshesOctree && this.useOctreeForPicking) {
  13407. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13408. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13409. len = intersections.length;
  13410. subMeshes = intersections.data;
  13411. }
  13412. else {
  13413. subMeshes = this.subMeshes;
  13414. len = subMeshes.length;
  13415. }
  13416. for (var index = 0; index < len; index++) {
  13417. var subMesh = subMeshes[index];
  13418. // Bounding test
  13419. if (len > 1 && !subMesh.canIntersects(ray))
  13420. continue;
  13421. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13422. if (currentIntersectInfo) {
  13423. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13424. intersectInfo = currentIntersectInfo;
  13425. intersectInfo.subMeshId = index;
  13426. if (fastCheck) {
  13427. break;
  13428. }
  13429. }
  13430. }
  13431. }
  13432. if (intersectInfo) {
  13433. // Get picked point
  13434. var world = this.getWorldMatrix();
  13435. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13436. var direction = ray.direction.clone();
  13437. direction = direction.scale(intersectInfo.distance);
  13438. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13439. var pickedPoint = worldOrigin.add(worldDirection);
  13440. // Return result
  13441. pickingInfo.hit = true;
  13442. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13443. pickingInfo.pickedPoint = pickedPoint;
  13444. pickingInfo.pickedMesh = this;
  13445. pickingInfo.bu = intersectInfo.bu;
  13446. pickingInfo.bv = intersectInfo.bv;
  13447. pickingInfo.faceId = intersectInfo.faceId;
  13448. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13449. return pickingInfo;
  13450. }
  13451. return pickingInfo;
  13452. };
  13453. /**
  13454. * Clones the mesh, used by the class Mesh.
  13455. * Just returns `null` for an AbstractMesh.
  13456. */
  13457. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13458. return null;
  13459. };
  13460. /**
  13461. * Disposes all the mesh submeshes.
  13462. * Returns the AbstractMesh.
  13463. */
  13464. AbstractMesh.prototype.releaseSubMeshes = function () {
  13465. if (this.subMeshes) {
  13466. while (this.subMeshes.length) {
  13467. this.subMeshes[0].dispose();
  13468. }
  13469. }
  13470. else {
  13471. this.subMeshes = new Array();
  13472. }
  13473. return this;
  13474. };
  13475. /**
  13476. * Disposes the AbstractMesh.
  13477. * Some internal references are kept for further use.
  13478. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13479. * Returns nothing.
  13480. */
  13481. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13482. var _this = this;
  13483. var index;
  13484. // Action manager
  13485. if (this.actionManager) {
  13486. this.actionManager.dispose();
  13487. this.actionManager = null;
  13488. }
  13489. // Skeleton
  13490. this.skeleton = null;
  13491. // Animations
  13492. this.getScene().stopAnimation(this);
  13493. // Physics
  13494. if (this.physicsImpostor) {
  13495. this.physicsImpostor.dispose();
  13496. }
  13497. // Intersections in progress
  13498. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13499. var other = this._intersectionsInProgress[index];
  13500. var pos = other._intersectionsInProgress.indexOf(this);
  13501. other._intersectionsInProgress.splice(pos, 1);
  13502. }
  13503. this._intersectionsInProgress = [];
  13504. // Lights
  13505. var lights = this.getScene().lights;
  13506. lights.forEach(function (light) {
  13507. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13508. if (meshIndex !== -1) {
  13509. light.includedOnlyMeshes.splice(meshIndex, 1);
  13510. }
  13511. meshIndex = light.excludedMeshes.indexOf(_this);
  13512. if (meshIndex !== -1) {
  13513. light.excludedMeshes.splice(meshIndex, 1);
  13514. }
  13515. // Shadow generators
  13516. var generator = light.getShadowGenerator();
  13517. if (generator) {
  13518. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  13519. if (meshIndex !== -1) {
  13520. generator.getShadowMap().renderList.splice(meshIndex, 1);
  13521. }
  13522. }
  13523. });
  13524. // Edges
  13525. if (this._edgesRenderer) {
  13526. this._edgesRenderer.dispose();
  13527. this._edgesRenderer = null;
  13528. }
  13529. // SubMeshes
  13530. if (this.getClassName() !== "InstancedMesh") {
  13531. this.releaseSubMeshes();
  13532. }
  13533. // Engine
  13534. this.getScene().getEngine().wipeCaches();
  13535. // Remove from scene
  13536. this.getScene().removeMesh(this);
  13537. if (!doNotRecurse) {
  13538. // Particles
  13539. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13540. if (this.getScene().particleSystems[index].emitter === this) {
  13541. this.getScene().particleSystems[index].dispose();
  13542. index--;
  13543. }
  13544. }
  13545. // Children
  13546. var objects = this.getDescendants(true);
  13547. for (index = 0; index < objects.length; index++) {
  13548. objects[index].dispose();
  13549. }
  13550. }
  13551. else {
  13552. var childMeshes = this.getChildMeshes(true);
  13553. for (index = 0; index < childMeshes.length; index++) {
  13554. var child = childMeshes[index];
  13555. child.parent = null;
  13556. child.computeWorldMatrix(true);
  13557. }
  13558. }
  13559. // facet data
  13560. if (this._facetDataEnabled) {
  13561. this.disableFacetData();
  13562. }
  13563. this.onAfterWorldMatrixUpdateObservable.clear();
  13564. this.onCollideObservable.clear();
  13565. this.onCollisionPositionChangeObservable.clear();
  13566. this._isDisposed = true;
  13567. _super.prototype.dispose.call(this);
  13568. };
  13569. /**
  13570. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13571. * This Vector3 is expressed in the World space.
  13572. */
  13573. AbstractMesh.prototype.getDirection = function (localAxis) {
  13574. var result = BABYLON.Vector3.Zero();
  13575. this.getDirectionToRef(localAxis, result);
  13576. return result;
  13577. };
  13578. /**
  13579. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13580. * localAxis is expressed in the mesh local space.
  13581. * result is computed in the Wordl space from the mesh World matrix.
  13582. * Returns the AbstractMesh.
  13583. */
  13584. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13585. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13586. return this;
  13587. };
  13588. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13589. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13590. if (this.getScene().getRenderId() == 0) {
  13591. this.computeWorldMatrix(true);
  13592. }
  13593. var wm = this.getWorldMatrix();
  13594. if (space == BABYLON.Space.WORLD) {
  13595. var tmat = BABYLON.Tmp.Matrix[0];
  13596. wm.invertToRef(tmat);
  13597. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13598. }
  13599. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13600. this._pivotMatrix.m[12] = -point.x;
  13601. this._pivotMatrix.m[13] = -point.y;
  13602. this._pivotMatrix.m[14] = -point.z;
  13603. this._cache.pivotMatrixUpdated = true;
  13604. return this;
  13605. };
  13606. /**
  13607. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13608. */
  13609. AbstractMesh.prototype.getPivotPoint = function () {
  13610. var point = BABYLON.Vector3.Zero();
  13611. this.getPivotPointToRef(point);
  13612. return point;
  13613. };
  13614. /**
  13615. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13616. * Returns the AbstractMesh.
  13617. */
  13618. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13619. result.x = -this._pivotMatrix.m[12];
  13620. result.y = -this._pivotMatrix.m[13];
  13621. result.z = -this._pivotMatrix.m[14];
  13622. return this;
  13623. };
  13624. /**
  13625. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13626. */
  13627. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13628. var point = BABYLON.Vector3.Zero();
  13629. this.getAbsolutePivotPointToRef(point);
  13630. return point;
  13631. };
  13632. /**
  13633. * Defines the passed mesh as the parent of the current mesh.
  13634. * If keepWorldPositionRotation is set to `true` (default `false`), the current mesh position and rotation are kept.
  13635. * Returns the AbstractMesh.
  13636. */
  13637. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  13638. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13639. var child = this;
  13640. var parent = mesh;
  13641. if (mesh == null) {
  13642. if (child.parent && keepWorldPositionRotation) {
  13643. var rotation = BABYLON.Tmp.Quaternion[0];
  13644. var position = BABYLON.Tmp.Vector3[0];
  13645. var scale = BABYLON.Tmp.Vector3[1];
  13646. child.getWorldMatrix().decompose(scale, rotation, position);
  13647. if (child.rotationQuaternion) {
  13648. child.rotationQuaternion.copyFrom(rotation);
  13649. }
  13650. else {
  13651. rotation.toEulerAnglesToRef(child.rotation);
  13652. }
  13653. child.position.x = position.x;
  13654. child.position.y = position.y;
  13655. child.position.z = position.z;
  13656. }
  13657. }
  13658. else {
  13659. if (keepWorldPositionRotation) {
  13660. var rotation = BABYLON.Tmp.Quaternion[0];
  13661. var position = BABYLON.Tmp.Vector3[0];
  13662. var scale = BABYLON.Tmp.Vector3[1];
  13663. var m1 = BABYLON.Tmp.Matrix[0];
  13664. var m2 = BABYLON.Tmp.Matrix[1];
  13665. parent.getWorldMatrix().decompose(scale, rotation, position);
  13666. rotation.toRotationMatrix(m1);
  13667. m2.setTranslation(position);
  13668. m2.multiplyToRef(m1, m1);
  13669. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13670. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13671. m.decompose(scale, rotation, position);
  13672. if (child.rotationQuaternion) {
  13673. child.rotationQuaternion.copyFrom(rotation);
  13674. }
  13675. else {
  13676. rotation.toEulerAnglesToRef(child.rotation);
  13677. }
  13678. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13679. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13680. m.decompose(scale, rotation, position);
  13681. child.position.x = position.x;
  13682. child.position.y = position.y;
  13683. child.position.z = position.z;
  13684. }
  13685. }
  13686. child.parent = parent;
  13687. return this;
  13688. };
  13689. /**
  13690. * Adds the passed mesh as a child to the current mesh.
  13691. * If keepWorldPositionRotation is set to `true` (default `false`), the child world position and rotation are kept.
  13692. * Returns the AbstractMesh.
  13693. */
  13694. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  13695. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13696. mesh.setParent(this, keepWorldPositionRotation);
  13697. return this;
  13698. };
  13699. /**
  13700. * Removes the passed mesh from the current mesh children list.
  13701. * Returns the AbstractMesh.
  13702. */
  13703. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  13704. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13705. mesh.setParent(null, keepWorldPositionRotation);
  13706. return this;
  13707. };
  13708. /**
  13709. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13710. * Returns the AbstractMesh.
  13711. */
  13712. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13713. result.x = this._pivotMatrix.m[12];
  13714. result.y = this._pivotMatrix.m[13];
  13715. result.z = this._pivotMatrix.m[14];
  13716. this.getPivotPointToRef(result);
  13717. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13718. return this;
  13719. };
  13720. // Facet data
  13721. /**
  13722. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13723. * Returns the AbstractMesh.
  13724. */
  13725. AbstractMesh.prototype._initFacetData = function () {
  13726. if (!this._facetNormals) {
  13727. this._facetNormals = new Array();
  13728. }
  13729. if (!this._facetPositions) {
  13730. this._facetPositions = new Array();
  13731. }
  13732. if (!this._facetPartitioning) {
  13733. this._facetPartitioning = new Array();
  13734. }
  13735. this._facetNb = this.getIndices().length / 3;
  13736. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13737. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13738. for (var f = 0; f < this._facetNb; f++) {
  13739. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13740. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13741. }
  13742. this._facetDataEnabled = true;
  13743. return this;
  13744. };
  13745. /**
  13746. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13747. * This method can be called within the render loop.
  13748. * 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.
  13749. * Returns the AbstractMesh.
  13750. */
  13751. AbstractMesh.prototype.updateFacetData = function () {
  13752. if (!this._facetDataEnabled) {
  13753. this._initFacetData();
  13754. }
  13755. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13756. var indices = this.getIndices();
  13757. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13758. var bInfo = this.getBoundingInfo();
  13759. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13760. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13761. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13762. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13763. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13764. this._subDiv.max = this._partitioningSubdivisions;
  13765. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13766. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13767. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13768. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13769. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13770. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13771. // set the parameters for ComputeNormals()
  13772. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13773. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13774. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13775. this._facetParameters.bInfo = bInfo;
  13776. this._facetParameters.bbSize = this._bbSize;
  13777. this._facetParameters.subDiv = this._subDiv;
  13778. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13779. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13780. return this;
  13781. };
  13782. /**
  13783. * Returns the facetLocalNormals array.
  13784. * The normals are expressed in the mesh local space.
  13785. */
  13786. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13787. if (!this._facetNormals) {
  13788. this.updateFacetData();
  13789. }
  13790. return this._facetNormals;
  13791. };
  13792. /**
  13793. * Returns the facetLocalPositions array.
  13794. * The facet positions are expressed in the mesh local space.
  13795. */
  13796. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13797. if (!this._facetPositions) {
  13798. this.updateFacetData();
  13799. }
  13800. return this._facetPositions;
  13801. };
  13802. /**
  13803. * Returns the facetLocalPartioning array.
  13804. */
  13805. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13806. if (!this._facetPartitioning) {
  13807. this.updateFacetData();
  13808. }
  13809. return this._facetPartitioning;
  13810. };
  13811. /**
  13812. * Returns the i-th facet position in the world system.
  13813. * This method allocates a new Vector3 per call.
  13814. */
  13815. AbstractMesh.prototype.getFacetPosition = function (i) {
  13816. var pos = BABYLON.Vector3.Zero();
  13817. this.getFacetPositionToRef(i, pos);
  13818. return pos;
  13819. };
  13820. /**
  13821. * Sets the reference Vector3 with the i-th facet position in the world system.
  13822. * Returns the AbstractMesh.
  13823. */
  13824. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13825. var localPos = (this.getFacetLocalPositions())[i];
  13826. var world = this.getWorldMatrix();
  13827. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13828. return this;
  13829. };
  13830. /**
  13831. * Returns the i-th facet normal in the world system.
  13832. * This method allocates a new Vector3 per call.
  13833. */
  13834. AbstractMesh.prototype.getFacetNormal = function (i) {
  13835. var norm = BABYLON.Vector3.Zero();
  13836. this.getFacetNormalToRef(i, norm);
  13837. return norm;
  13838. };
  13839. /**
  13840. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13841. * Returns the AbstractMesh.
  13842. */
  13843. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13844. var localNorm = (this.getFacetLocalNormals())[i];
  13845. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13846. return this;
  13847. };
  13848. /**
  13849. * 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).
  13850. */
  13851. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13852. var bInfo = this.getBoundingInfo();
  13853. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13854. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13855. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13856. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13857. return null;
  13858. }
  13859. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13860. };
  13861. /**
  13862. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13863. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13864. * 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.
  13865. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13866. * 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.
  13867. */
  13868. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13869. if (checkFace === void 0) { checkFace = false; }
  13870. if (facing === void 0) { facing = true; }
  13871. var world = this.getWorldMatrix();
  13872. var invMat = BABYLON.Tmp.Matrix[5];
  13873. world.invertToRef(invMat);
  13874. var invVect = BABYLON.Tmp.Vector3[8];
  13875. var closest = null;
  13876. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13877. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13878. if (projected) {
  13879. // tranform the local computed projected vector to world coordinates
  13880. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13881. }
  13882. return closest;
  13883. };
  13884. /**
  13885. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13886. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13887. * 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.
  13888. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13889. * 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.
  13890. */
  13891. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13892. if (checkFace === void 0) { checkFace = false; }
  13893. if (facing === void 0) { facing = true; }
  13894. var closest = null;
  13895. var tmpx = 0.0;
  13896. var tmpy = 0.0;
  13897. var tmpz = 0.0;
  13898. var d = 0.0; // tmp dot facet normal * facet position
  13899. var t0 = 0.0;
  13900. var projx = 0.0;
  13901. var projy = 0.0;
  13902. var projz = 0.0;
  13903. // Get all the facets in the same partitioning block than (x, y, z)
  13904. var facetPositions = this.getFacetLocalPositions();
  13905. var facetNormals = this.getFacetLocalNormals();
  13906. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13907. if (!facetsInBlock) {
  13908. return null;
  13909. }
  13910. // Get the closest facet to (x, y, z)
  13911. var shortest = Number.MAX_VALUE; // init distance vars
  13912. var tmpDistance = shortest;
  13913. var fib; // current facet in the block
  13914. var norm; // current facet normal
  13915. var p0; // current facet barycenter position
  13916. // loop on all the facets in the current partitioning block
  13917. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13918. fib = facetsInBlock[idx];
  13919. norm = facetNormals[fib];
  13920. p0 = facetPositions[fib];
  13921. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13922. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13923. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13924. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13925. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13926. projx = x + norm.x * t0;
  13927. projy = y + norm.y * t0;
  13928. projz = z + norm.z * t0;
  13929. tmpx = projx - x;
  13930. tmpy = projy - y;
  13931. tmpz = projz - z;
  13932. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13933. if (tmpDistance < shortest) {
  13934. shortest = tmpDistance;
  13935. closest = fib;
  13936. if (projected) {
  13937. projected.x = projx;
  13938. projected.y = projy;
  13939. projected.z = projz;
  13940. }
  13941. }
  13942. }
  13943. }
  13944. return closest;
  13945. };
  13946. /**
  13947. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13948. */
  13949. AbstractMesh.prototype.getFacetDataParameters = function () {
  13950. return this._facetParameters;
  13951. };
  13952. /**
  13953. * Disables the feature FacetData and frees the related memory.
  13954. * Returns the AbstractMesh.
  13955. */
  13956. AbstractMesh.prototype.disableFacetData = function () {
  13957. if (this._facetDataEnabled) {
  13958. this._facetDataEnabled = false;
  13959. this._facetPositions = null;
  13960. this._facetNormals = null;
  13961. this._facetPartitioning = null;
  13962. this._facetParameters = null;
  13963. }
  13964. return this;
  13965. };
  13966. return AbstractMesh;
  13967. }(BABYLON.Node));
  13968. // Statics
  13969. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13970. AbstractMesh._BILLBOARDMODE_X = 1;
  13971. AbstractMesh._BILLBOARDMODE_Y = 2;
  13972. AbstractMesh._BILLBOARDMODE_Z = 4;
  13973. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13974. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13975. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13976. BABYLON.AbstractMesh = AbstractMesh;
  13977. })(BABYLON || (BABYLON = {}));
  13978. //# sourceMappingURL=babylon.abstractMesh.js.map
  13979. var BABYLON;
  13980. (function (BABYLON) {
  13981. var Light = (function (_super) {
  13982. __extends(Light, _super);
  13983. /**
  13984. * Creates a Light object in the scene.
  13985. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13986. */
  13987. function Light(name, scene) {
  13988. var _this = _super.call(this, name, scene) || this;
  13989. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13990. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13991. _this.intensity = 1.0;
  13992. _this.range = Number.MAX_VALUE;
  13993. _this._excludeWithLayerMask = 0;
  13994. _this._includeOnlyWithLayerMask = 0;
  13995. _this._lightmapMode = 0;
  13996. // PBR Properties.
  13997. _this.radius = 0.00001;
  13998. _this._excludedMeshesIds = new Array();
  13999. _this._includedOnlyMeshesIds = new Array();
  14000. _this.getScene().addLight(_this);
  14001. _this.includedOnlyMeshes = new Array();
  14002. _this.excludedMeshes = new Array();
  14003. _this._resyncMeshes();
  14004. return _this;
  14005. }
  14006. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14007. /**
  14008. * If every light affecting the material is in this lightmapMode,
  14009. * material.lightmapTexture adds or multiplies
  14010. * (depends on material.useLightmapAsShadowmap)
  14011. * after every other light calculations.
  14012. */
  14013. get: function () {
  14014. return Light._LIGHTMAP_DEFAULT;
  14015. },
  14016. enumerable: true,
  14017. configurable: true
  14018. });
  14019. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14020. /**
  14021. * material.lightmapTexture as only diffuse lighting from this light
  14022. * adds pnly specular lighting from this light
  14023. * adds dynamic shadows
  14024. */
  14025. get: function () {
  14026. return Light._LIGHTMAP_SPECULAR;
  14027. },
  14028. enumerable: true,
  14029. configurable: true
  14030. });
  14031. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14032. /**
  14033. * material.lightmapTexture as only lighting
  14034. * no light calculation from this light
  14035. * only adds dynamic shadows from this light
  14036. */
  14037. get: function () {
  14038. return Light._LIGHTMAP_SHADOWSONLY;
  14039. },
  14040. enumerable: true,
  14041. configurable: true
  14042. });
  14043. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14044. get: function () {
  14045. return this._includedOnlyMeshes;
  14046. },
  14047. set: function (value) {
  14048. this._includedOnlyMeshes = value;
  14049. this._hookArray(value);
  14050. },
  14051. enumerable: true,
  14052. configurable: true
  14053. });
  14054. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14055. get: function () {
  14056. return this._excludedMeshes;
  14057. },
  14058. set: function (value) {
  14059. this._excludedMeshes = value;
  14060. this._hookArray(value);
  14061. },
  14062. enumerable: true,
  14063. configurable: true
  14064. });
  14065. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14066. get: function () {
  14067. return this._excludeWithLayerMask;
  14068. },
  14069. set: function (value) {
  14070. this._excludeWithLayerMask = value;
  14071. this._resyncMeshes();
  14072. },
  14073. enumerable: true,
  14074. configurable: true
  14075. });
  14076. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14077. get: function () {
  14078. return this._includeOnlyWithLayerMask;
  14079. },
  14080. set: function (value) {
  14081. this._includeOnlyWithLayerMask = value;
  14082. this._resyncMeshes();
  14083. },
  14084. enumerable: true,
  14085. configurable: true
  14086. });
  14087. Object.defineProperty(Light.prototype, "lightmapMode", {
  14088. get: function () {
  14089. return this._lightmapMode;
  14090. },
  14091. set: function (value) {
  14092. if (this._lightmapMode === value) {
  14093. return;
  14094. }
  14095. this._lightmapMode = value;
  14096. this._markMeshesAsLightDirty();
  14097. },
  14098. enumerable: true,
  14099. configurable: true
  14100. });
  14101. /**
  14102. * Returns the string "Light".
  14103. */
  14104. Light.prototype.getClassName = function () {
  14105. return "Light";
  14106. };
  14107. /**
  14108. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14109. */
  14110. Light.prototype.toString = function (fullDetails) {
  14111. var ret = "Name: " + this.name;
  14112. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14113. if (this.animations) {
  14114. for (var i = 0; i < this.animations.length; i++) {
  14115. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14116. }
  14117. }
  14118. if (fullDetails) {
  14119. }
  14120. return ret;
  14121. };
  14122. /**
  14123. * Set the enabled state of this node.
  14124. * @param {boolean} value - the new enabled state
  14125. * @see isEnabled
  14126. */
  14127. Light.prototype.setEnabled = function (value) {
  14128. _super.prototype.setEnabled.call(this, value);
  14129. this._resyncMeshes();
  14130. };
  14131. /**
  14132. * Returns the Light associated shadow generator.
  14133. */
  14134. Light.prototype.getShadowGenerator = function () {
  14135. return this._shadowGenerator;
  14136. };
  14137. /**
  14138. * Returns a Vector3, the absolute light position in the World.
  14139. */
  14140. Light.prototype.getAbsolutePosition = function () {
  14141. return BABYLON.Vector3.Zero();
  14142. };
  14143. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  14144. };
  14145. Light.prototype._getWorldMatrix = function () {
  14146. return BABYLON.Matrix.Identity();
  14147. };
  14148. /**
  14149. * Boolean : True if the light will affect the passed mesh.
  14150. */
  14151. Light.prototype.canAffectMesh = function (mesh) {
  14152. if (!mesh) {
  14153. return true;
  14154. }
  14155. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14156. return false;
  14157. }
  14158. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14159. return false;
  14160. }
  14161. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14162. return false;
  14163. }
  14164. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14165. return false;
  14166. }
  14167. return true;
  14168. };
  14169. /**
  14170. * Returns the light World matrix.
  14171. */
  14172. Light.prototype.getWorldMatrix = function () {
  14173. this._currentRenderId = this.getScene().getRenderId();
  14174. var worldMatrix = this._getWorldMatrix();
  14175. if (this.parent && this.parent.getWorldMatrix) {
  14176. if (!this._parentedWorldMatrix) {
  14177. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14178. }
  14179. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14180. this._markSyncedWithParent();
  14181. return this._parentedWorldMatrix;
  14182. }
  14183. return worldMatrix;
  14184. };
  14185. /**
  14186. * Disposes the light.
  14187. */
  14188. Light.prototype.dispose = function () {
  14189. if (this._shadowGenerator) {
  14190. this._shadowGenerator.dispose();
  14191. this._shadowGenerator = null;
  14192. }
  14193. // Animations
  14194. this.getScene().stopAnimation(this);
  14195. // Remove from meshes
  14196. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14197. var mesh = _a[_i];
  14198. mesh._removeLightSource(this);
  14199. }
  14200. // Remove from scene
  14201. this.getScene().removeLight(this);
  14202. _super.prototype.dispose.call(this);
  14203. };
  14204. /**
  14205. * Returns the light type ID (integer).
  14206. */
  14207. Light.prototype.getTypeID = function () {
  14208. return 0;
  14209. };
  14210. /**
  14211. * Returns a new Light object, named "name", from the current one.
  14212. */
  14213. Light.prototype.clone = function (name) {
  14214. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14215. };
  14216. /**
  14217. * Serializes the current light into a Serialization object.
  14218. * Returns the serialized object.
  14219. */
  14220. Light.prototype.serialize = function () {
  14221. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14222. // Type
  14223. serializationObject.type = this.getTypeID();
  14224. // Parent
  14225. if (this.parent) {
  14226. serializationObject.parentId = this.parent.id;
  14227. }
  14228. // Inclusion / exclusions
  14229. if (this.excludedMeshes.length > 0) {
  14230. serializationObject.excludedMeshesIds = [];
  14231. this.excludedMeshes.forEach(function (mesh) {
  14232. serializationObject.excludedMeshesIds.push(mesh.id);
  14233. });
  14234. }
  14235. if (this.includedOnlyMeshes.length > 0) {
  14236. serializationObject.includedOnlyMeshesIds = [];
  14237. this.includedOnlyMeshes.forEach(function (mesh) {
  14238. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14239. });
  14240. }
  14241. // Animations
  14242. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14243. serializationObject.ranges = this.serializeAnimationRanges();
  14244. return serializationObject;
  14245. };
  14246. /**
  14247. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14248. * This new light is named "name" and added to the passed scene.
  14249. */
  14250. Light.GetConstructorFromName = function (type, name, scene) {
  14251. switch (type) {
  14252. case 0:
  14253. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14254. case 1:
  14255. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14256. case 2:
  14257. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14258. case 3:
  14259. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14260. }
  14261. };
  14262. /**
  14263. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14264. */
  14265. Light.Parse = function (parsedLight, scene) {
  14266. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14267. // Inclusion / exclusions
  14268. if (parsedLight.excludedMeshesIds) {
  14269. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14270. }
  14271. if (parsedLight.includedOnlyMeshesIds) {
  14272. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14273. }
  14274. // Parent
  14275. if (parsedLight.parentId) {
  14276. light._waitingParentId = parsedLight.parentId;
  14277. }
  14278. // Animations
  14279. if (parsedLight.animations) {
  14280. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14281. var parsedAnimation = parsedLight.animations[animationIndex];
  14282. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14283. }
  14284. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14285. }
  14286. if (parsedLight.autoAnimate) {
  14287. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14288. }
  14289. return light;
  14290. };
  14291. Light.prototype._hookArray = function (array) {
  14292. var _this = this;
  14293. var oldPush = array.push;
  14294. array.push = function () {
  14295. var items = [];
  14296. for (var _i = 0; _i < arguments.length; _i++) {
  14297. items[_i] = arguments[_i];
  14298. }
  14299. var result = oldPush.apply(array, items);
  14300. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14301. var item = items_1[_a];
  14302. item._resyncLighSource(_this);
  14303. }
  14304. return result;
  14305. };
  14306. var oldSplice = array.splice;
  14307. array.splice = function (index, deleteCount) {
  14308. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14309. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14310. var item = deleted_1[_i];
  14311. item._resyncLighSource(_this);
  14312. }
  14313. return deleted;
  14314. };
  14315. };
  14316. Light.prototype._resyncMeshes = function () {
  14317. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14318. var mesh = _a[_i];
  14319. mesh._resyncLighSource(this);
  14320. }
  14321. };
  14322. Light.prototype._markMeshesAsLightDirty = function () {
  14323. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14324. var mesh = _a[_i];
  14325. if (mesh._lightSources.indexOf(this) !== -1) {
  14326. mesh._markSubMeshesAsLightDirty();
  14327. }
  14328. }
  14329. };
  14330. return Light;
  14331. }(BABYLON.Node));
  14332. //lightmapMode Consts
  14333. Light._LIGHTMAP_DEFAULT = 0;
  14334. Light._LIGHTMAP_SPECULAR = 1;
  14335. Light._LIGHTMAP_SHADOWSONLY = 2;
  14336. __decorate([
  14337. BABYLON.serializeAsColor3()
  14338. ], Light.prototype, "diffuse", void 0);
  14339. __decorate([
  14340. BABYLON.serializeAsColor3()
  14341. ], Light.prototype, "specular", void 0);
  14342. __decorate([
  14343. BABYLON.serialize()
  14344. ], Light.prototype, "intensity", void 0);
  14345. __decorate([
  14346. BABYLON.serialize()
  14347. ], Light.prototype, "range", void 0);
  14348. __decorate([
  14349. BABYLON.serialize("excludeWithLayerMask")
  14350. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14351. __decorate([
  14352. BABYLON.serialize("includeOnlyWithLayerMask")
  14353. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14354. __decorate([
  14355. BABYLON.serialize("lightmapMode")
  14356. ], Light.prototype, "_lightmapMode", void 0);
  14357. __decorate([
  14358. BABYLON.serialize()
  14359. ], Light.prototype, "radius", void 0);
  14360. BABYLON.Light = Light;
  14361. })(BABYLON || (BABYLON = {}));
  14362. //# sourceMappingURL=babylon.light.js.map
  14363. var BABYLON;
  14364. (function (BABYLON) {
  14365. var PointLight = (function (_super) {
  14366. __extends(PointLight, _super);
  14367. /**
  14368. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  14369. * A PointLight emits the light in every direction.
  14370. * It can cast shadows.
  14371. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  14372. * ```javascript
  14373. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  14374. * ```
  14375. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14376. */
  14377. function PointLight(name, position, scene) {
  14378. var _this = _super.call(this, name, scene) || this;
  14379. _this.position = position;
  14380. return _this;
  14381. }
  14382. /**
  14383. * Returns the string "PointLight"
  14384. */
  14385. PointLight.prototype.getClassName = function () {
  14386. return "PointLight";
  14387. };
  14388. /**
  14389. * Returns a Vector3, the PointLight absolute position in the World.
  14390. */
  14391. PointLight.prototype.getAbsolutePosition = function () {
  14392. return this.transformedPosition ? this.transformedPosition : this.position;
  14393. };
  14394. /**
  14395. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  14396. */
  14397. PointLight.prototype.computeTransformedPosition = function () {
  14398. if (this.parent && this.parent.getWorldMatrix) {
  14399. if (!this.transformedPosition) {
  14400. this.transformedPosition = BABYLON.Vector3.Zero();
  14401. }
  14402. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14403. return true;
  14404. }
  14405. return false;
  14406. };
  14407. /**
  14408. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  14409. * Returns the PointLight.
  14410. */
  14411. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  14412. if (this.parent && this.parent.getWorldMatrix) {
  14413. this.computeTransformedPosition();
  14414. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0);
  14415. return this;
  14416. }
  14417. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  14418. return this;
  14419. };
  14420. /**
  14421. * Boolean : returns true by default.
  14422. */
  14423. PointLight.prototype.needCube = function () {
  14424. return true;
  14425. };
  14426. /**
  14427. * Boolean : returns false by default.
  14428. */
  14429. PointLight.prototype.needRefreshPerFrame = function () {
  14430. return false;
  14431. };
  14432. /**
  14433. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  14434. */
  14435. PointLight.prototype.getShadowDirection = function (faceIndex) {
  14436. switch (faceIndex) {
  14437. case 0:
  14438. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  14439. case 1:
  14440. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  14441. case 2:
  14442. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  14443. case 3:
  14444. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  14445. case 4:
  14446. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  14447. case 5:
  14448. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  14449. }
  14450. return BABYLON.Vector3.Zero();
  14451. };
  14452. /**
  14453. * Return the depth scale used for the shadow map.
  14454. */
  14455. PointLight.prototype.getDepthScale = function () {
  14456. return 30.0;
  14457. };
  14458. /**
  14459. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  14460. * - fov = PI / 2
  14461. * - aspect ratio : 1.0
  14462. * - z-near and far equal to the active camera minZ and maxZ.
  14463. * Returns the PointLight.
  14464. */
  14465. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14466. if (this.customProjectionMatrixBuilder) {
  14467. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14468. }
  14469. else {
  14470. var activeCamera = this.getScene().activeCamera;
  14471. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  14472. }
  14473. return this;
  14474. };
  14475. PointLight.prototype._getWorldMatrix = function () {
  14476. if (!this._worldMatrix) {
  14477. this._worldMatrix = BABYLON.Matrix.Identity();
  14478. }
  14479. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14480. return this._worldMatrix;
  14481. };
  14482. /**
  14483. * Returns the integer 0.
  14484. */
  14485. PointLight.prototype.getTypeID = function () {
  14486. return 0;
  14487. };
  14488. return PointLight;
  14489. }(BABYLON.Light));
  14490. __decorate([
  14491. BABYLON.serializeAsVector3()
  14492. ], PointLight.prototype, "position", void 0);
  14493. __decorate([
  14494. BABYLON.serialize()
  14495. ], PointLight.prototype, "shadowMinZ", void 0);
  14496. __decorate([
  14497. BABYLON.serialize()
  14498. ], PointLight.prototype, "shadowMaxZ", void 0);
  14499. BABYLON.PointLight = PointLight;
  14500. })(BABYLON || (BABYLON = {}));
  14501. //# sourceMappingURL=babylon.pointLight.js.map
  14502. var BABYLON;
  14503. (function (BABYLON) {
  14504. var SpotLight = (function (_super) {
  14505. __extends(SpotLight, _super);
  14506. /**
  14507. * Creates a SpotLight object in the scene with the passed parameters :
  14508. * - `position` (Vector3) is the initial SpotLight position,
  14509. * - `direction` (Vector3) is the initial SpotLight direction,
  14510. * - `angle` (float, in radians) is the spot light cone angle,
  14511. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  14512. * A spot light is a simply light oriented cone.
  14513. * It can cast shadows.
  14514. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14515. */
  14516. function SpotLight(name, position, direction, angle, exponent, scene) {
  14517. var _this = _super.call(this, name, scene) || this;
  14518. _this.position = position;
  14519. _this.direction = direction;
  14520. _this.angle = angle;
  14521. _this.exponent = exponent;
  14522. return _this;
  14523. }
  14524. /**
  14525. * Returns the string "SpotLight".
  14526. */
  14527. SpotLight.prototype.getClassName = function () {
  14528. return "SpotLight";
  14529. };
  14530. /**
  14531. * Returns the SpotLight absolute position in the World (Vector3).
  14532. */
  14533. SpotLight.prototype.getAbsolutePosition = function () {
  14534. return this.transformedPosition ? this.transformedPosition : this.position;
  14535. };
  14536. /**
  14537. * Return the depth scale used for the shadow map.
  14538. */
  14539. SpotLight.prototype.getDepthScale = function () {
  14540. return 30.0;
  14541. };
  14542. /**
  14543. * 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.
  14544. * Returns the SpotLight.
  14545. */
  14546. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14547. if (this.customProjectionMatrixBuilder) {
  14548. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14549. }
  14550. else {
  14551. var activeCamera = this.getScene().activeCamera;
  14552. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  14553. }
  14554. return this;
  14555. };
  14556. /**
  14557. * Boolean : false by default.
  14558. */
  14559. SpotLight.prototype.needCube = function () {
  14560. return false;
  14561. };
  14562. /**
  14563. * Boolean : false by default.
  14564. */
  14565. SpotLight.prototype.needRefreshPerFrame = function () {
  14566. return false;
  14567. };
  14568. /**
  14569. * Returns the SpotLight direction (Vector3) for any passed face index.
  14570. */
  14571. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  14572. return this.direction;
  14573. };
  14574. /**
  14575. * Updates the SpotLight direction towards the passed target (Vector3).
  14576. * Returns the updated direction.
  14577. */
  14578. SpotLight.prototype.setDirectionToTarget = function (target) {
  14579. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14580. return this.direction;
  14581. };
  14582. /**
  14583. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  14584. */
  14585. SpotLight.prototype.computeTransformedPosition = function () {
  14586. if (this.parent && this.parent.getWorldMatrix) {
  14587. if (!this.transformedPosition) {
  14588. this.transformedPosition = BABYLON.Vector3.Zero();
  14589. }
  14590. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14591. return true;
  14592. }
  14593. return false;
  14594. };
  14595. /**
  14596. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  14597. * Return the SpotLight.
  14598. */
  14599. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  14600. var normalizeDirection;
  14601. if (this.parent && this.parent.getWorldMatrix) {
  14602. if (!this._transformedDirection) {
  14603. this._transformedDirection = BABYLON.Vector3.Zero();
  14604. }
  14605. this.computeTransformedPosition();
  14606. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14607. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  14608. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  14609. }
  14610. else {
  14611. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  14612. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14613. }
  14614. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  14615. return this;
  14616. };
  14617. SpotLight.prototype._getWorldMatrix = function () {
  14618. if (!this._worldMatrix) {
  14619. this._worldMatrix = BABYLON.Matrix.Identity();
  14620. }
  14621. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14622. return this._worldMatrix;
  14623. };
  14624. /**
  14625. * Returns the integer 2.
  14626. */
  14627. SpotLight.prototype.getTypeID = function () {
  14628. return 2;
  14629. };
  14630. /**
  14631. * Returns the SpotLight rotation (Vector3).
  14632. */
  14633. SpotLight.prototype.getRotation = function () {
  14634. this.direction.normalize();
  14635. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  14636. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  14637. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  14638. };
  14639. return SpotLight;
  14640. }(BABYLON.Light));
  14641. __decorate([
  14642. BABYLON.serializeAsVector3()
  14643. ], SpotLight.prototype, "position", void 0);
  14644. __decorate([
  14645. BABYLON.serializeAsVector3()
  14646. ], SpotLight.prototype, "direction", void 0);
  14647. __decorate([
  14648. BABYLON.serialize()
  14649. ], SpotLight.prototype, "angle", void 0);
  14650. __decorate([
  14651. BABYLON.serialize()
  14652. ], SpotLight.prototype, "exponent", void 0);
  14653. __decorate([
  14654. BABYLON.serialize()
  14655. ], SpotLight.prototype, "shadowMinZ", void 0);
  14656. __decorate([
  14657. BABYLON.serialize()
  14658. ], SpotLight.prototype, "shadowMaxZ", void 0);
  14659. BABYLON.SpotLight = SpotLight;
  14660. })(BABYLON || (BABYLON = {}));
  14661. //# sourceMappingURL=babylon.spotLight.js.map
  14662. var BABYLON;
  14663. (function (BABYLON) {
  14664. var HemisphericLight = (function (_super) {
  14665. __extends(HemisphericLight, _super);
  14666. /**
  14667. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  14668. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  14669. * The HemisphericLight can't cast shadows.
  14670. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14671. */
  14672. function HemisphericLight(name, direction, scene) {
  14673. var _this = _super.call(this, name, scene) || this;
  14674. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  14675. _this.direction = direction;
  14676. return _this;
  14677. }
  14678. /**
  14679. * Returns the string "HemisphericLight".
  14680. */
  14681. HemisphericLight.prototype.getClassName = function () {
  14682. return "HemisphericLight";
  14683. };
  14684. /**
  14685. * Sets the HemisphericLight direction towards the passed target (Vector3).
  14686. * Returns the updated direction.
  14687. */
  14688. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  14689. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  14690. return this.direction;
  14691. };
  14692. HemisphericLight.prototype.getShadowGenerator = function () {
  14693. return null;
  14694. };
  14695. /**
  14696. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  14697. * Returns the HemisphericLight.
  14698. */
  14699. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  14700. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14701. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0);
  14702. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  14703. return this;
  14704. };
  14705. HemisphericLight.prototype._getWorldMatrix = function () {
  14706. if (!this._worldMatrix) {
  14707. this._worldMatrix = BABYLON.Matrix.Identity();
  14708. }
  14709. return this._worldMatrix;
  14710. };
  14711. /**
  14712. * Returns the integer 3.
  14713. */
  14714. HemisphericLight.prototype.getTypeID = function () {
  14715. return 3;
  14716. };
  14717. return HemisphericLight;
  14718. }(BABYLON.Light));
  14719. __decorate([
  14720. BABYLON.serializeAsColor3()
  14721. ], HemisphericLight.prototype, "groundColor", void 0);
  14722. __decorate([
  14723. BABYLON.serializeAsVector3()
  14724. ], HemisphericLight.prototype, "direction", void 0);
  14725. BABYLON.HemisphericLight = HemisphericLight;
  14726. })(BABYLON || (BABYLON = {}));
  14727. //# sourceMappingURL=babylon.hemisphericLight.js.map
  14728. /// <reference path="babylon.light.ts" />
  14729. var BABYLON;
  14730. (function (BABYLON) {
  14731. var DirectionalLight = (function (_super) {
  14732. __extends(DirectionalLight, _super);
  14733. /**
  14734. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  14735. * The directional light is emitted from everywhere in the given direction.
  14736. * It can cast shawdows.
  14737. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14738. */
  14739. function DirectionalLight(name, direction, scene) {
  14740. var _this = _super.call(this, name, scene) || this;
  14741. _this.shadowOrthoScale = 0.5;
  14742. _this.autoUpdateExtends = true;
  14743. // Cache
  14744. _this._orthoLeft = Number.MAX_VALUE;
  14745. _this._orthoRight = Number.MIN_VALUE;
  14746. _this._orthoTop = Number.MIN_VALUE;
  14747. _this._orthoBottom = Number.MAX_VALUE;
  14748. _this.position = direction.scale(-1.0);
  14749. _this.direction = direction;
  14750. return _this;
  14751. }
  14752. /**
  14753. * Returns the string "DirectionalLight".
  14754. */
  14755. DirectionalLight.prototype.getClassName = function () {
  14756. return "DirectionalLight";
  14757. };
  14758. /**
  14759. * Returns the DirectionalLight absolute position in the World.
  14760. */
  14761. DirectionalLight.prototype.getAbsolutePosition = function () {
  14762. return this.transformedPosition ? this.transformedPosition : this.position;
  14763. };
  14764. /**
  14765. * Sets the DirectionalLight direction toward the passed target (Vector3).
  14766. * Returns the updated DirectionalLight direction (Vector3).
  14767. */
  14768. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  14769. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14770. return this.direction;
  14771. };
  14772. /**
  14773. * Return the depth scale used for the shadow map.
  14774. */
  14775. DirectionalLight.prototype.getDepthScale = function () {
  14776. return 30.0;
  14777. };
  14778. /**
  14779. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  14780. * Returns the DirectionalLight.
  14781. */
  14782. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14783. if (this.customProjectionMatrixBuilder) {
  14784. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14785. }
  14786. else {
  14787. var activeCamera = this.getScene().activeCamera;
  14788. // Check extends
  14789. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  14790. var tempVector3 = BABYLON.Vector3.Zero();
  14791. this._orthoLeft = Number.MAX_VALUE;
  14792. this._orthoRight = Number.MIN_VALUE;
  14793. this._orthoTop = Number.MIN_VALUE;
  14794. this._orthoBottom = Number.MAX_VALUE;
  14795. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  14796. var mesh = renderList[meshIndex];
  14797. if (!mesh) {
  14798. continue;
  14799. }
  14800. var boundingInfo = mesh.getBoundingInfo();
  14801. if (!boundingInfo) {
  14802. continue;
  14803. }
  14804. var boundingBox = boundingInfo.boundingBox;
  14805. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  14806. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  14807. if (tempVector3.x < this._orthoLeft)
  14808. this._orthoLeft = tempVector3.x;
  14809. if (tempVector3.y < this._orthoBottom)
  14810. this._orthoBottom = tempVector3.y;
  14811. if (tempVector3.x > this._orthoRight)
  14812. this._orthoRight = tempVector3.x;
  14813. if (tempVector3.y > this._orthoTop)
  14814. this._orthoTop = tempVector3.y;
  14815. }
  14816. }
  14817. }
  14818. var xOffset = this._orthoRight - this._orthoLeft;
  14819. var yOffset = this._orthoTop - this._orthoBottom;
  14820. 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);
  14821. }
  14822. return this;
  14823. };
  14824. /**
  14825. * Boolean : true by default.
  14826. */
  14827. DirectionalLight.prototype.needRefreshPerFrame = function () {
  14828. return true;
  14829. };
  14830. /**
  14831. * Boolean : false by default.
  14832. */
  14833. DirectionalLight.prototype.needCube = function () {
  14834. return false;
  14835. };
  14836. /**
  14837. * Returns the light direction (Vector3) for any passed face index.
  14838. */
  14839. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  14840. return this.direction;
  14841. };
  14842. /**
  14843. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  14844. */
  14845. DirectionalLight.prototype.computeTransformedPosition = function () {
  14846. if (this.parent && this.parent.getWorldMatrix) {
  14847. if (!this.transformedPosition) {
  14848. this.transformedPosition = BABYLON.Vector3.Zero();
  14849. }
  14850. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14851. return true;
  14852. }
  14853. return false;
  14854. };
  14855. /**
  14856. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  14857. * Returns the DirectionalLight.
  14858. */
  14859. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  14860. if (this.parent && this.parent.getWorldMatrix) {
  14861. if (!this._transformedDirection) {
  14862. this._transformedDirection = BABYLON.Vector3.Zero();
  14863. }
  14864. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14865. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  14866. return this;
  14867. }
  14868. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  14869. return this;
  14870. };
  14871. DirectionalLight.prototype._getWorldMatrix = function () {
  14872. if (!this._worldMatrix) {
  14873. this._worldMatrix = BABYLON.Matrix.Identity();
  14874. }
  14875. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14876. return this._worldMatrix;
  14877. };
  14878. /**
  14879. * Returns the integer 1.
  14880. */
  14881. DirectionalLight.prototype.getTypeID = function () {
  14882. return 1;
  14883. };
  14884. return DirectionalLight;
  14885. }(BABYLON.Light));
  14886. __decorate([
  14887. BABYLON.serializeAsVector3()
  14888. ], DirectionalLight.prototype, "position", void 0);
  14889. __decorate([
  14890. BABYLON.serializeAsVector3()
  14891. ], DirectionalLight.prototype, "direction", void 0);
  14892. __decorate([
  14893. BABYLON.serialize()
  14894. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  14895. __decorate([
  14896. BABYLON.serialize()
  14897. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  14898. __decorate([
  14899. BABYLON.serialize()
  14900. ], DirectionalLight.prototype, "shadowMinZ", void 0);
  14901. __decorate([
  14902. BABYLON.serialize()
  14903. ], DirectionalLight.prototype, "shadowMaxZ", void 0);
  14904. BABYLON.DirectionalLight = DirectionalLight;
  14905. })(BABYLON || (BABYLON = {}));
  14906. //# sourceMappingURL=babylon.directionalLight.js.map
  14907. var BABYLON;
  14908. (function (BABYLON) {
  14909. var ShadowGenerator = (function () {
  14910. /**
  14911. * Creates a ShadowGenerator object.
  14912. * A ShadowGenerator is the required tool to use the shadows.
  14913. * Each light casting shadows needs to use its own ShadowGenerator.
  14914. * Required parameters :
  14915. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  14916. * - `light` : the light object generating the shadows.
  14917. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  14918. */
  14919. function ShadowGenerator(mapSize, light) {
  14920. var _this = this;
  14921. // Members
  14922. this._filter = ShadowGenerator.FILTER_NONE;
  14923. this.blurScale = 2;
  14924. this._blurBoxOffset = 0;
  14925. this._bias = 0.00005;
  14926. this._lightDirection = BABYLON.Vector3.Zero();
  14927. this.forceBackFacesOnly = false;
  14928. this._darkness = 0;
  14929. this._transparencyShadow = false;
  14930. this._viewMatrix = BABYLON.Matrix.Zero();
  14931. this._projectionMatrix = BABYLON.Matrix.Zero();
  14932. this._transformMatrix = BABYLON.Matrix.Zero();
  14933. this._worldViewProjection = BABYLON.Matrix.Zero();
  14934. this._currentFaceIndex = 0;
  14935. this._currentFaceIndexCache = 0;
  14936. this._useFullFloat = true;
  14937. this._light = light;
  14938. this._scene = light.getScene();
  14939. this._mapSize = mapSize;
  14940. light._shadowGenerator = this;
  14941. light._markMeshesAsLightDirty();
  14942. // Texture type fallback from float to int if not supported.
  14943. var textureType;
  14944. var caps = this._scene.getEngine().getCaps();
  14945. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  14946. this._useFullFloat = true;
  14947. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  14948. }
  14949. else {
  14950. this._useFullFloat = false;
  14951. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  14952. }
  14953. // Render target
  14954. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  14955. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14956. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14957. this._shadowMap.anisotropicFilteringLevel = 1;
  14958. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14959. this._shadowMap.renderParticles = false;
  14960. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  14961. _this._currentFaceIndex = faceIndex;
  14962. });
  14963. this._shadowMap.onAfterUnbindObservable.add(function () {
  14964. if (!_this.useBlurExponentialShadowMap) {
  14965. return;
  14966. }
  14967. if (!_this._shadowMap2) {
  14968. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  14969. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14970. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14971. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14972. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  14973. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  14974. effect.setTexture("textureSampler", _this._shadowMap);
  14975. });
  14976. _this.blurBoxOffset = 1;
  14977. }
  14978. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  14979. });
  14980. // Custom render function
  14981. var renderSubMesh = function (subMesh) {
  14982. var mesh = subMesh.getRenderingMesh();
  14983. var scene = _this._scene;
  14984. var engine = scene.getEngine();
  14985. // Culling
  14986. engine.setState(subMesh.getMaterial().backFaceCulling);
  14987. // Managing instances
  14988. var batch = mesh._getInstancesRenderList(subMesh._id);
  14989. if (batch.mustReturn) {
  14990. return;
  14991. }
  14992. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14993. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  14994. engine.enableEffect(_this._effect);
  14995. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  14996. var material = subMesh.getMaterial();
  14997. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  14998. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  14999. _this._effect.setVector3("lightPosition", _this.getLight().position);
  15000. if (_this.getLight().needCube()) {
  15001. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  15002. }
  15003. // Alpha test
  15004. if (material && material.needAlphaTesting()) {
  15005. var alphaTexture = material.getAlphaTestTexture();
  15006. _this._effect.setTexture("diffuseSampler", alphaTexture);
  15007. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  15008. }
  15009. // Bones
  15010. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  15011. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  15012. }
  15013. if (_this.forceBackFacesOnly) {
  15014. engine.setState(true, 0, false, true);
  15015. }
  15016. // Draw
  15017. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  15018. if (_this.forceBackFacesOnly) {
  15019. engine.setState(true, 0, false, false);
  15020. }
  15021. }
  15022. else {
  15023. // Need to reset refresh rate of the shadowMap
  15024. _this._shadowMap.resetRefreshCounter();
  15025. }
  15026. };
  15027. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  15028. var index;
  15029. for (index = 0; index < opaqueSubMeshes.length; index++) {
  15030. renderSubMesh(opaqueSubMeshes.data[index]);
  15031. }
  15032. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  15033. renderSubMesh(alphaTestSubMeshes.data[index]);
  15034. }
  15035. if (_this._transparencyShadow) {
  15036. for (index = 0; index < transparentSubMeshes.length; index++) {
  15037. renderSubMesh(transparentSubMeshes.data[index]);
  15038. }
  15039. }
  15040. };
  15041. this._shadowMap.onClearObservable.add(function (engine) {
  15042. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  15043. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  15044. }
  15045. else {
  15046. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  15047. }
  15048. });
  15049. }
  15050. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  15051. // Static
  15052. get: function () {
  15053. return ShadowGenerator._FILTER_NONE;
  15054. },
  15055. enumerable: true,
  15056. configurable: true
  15057. });
  15058. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  15059. get: function () {
  15060. return ShadowGenerator._FILTER_POISSONSAMPLING;
  15061. },
  15062. enumerable: true,
  15063. configurable: true
  15064. });
  15065. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  15066. get: function () {
  15067. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  15068. },
  15069. enumerable: true,
  15070. configurable: true
  15071. });
  15072. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  15073. get: function () {
  15074. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  15075. },
  15076. enumerable: true,
  15077. configurable: true
  15078. });
  15079. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  15080. get: function () {
  15081. return this._bias;
  15082. },
  15083. set: function (bias) {
  15084. this._bias = bias;
  15085. },
  15086. enumerable: true,
  15087. configurable: true
  15088. });
  15089. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  15090. get: function () {
  15091. return this._blurBoxOffset;
  15092. },
  15093. set: function (value) {
  15094. var _this = this;
  15095. if (this._blurBoxOffset === value) {
  15096. return;
  15097. }
  15098. this._blurBoxOffset = value;
  15099. if (this._boxBlurPostprocess) {
  15100. this._boxBlurPostprocess.dispose();
  15101. }
  15102. var textureType;
  15103. var caps = this._scene.getEngine().getCaps();
  15104. if (this._useFullFloat) {
  15105. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  15106. }
  15107. else {
  15108. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  15109. }
  15110. 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);
  15111. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  15112. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  15113. });
  15114. },
  15115. enumerable: true,
  15116. configurable: true
  15117. });
  15118. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  15119. get: function () {
  15120. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  15121. },
  15122. set: function (value) {
  15123. this._depthScale = value;
  15124. },
  15125. enumerable: true,
  15126. configurable: true
  15127. });
  15128. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  15129. get: function () {
  15130. return this._filter;
  15131. },
  15132. set: function (value) {
  15133. if (this._filter === value) {
  15134. return;
  15135. }
  15136. this._filter = value;
  15137. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  15138. this._shadowMap.anisotropicFilteringLevel = 16;
  15139. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  15140. }
  15141. else {
  15142. this._shadowMap.anisotropicFilteringLevel = 1;
  15143. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  15144. }
  15145. this._light._markMeshesAsLightDirty();
  15146. },
  15147. enumerable: true,
  15148. configurable: true
  15149. });
  15150. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  15151. get: function () {
  15152. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  15153. return this.useExponentialShadowMap;
  15154. },
  15155. set: function (value) {
  15156. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  15157. this.useExponentialShadowMap = value;
  15158. },
  15159. enumerable: true,
  15160. configurable: true
  15161. });
  15162. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  15163. get: function () {
  15164. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  15165. },
  15166. set: function (value) {
  15167. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  15168. },
  15169. enumerable: true,
  15170. configurable: true
  15171. });
  15172. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  15173. get: function () {
  15174. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  15175. },
  15176. set: function (value) {
  15177. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  15178. },
  15179. enumerable: true,
  15180. configurable: true
  15181. });
  15182. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  15183. get: function () {
  15184. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  15185. return this.useBlurExponentialShadowMap;
  15186. },
  15187. set: function (value) {
  15188. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  15189. this.useBlurExponentialShadowMap = value;
  15190. },
  15191. enumerable: true,
  15192. configurable: true
  15193. });
  15194. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  15195. get: function () {
  15196. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  15197. },
  15198. set: function (value) {
  15199. if (this._light.needCube() && value) {
  15200. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  15201. }
  15202. else {
  15203. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  15204. }
  15205. },
  15206. enumerable: true,
  15207. configurable: true
  15208. });
  15209. /**
  15210. * Boolean : true when the ShadowGenerator is finally computed.
  15211. */
  15212. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  15213. var defines = [];
  15214. if (this._useFullFloat) {
  15215. defines.push("#define FULLFLOAT");
  15216. }
  15217. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  15218. defines.push("#define ESM");
  15219. }
  15220. if (this.getLight().needCube()) {
  15221. defines.push("#define CUBEMAP");
  15222. }
  15223. var attribs = [BABYLON.VertexBuffer.PositionKind];
  15224. var mesh = subMesh.getMesh();
  15225. var material = subMesh.getMaterial();
  15226. // Alpha test
  15227. if (material && material.needAlphaTesting()) {
  15228. defines.push("#define ALPHATEST");
  15229. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15230. attribs.push(BABYLON.VertexBuffer.UVKind);
  15231. defines.push("#define UV1");
  15232. }
  15233. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15234. var alphaTexture = material.getAlphaTestTexture();
  15235. if (alphaTexture.coordinatesIndex === 1) {
  15236. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  15237. defines.push("#define UV2");
  15238. }
  15239. }
  15240. }
  15241. // Bones
  15242. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  15243. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15244. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15245. if (mesh.numBoneInfluencers > 4) {
  15246. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  15247. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  15248. }
  15249. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  15250. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  15251. }
  15252. else {
  15253. defines.push("#define NUM_BONE_INFLUENCERS 0");
  15254. }
  15255. // Instances
  15256. if (useInstances) {
  15257. defines.push("#define INSTANCES");
  15258. attribs.push("world0");
  15259. attribs.push("world1");
  15260. attribs.push("world2");
  15261. attribs.push("world3");
  15262. }
  15263. // Get correct effect
  15264. var join = defines.join("\n");
  15265. if (this._cachedDefines !== join) {
  15266. this._cachedDefines = join;
  15267. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  15268. }
  15269. return this._effect.isReady();
  15270. };
  15271. /**
  15272. * Returns a RenderTargetTexture object : the shadow map texture.
  15273. */
  15274. ShadowGenerator.prototype.getShadowMap = function () {
  15275. return this._shadowMap;
  15276. };
  15277. /**
  15278. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  15279. */
  15280. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  15281. if (this._shadowMap2) {
  15282. return this._shadowMap2;
  15283. }
  15284. return this._shadowMap;
  15285. };
  15286. /**
  15287. * Returns the associated light object.
  15288. */
  15289. ShadowGenerator.prototype.getLight = function () {
  15290. return this._light;
  15291. };
  15292. // Methods
  15293. /**
  15294. * Returns a Matrix object : the updated transformation matrix.
  15295. */
  15296. ShadowGenerator.prototype.getTransformMatrix = function () {
  15297. var scene = this._scene;
  15298. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  15299. return this._transformMatrix;
  15300. }
  15301. this._currentRenderID = scene.getRenderId();
  15302. this._currentFaceIndexCache = this._currentFaceIndex;
  15303. var lightPosition = this._light.position;
  15304. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  15305. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  15306. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  15307. }
  15308. if (this._light.computeTransformedPosition()) {
  15309. lightPosition = this._light.transformedPosition;
  15310. }
  15311. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  15312. this._cachedPosition = lightPosition.clone();
  15313. this._cachedDirection = this._lightDirection.clone();
  15314. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  15315. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  15316. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15317. }
  15318. return this._transformMatrix;
  15319. };
  15320. /**
  15321. * Returns the darkness value (float).
  15322. */
  15323. ShadowGenerator.prototype.getDarkness = function () {
  15324. return this._darkness;
  15325. };
  15326. /**
  15327. * Sets the ShadowGenerator darkness value (float <= 1.0).
  15328. * Returns the ShadowGenerator.
  15329. */
  15330. ShadowGenerator.prototype.setDarkness = function (darkness) {
  15331. if (darkness >= 1.0)
  15332. this._darkness = 1.0;
  15333. else if (darkness <= 0.0)
  15334. this._darkness = 0.0;
  15335. else
  15336. this._darkness = darkness;
  15337. return this;
  15338. };
  15339. /**
  15340. * Sets the ability to have transparent shadow (boolean).
  15341. * Returns the ShadowGenerator.
  15342. */
  15343. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  15344. this._transparencyShadow = hasShadow;
  15345. return this;
  15346. };
  15347. ShadowGenerator.prototype._packHalf = function (depth) {
  15348. var scale = depth * 255.0;
  15349. var fract = scale - Math.floor(scale);
  15350. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  15351. };
  15352. /**
  15353. * Disposes the ShadowGenerator.
  15354. * Returns nothing.
  15355. */
  15356. ShadowGenerator.prototype.dispose = function () {
  15357. this._shadowMap.dispose();
  15358. if (this._shadowMap2) {
  15359. this._shadowMap2.dispose();
  15360. }
  15361. if (this._downSamplePostprocess) {
  15362. this._downSamplePostprocess.dispose();
  15363. }
  15364. if (this._boxBlurPostprocess) {
  15365. this._boxBlurPostprocess.dispose();
  15366. }
  15367. this._light._shadowGenerator = null;
  15368. this._light._markMeshesAsLightDirty();
  15369. };
  15370. /**
  15371. * Serializes the ShadowGenerator and returns a serializationObject.
  15372. */
  15373. ShadowGenerator.prototype.serialize = function () {
  15374. var serializationObject = {};
  15375. serializationObject.lightId = this._light.id;
  15376. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  15377. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  15378. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  15379. serializationObject.usePoissonSampling = this.usePoissonSampling;
  15380. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  15381. serializationObject.depthScale = this.depthScale;
  15382. serializationObject.darkness = this.getDarkness();
  15383. serializationObject.renderList = [];
  15384. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  15385. var mesh = this.getShadowMap().renderList[meshIndex];
  15386. serializationObject.renderList.push(mesh.id);
  15387. }
  15388. return serializationObject;
  15389. };
  15390. /**
  15391. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  15392. */
  15393. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  15394. //casting to point light, as light is missing the position attr and typescript complains.
  15395. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  15396. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  15397. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  15398. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  15399. meshes.forEach(function (mesh) {
  15400. shadowGenerator.getShadowMap().renderList.push(mesh);
  15401. });
  15402. }
  15403. if (parsedShadowGenerator.usePoissonSampling) {
  15404. shadowGenerator.usePoissonSampling = true;
  15405. }
  15406. else if (parsedShadowGenerator.useExponentialShadowMap) {
  15407. shadowGenerator.useExponentialShadowMap = true;
  15408. }
  15409. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  15410. shadowGenerator.useBlurExponentialShadowMap = true;
  15411. }
  15412. else if (parsedShadowGenerator.useVarianceShadowMap) {
  15413. shadowGenerator.useExponentialShadowMap = true;
  15414. }
  15415. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  15416. shadowGenerator.useBlurExponentialShadowMap = true;
  15417. }
  15418. if (parsedShadowGenerator.depthScale) {
  15419. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  15420. }
  15421. if (parsedShadowGenerator.blurScale) {
  15422. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  15423. }
  15424. if (parsedShadowGenerator.blurBoxOffset) {
  15425. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  15426. }
  15427. if (parsedShadowGenerator.bias !== undefined) {
  15428. shadowGenerator.bias = parsedShadowGenerator.bias;
  15429. }
  15430. if (parsedShadowGenerator.darkness) {
  15431. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  15432. }
  15433. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  15434. return shadowGenerator;
  15435. };
  15436. return ShadowGenerator;
  15437. }());
  15438. ShadowGenerator._FILTER_NONE = 0;
  15439. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  15440. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  15441. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  15442. BABYLON.ShadowGenerator = ShadowGenerator;
  15443. })(BABYLON || (BABYLON = {}));
  15444. //# sourceMappingURL=babylon.shadowGenerator.js.map
  15445. var BABYLON;
  15446. (function (BABYLON) {
  15447. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  15448. if (boxMin.x > sphereCenter.x + sphereRadius)
  15449. return false;
  15450. if (sphereCenter.x - sphereRadius > boxMax.x)
  15451. return false;
  15452. if (boxMin.y > sphereCenter.y + sphereRadius)
  15453. return false;
  15454. if (sphereCenter.y - sphereRadius > boxMax.y)
  15455. return false;
  15456. if (boxMin.z > sphereCenter.z + sphereRadius)
  15457. return false;
  15458. if (sphereCenter.z - sphereRadius > boxMax.z)
  15459. return false;
  15460. return true;
  15461. };
  15462. var getLowestRoot = (function () {
  15463. var result = { root: 0, found: false };
  15464. return function (a, b, c, maxR) {
  15465. result.root = 0;
  15466. result.found = false;
  15467. var determinant = b * b - 4.0 * a * c;
  15468. if (determinant < 0)
  15469. return result;
  15470. var sqrtD = Math.sqrt(determinant);
  15471. var r1 = (-b - sqrtD) / (2.0 * a);
  15472. var r2 = (-b + sqrtD) / (2.0 * a);
  15473. if (r1 > r2) {
  15474. var temp = r2;
  15475. r2 = r1;
  15476. r1 = temp;
  15477. }
  15478. if (r1 > 0 && r1 < maxR) {
  15479. result.root = r1;
  15480. result.found = true;
  15481. return result;
  15482. }
  15483. if (r2 > 0 && r2 < maxR) {
  15484. result.root = r2;
  15485. result.found = true;
  15486. return result;
  15487. }
  15488. return result;
  15489. };
  15490. })();
  15491. var Collider = (function () {
  15492. function Collider() {
  15493. this.radius = new BABYLON.Vector3(1, 1, 1);
  15494. this.retry = 0;
  15495. this.basePointWorld = BABYLON.Vector3.Zero();
  15496. this.velocityWorld = BABYLON.Vector3.Zero();
  15497. this.normalizedVelocity = BABYLON.Vector3.Zero();
  15498. this._collisionPoint = BABYLON.Vector3.Zero();
  15499. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  15500. this._tempVector = BABYLON.Vector3.Zero();
  15501. this._tempVector2 = BABYLON.Vector3.Zero();
  15502. this._tempVector3 = BABYLON.Vector3.Zero();
  15503. this._tempVector4 = BABYLON.Vector3.Zero();
  15504. this._edge = BABYLON.Vector3.Zero();
  15505. this._baseToVertex = BABYLON.Vector3.Zero();
  15506. this._destinationPoint = BABYLON.Vector3.Zero();
  15507. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  15508. this._displacementVector = BABYLON.Vector3.Zero();
  15509. this._collisionMask = -1;
  15510. }
  15511. Object.defineProperty(Collider.prototype, "collisionMask", {
  15512. get: function () {
  15513. return this._collisionMask;
  15514. },
  15515. set: function (mask) {
  15516. this._collisionMask = !isNaN(mask) ? mask : -1;
  15517. },
  15518. enumerable: true,
  15519. configurable: true
  15520. });
  15521. // Methods
  15522. Collider.prototype._initialize = function (source, dir, e) {
  15523. this.velocity = dir;
  15524. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  15525. this.basePoint = source;
  15526. source.multiplyToRef(this.radius, this.basePointWorld);
  15527. dir.multiplyToRef(this.radius, this.velocityWorld);
  15528. this.velocityWorldLength = this.velocityWorld.length();
  15529. this.epsilon = e;
  15530. this.collisionFound = false;
  15531. };
  15532. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  15533. pa.subtractToRef(point, this._tempVector);
  15534. pb.subtractToRef(point, this._tempVector2);
  15535. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  15536. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15537. if (d < 0)
  15538. return false;
  15539. pc.subtractToRef(point, this._tempVector3);
  15540. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  15541. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15542. if (d < 0)
  15543. return false;
  15544. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  15545. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15546. return d >= 0;
  15547. };
  15548. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  15549. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  15550. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  15551. if (distance > this.velocityWorldLength + max + sphereRadius) {
  15552. return false;
  15553. }
  15554. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  15555. return false;
  15556. return true;
  15557. };
  15558. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  15559. var t0;
  15560. var embeddedInPlane = false;
  15561. //defensive programming, actually not needed.
  15562. if (!trianglePlaneArray) {
  15563. trianglePlaneArray = [];
  15564. }
  15565. if (!trianglePlaneArray[faceIndex]) {
  15566. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  15567. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  15568. }
  15569. var trianglePlane = trianglePlaneArray[faceIndex];
  15570. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  15571. return;
  15572. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  15573. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  15574. if (normalDotVelocity == 0) {
  15575. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  15576. return;
  15577. embeddedInPlane = true;
  15578. t0 = 0;
  15579. }
  15580. else {
  15581. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15582. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15583. if (t0 > t1) {
  15584. var temp = t1;
  15585. t1 = t0;
  15586. t0 = temp;
  15587. }
  15588. if (t0 > 1.0 || t1 < 0.0)
  15589. return;
  15590. if (t0 < 0)
  15591. t0 = 0;
  15592. if (t0 > 1.0)
  15593. t0 = 1.0;
  15594. }
  15595. this._collisionPoint.copyFromFloats(0, 0, 0);
  15596. var found = false;
  15597. var t = 1.0;
  15598. if (!embeddedInPlane) {
  15599. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  15600. this.velocity.scaleToRef(t0, this._tempVector);
  15601. this._planeIntersectionPoint.addInPlace(this._tempVector);
  15602. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  15603. found = true;
  15604. t = t0;
  15605. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  15606. }
  15607. }
  15608. if (!found) {
  15609. var velocitySquaredLength = this.velocity.lengthSquared();
  15610. var a = velocitySquaredLength;
  15611. this.basePoint.subtractToRef(p1, this._tempVector);
  15612. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15613. var c = this._tempVector.lengthSquared() - 1.0;
  15614. var lowestRoot = getLowestRoot(a, b, c, t);
  15615. if (lowestRoot.found) {
  15616. t = lowestRoot.root;
  15617. found = true;
  15618. this._collisionPoint.copyFrom(p1);
  15619. }
  15620. this.basePoint.subtractToRef(p2, this._tempVector);
  15621. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15622. c = this._tempVector.lengthSquared() - 1.0;
  15623. lowestRoot = getLowestRoot(a, b, c, t);
  15624. if (lowestRoot.found) {
  15625. t = lowestRoot.root;
  15626. found = true;
  15627. this._collisionPoint.copyFrom(p2);
  15628. }
  15629. this.basePoint.subtractToRef(p3, this._tempVector);
  15630. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15631. c = this._tempVector.lengthSquared() - 1.0;
  15632. lowestRoot = getLowestRoot(a, b, c, t);
  15633. if (lowestRoot.found) {
  15634. t = lowestRoot.root;
  15635. found = true;
  15636. this._collisionPoint.copyFrom(p3);
  15637. }
  15638. p2.subtractToRef(p1, this._edge);
  15639. p1.subtractToRef(this.basePoint, this._baseToVertex);
  15640. var edgeSquaredLength = this._edge.lengthSquared();
  15641. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15642. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15643. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15644. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15645. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15646. lowestRoot = getLowestRoot(a, b, c, t);
  15647. if (lowestRoot.found) {
  15648. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15649. if (f >= 0.0 && f <= 1.0) {
  15650. t = lowestRoot.root;
  15651. found = true;
  15652. this._edge.scaleInPlace(f);
  15653. p1.addToRef(this._edge, this._collisionPoint);
  15654. }
  15655. }
  15656. p3.subtractToRef(p2, this._edge);
  15657. p2.subtractToRef(this.basePoint, this._baseToVertex);
  15658. edgeSquaredLength = this._edge.lengthSquared();
  15659. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15660. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15661. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15662. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15663. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15664. lowestRoot = getLowestRoot(a, b, c, t);
  15665. if (lowestRoot.found) {
  15666. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15667. if (f >= 0.0 && f <= 1.0) {
  15668. t = lowestRoot.root;
  15669. found = true;
  15670. this._edge.scaleInPlace(f);
  15671. p2.addToRef(this._edge, this._collisionPoint);
  15672. }
  15673. }
  15674. p1.subtractToRef(p3, this._edge);
  15675. p3.subtractToRef(this.basePoint, this._baseToVertex);
  15676. edgeSquaredLength = this._edge.lengthSquared();
  15677. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15678. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15679. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15680. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15681. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15682. lowestRoot = getLowestRoot(a, b, c, t);
  15683. if (lowestRoot.found) {
  15684. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15685. if (f >= 0.0 && f <= 1.0) {
  15686. t = lowestRoot.root;
  15687. found = true;
  15688. this._edge.scaleInPlace(f);
  15689. p3.addToRef(this._edge, this._collisionPoint);
  15690. }
  15691. }
  15692. }
  15693. if (found) {
  15694. var distToCollision = t * this.velocity.length();
  15695. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  15696. if (!this.intersectionPoint) {
  15697. this.intersectionPoint = this._collisionPoint.clone();
  15698. }
  15699. else {
  15700. this.intersectionPoint.copyFrom(this._collisionPoint);
  15701. }
  15702. this.nearestDistance = distToCollision;
  15703. this.collisionFound = true;
  15704. }
  15705. }
  15706. };
  15707. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  15708. for (var i = indexStart; i < indexEnd; i += 3) {
  15709. var p1 = pts[indices[i] - decal];
  15710. var p2 = pts[indices[i + 1] - decal];
  15711. var p3 = pts[indices[i + 2] - decal];
  15712. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  15713. }
  15714. };
  15715. Collider.prototype._getResponse = function (pos, vel) {
  15716. pos.addToRef(vel, this._destinationPoint);
  15717. vel.scaleInPlace((this.nearestDistance / vel.length()));
  15718. this.basePoint.addToRef(vel, pos);
  15719. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  15720. this._slidePlaneNormal.normalize();
  15721. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  15722. pos.addInPlace(this._displacementVector);
  15723. this.intersectionPoint.addInPlace(this._displacementVector);
  15724. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  15725. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  15726. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  15727. };
  15728. return Collider;
  15729. }());
  15730. BABYLON.Collider = Collider;
  15731. })(BABYLON || (BABYLON = {}));
  15732. //# sourceMappingURL=babylon.collider.js.map
  15733. var BABYLON;
  15734. (function (BABYLON) {
  15735. //WebWorker code will be inserted to this variable.
  15736. BABYLON.CollisionWorker = "";
  15737. var WorkerTaskType;
  15738. (function (WorkerTaskType) {
  15739. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  15740. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  15741. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  15742. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  15743. var WorkerReplyType;
  15744. (function (WorkerReplyType) {
  15745. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  15746. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  15747. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  15748. var CollisionCoordinatorWorker = (function () {
  15749. function CollisionCoordinatorWorker() {
  15750. var _this = this;
  15751. this._scaledPosition = BABYLON.Vector3.Zero();
  15752. this._scaledVelocity = BABYLON.Vector3.Zero();
  15753. this.onMeshUpdated = function (mesh) {
  15754. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  15755. };
  15756. this.onGeometryUpdated = function (geometry) {
  15757. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  15758. };
  15759. this._afterRender = function () {
  15760. if (!_this._init)
  15761. return;
  15762. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  15763. return;
  15764. }
  15765. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  15766. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  15767. if (_this._runningUpdated > 4) {
  15768. return;
  15769. }
  15770. ++_this._runningUpdated;
  15771. var payload = {
  15772. updatedMeshes: _this._addUpdateMeshesList,
  15773. updatedGeometries: _this._addUpdateGeometriesList,
  15774. removedGeometries: _this._toRemoveGeometryArray,
  15775. removedMeshes: _this._toRemoveMeshesArray
  15776. };
  15777. var message = {
  15778. payload: payload,
  15779. taskType: WorkerTaskType.UPDATE
  15780. };
  15781. var serializable = [];
  15782. for (var id in payload.updatedGeometries) {
  15783. if (payload.updatedGeometries.hasOwnProperty(id)) {
  15784. //prepare transferables
  15785. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  15786. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  15787. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  15788. }
  15789. }
  15790. _this._worker.postMessage(message, serializable);
  15791. _this._addUpdateMeshesList = {};
  15792. _this._addUpdateGeometriesList = {};
  15793. _this._toRemoveGeometryArray = [];
  15794. _this._toRemoveMeshesArray = [];
  15795. };
  15796. this._onMessageFromWorker = function (e) {
  15797. var returnData = e.data;
  15798. if (returnData.error != WorkerReplyType.SUCCESS) {
  15799. //TODO what errors can be returned from the worker?
  15800. BABYLON.Tools.Warn("error returned from worker!");
  15801. return;
  15802. }
  15803. switch (returnData.taskType) {
  15804. case WorkerTaskType.INIT:
  15805. _this._init = true;
  15806. //Update the worked with ALL of the scene's current state
  15807. _this._scene.meshes.forEach(function (mesh) {
  15808. _this.onMeshAdded(mesh);
  15809. });
  15810. _this._scene.getGeometries().forEach(function (geometry) {
  15811. _this.onGeometryAdded(geometry);
  15812. });
  15813. break;
  15814. case WorkerTaskType.UPDATE:
  15815. _this._runningUpdated--;
  15816. break;
  15817. case WorkerTaskType.COLLIDE:
  15818. _this._runningCollisionTask = false;
  15819. var returnPayload = returnData.payload;
  15820. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  15821. return;
  15822. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  15823. //cleanup
  15824. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  15825. break;
  15826. }
  15827. };
  15828. this._collisionsCallbackArray = [];
  15829. this._init = false;
  15830. this._runningUpdated = 0;
  15831. this._runningCollisionTask = false;
  15832. this._addUpdateMeshesList = {};
  15833. this._addUpdateGeometriesList = {};
  15834. this._toRemoveGeometryArray = [];
  15835. this._toRemoveMeshesArray = [];
  15836. }
  15837. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15838. if (!this._init)
  15839. return;
  15840. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  15841. return;
  15842. position.divideToRef(collider.radius, this._scaledPosition);
  15843. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15844. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  15845. var payload = {
  15846. collider: {
  15847. position: this._scaledPosition.asArray(),
  15848. velocity: this._scaledVelocity.asArray(),
  15849. radius: collider.radius.asArray()
  15850. },
  15851. collisionId: collisionIndex,
  15852. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  15853. maximumRetry: maximumRetry
  15854. };
  15855. var message = {
  15856. payload: payload,
  15857. taskType: WorkerTaskType.COLLIDE
  15858. };
  15859. this._worker.postMessage(message);
  15860. };
  15861. CollisionCoordinatorWorker.prototype.init = function (scene) {
  15862. this._scene = scene;
  15863. this._scene.registerAfterRender(this._afterRender);
  15864. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  15865. this._worker = new Worker(workerUrl);
  15866. this._worker.onmessage = this._onMessageFromWorker;
  15867. var message = {
  15868. payload: {},
  15869. taskType: WorkerTaskType.INIT
  15870. };
  15871. this._worker.postMessage(message);
  15872. };
  15873. CollisionCoordinatorWorker.prototype.destroy = function () {
  15874. this._scene.unregisterAfterRender(this._afterRender);
  15875. this._worker.terminate();
  15876. };
  15877. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  15878. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  15879. this.onMeshUpdated(mesh);
  15880. };
  15881. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  15882. this._toRemoveMeshesArray.push(mesh.uniqueId);
  15883. };
  15884. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  15885. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  15886. geometry.onGeometryUpdated = this.onGeometryUpdated;
  15887. this.onGeometryUpdated(geometry);
  15888. };
  15889. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  15890. this._toRemoveGeometryArray.push(geometry.id);
  15891. };
  15892. return CollisionCoordinatorWorker;
  15893. }());
  15894. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  15895. var submeshes = [];
  15896. if (mesh.subMeshes) {
  15897. submeshes = mesh.subMeshes.map(function (sm, idx) {
  15898. return {
  15899. position: idx,
  15900. verticesStart: sm.verticesStart,
  15901. verticesCount: sm.verticesCount,
  15902. indexStart: sm.indexStart,
  15903. indexCount: sm.indexCount,
  15904. hasMaterial: !!sm.getMaterial(),
  15905. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15906. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  15907. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15908. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  15909. };
  15910. });
  15911. }
  15912. var geometryId = null;
  15913. if (mesh instanceof BABYLON.Mesh) {
  15914. geometryId = mesh.geometry ? mesh.geometry.id : null;
  15915. }
  15916. else if (mesh instanceof BABYLON.InstancedMesh) {
  15917. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  15918. }
  15919. return {
  15920. uniqueId: mesh.uniqueId,
  15921. id: mesh.id,
  15922. name: mesh.name,
  15923. geometryId: geometryId,
  15924. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15925. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  15926. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15927. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  15928. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  15929. subMeshes: submeshes,
  15930. checkCollisions: mesh.checkCollisions
  15931. };
  15932. };
  15933. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  15934. return {
  15935. id: geometry.id,
  15936. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  15937. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  15938. indices: new Uint32Array(geometry.getIndices() || []),
  15939. };
  15940. };
  15941. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  15942. var CollisionCoordinatorLegacy = (function () {
  15943. function CollisionCoordinatorLegacy() {
  15944. this._scaledPosition = BABYLON.Vector3.Zero();
  15945. this._scaledVelocity = BABYLON.Vector3.Zero();
  15946. this._finalPosition = BABYLON.Vector3.Zero();
  15947. }
  15948. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15949. position.divideToRef(collider.radius, this._scaledPosition);
  15950. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15951. collider.collidedMesh = null;
  15952. collider.retry = 0;
  15953. collider.initialVelocity = this._scaledVelocity;
  15954. collider.initialPosition = this._scaledPosition;
  15955. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  15956. this._finalPosition.multiplyInPlace(collider.radius);
  15957. //run the callback
  15958. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  15959. };
  15960. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  15961. this._scene = scene;
  15962. };
  15963. CollisionCoordinatorLegacy.prototype.destroy = function () {
  15964. //Legacy need no destruction method.
  15965. };
  15966. //No update in legacy mode
  15967. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  15968. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  15969. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  15970. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  15971. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  15972. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  15973. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  15974. if (excludedMesh === void 0) { excludedMesh = null; }
  15975. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  15976. if (collider.retry >= maximumRetry) {
  15977. finalPosition.copyFrom(position);
  15978. return;
  15979. }
  15980. // Check if this is a mesh else camera or -1
  15981. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  15982. collider._initialize(position, velocity, closeDistance);
  15983. // Check all meshes
  15984. for (var index = 0; index < this._scene.meshes.length; index++) {
  15985. var mesh = this._scene.meshes[index];
  15986. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  15987. mesh._checkCollision(collider);
  15988. }
  15989. }
  15990. if (!collider.collisionFound) {
  15991. position.addToRef(velocity, finalPosition);
  15992. return;
  15993. }
  15994. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  15995. collider._getResponse(position, velocity);
  15996. }
  15997. if (velocity.length() <= closeDistance) {
  15998. finalPosition.copyFrom(position);
  15999. return;
  16000. }
  16001. collider.retry++;
  16002. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  16003. };
  16004. return CollisionCoordinatorLegacy;
  16005. }());
  16006. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  16007. })(BABYLON || (BABYLON = {}));
  16008. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  16009. var BABYLON;
  16010. (function (BABYLON) {
  16011. var Camera = (function (_super) {
  16012. __extends(Camera, _super);
  16013. function Camera(name, position, scene) {
  16014. var _this = _super.call(this, name, scene) || this;
  16015. _this.upVector = BABYLON.Vector3.Up();
  16016. _this.orthoLeft = null;
  16017. _this.orthoRight = null;
  16018. _this.orthoBottom = null;
  16019. _this.orthoTop = null;
  16020. _this.fov = 0.8;
  16021. _this.minZ = 1.0;
  16022. _this.maxZ = 10000.0;
  16023. _this.inertia = 0.9;
  16024. _this.mode = Camera.PERSPECTIVE_CAMERA;
  16025. _this.isIntermediate = false;
  16026. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  16027. _this.layerMask = 0x0FFFFFFF;
  16028. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  16029. // Camera rig members
  16030. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  16031. _this._rigCameras = new Array();
  16032. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  16033. // Cache
  16034. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  16035. _this._projectionMatrix = new BABYLON.Matrix();
  16036. _this._doNotComputeProjectionMatrix = false;
  16037. _this._postProcesses = new Array();
  16038. _this._transformMatrix = BABYLON.Matrix.Zero();
  16039. _this._activeMeshes = new BABYLON.SmartArray(256);
  16040. _this._globalPosition = BABYLON.Vector3.Zero();
  16041. _this._refreshFrustumPlanes = true;
  16042. _this.getScene().addCamera(_this);
  16043. if (!_this.getScene().activeCamera) {
  16044. _this.getScene().activeCamera = _this;
  16045. }
  16046. _this.position = position;
  16047. return _this;
  16048. }
  16049. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  16050. get: function () {
  16051. return Camera._PERSPECTIVE_CAMERA;
  16052. },
  16053. enumerable: true,
  16054. configurable: true
  16055. });
  16056. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  16057. get: function () {
  16058. return Camera._ORTHOGRAPHIC_CAMERA;
  16059. },
  16060. enumerable: true,
  16061. configurable: true
  16062. });
  16063. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  16064. get: function () {
  16065. return Camera._FOVMODE_VERTICAL_FIXED;
  16066. },
  16067. enumerable: true,
  16068. configurable: true
  16069. });
  16070. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  16071. get: function () {
  16072. return Camera._FOVMODE_HORIZONTAL_FIXED;
  16073. },
  16074. enumerable: true,
  16075. configurable: true
  16076. });
  16077. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  16078. get: function () {
  16079. return Camera._RIG_MODE_NONE;
  16080. },
  16081. enumerable: true,
  16082. configurable: true
  16083. });
  16084. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  16085. get: function () {
  16086. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  16087. },
  16088. enumerable: true,
  16089. configurable: true
  16090. });
  16091. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  16092. get: function () {
  16093. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  16094. },
  16095. enumerable: true,
  16096. configurable: true
  16097. });
  16098. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  16099. get: function () {
  16100. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16101. },
  16102. enumerable: true,
  16103. configurable: true
  16104. });
  16105. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  16106. get: function () {
  16107. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  16108. },
  16109. enumerable: true,
  16110. configurable: true
  16111. });
  16112. Object.defineProperty(Camera, "RIG_MODE_VR", {
  16113. get: function () {
  16114. return Camera._RIG_MODE_VR;
  16115. },
  16116. enumerable: true,
  16117. configurable: true
  16118. });
  16119. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  16120. get: function () {
  16121. return Camera._RIG_MODE_WEBVR;
  16122. },
  16123. enumerable: true,
  16124. configurable: true
  16125. });
  16126. Camera.prototype.getClassName = function () {
  16127. return "Camera";
  16128. };
  16129. /**
  16130. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16131. */
  16132. Camera.prototype.toString = function (fullDetails) {
  16133. var ret = "Name: " + this.name;
  16134. ret += ", type: " + this.getClassName();
  16135. if (this.animations) {
  16136. for (var i = 0; i < this.animations.length; i++) {
  16137. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16138. }
  16139. }
  16140. if (fullDetails) {
  16141. }
  16142. return ret;
  16143. };
  16144. Object.defineProperty(Camera.prototype, "globalPosition", {
  16145. get: function () {
  16146. return this._globalPosition;
  16147. },
  16148. enumerable: true,
  16149. configurable: true
  16150. });
  16151. Camera.prototype.getActiveMeshes = function () {
  16152. return this._activeMeshes;
  16153. };
  16154. Camera.prototype.isActiveMesh = function (mesh) {
  16155. return (this._activeMeshes.indexOf(mesh) !== -1);
  16156. };
  16157. //Cache
  16158. Camera.prototype._initCache = function () {
  16159. _super.prototype._initCache.call(this);
  16160. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16161. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16162. this._cache.mode = undefined;
  16163. this._cache.minZ = undefined;
  16164. this._cache.maxZ = undefined;
  16165. this._cache.fov = undefined;
  16166. this._cache.fovMode = undefined;
  16167. this._cache.aspectRatio = undefined;
  16168. this._cache.orthoLeft = undefined;
  16169. this._cache.orthoRight = undefined;
  16170. this._cache.orthoBottom = undefined;
  16171. this._cache.orthoTop = undefined;
  16172. this._cache.renderWidth = undefined;
  16173. this._cache.renderHeight = undefined;
  16174. };
  16175. Camera.prototype._updateCache = function (ignoreParentClass) {
  16176. if (!ignoreParentClass) {
  16177. _super.prototype._updateCache.call(this);
  16178. }
  16179. var engine = this.getEngine();
  16180. this._cache.position.copyFrom(this.position);
  16181. this._cache.upVector.copyFrom(this.upVector);
  16182. this._cache.mode = this.mode;
  16183. this._cache.minZ = this.minZ;
  16184. this._cache.maxZ = this.maxZ;
  16185. this._cache.fov = this.fov;
  16186. this._cache.fovMode = this.fovMode;
  16187. this._cache.aspectRatio = engine.getAspectRatio(this);
  16188. this._cache.orthoLeft = this.orthoLeft;
  16189. this._cache.orthoRight = this.orthoRight;
  16190. this._cache.orthoBottom = this.orthoBottom;
  16191. this._cache.orthoTop = this.orthoTop;
  16192. this._cache.renderWidth = engine.getRenderWidth();
  16193. this._cache.renderHeight = engine.getRenderHeight();
  16194. };
  16195. Camera.prototype._updateFromScene = function () {
  16196. this.updateCache();
  16197. this.update();
  16198. };
  16199. // Synchronized
  16200. Camera.prototype._isSynchronized = function () {
  16201. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16202. };
  16203. Camera.prototype._isSynchronizedViewMatrix = function () {
  16204. if (!_super.prototype._isSynchronized.call(this))
  16205. return false;
  16206. return this._cache.position.equals(this.position)
  16207. && this._cache.upVector.equals(this.upVector)
  16208. && this.isSynchronizedWithParent();
  16209. };
  16210. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16211. var check = this._cache.mode === this.mode
  16212. && this._cache.minZ === this.minZ
  16213. && this._cache.maxZ === this.maxZ;
  16214. if (!check) {
  16215. return false;
  16216. }
  16217. var engine = this.getEngine();
  16218. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16219. check = this._cache.fov === this.fov
  16220. && this._cache.fovMode === this.fovMode
  16221. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16222. }
  16223. else {
  16224. check = this._cache.orthoLeft === this.orthoLeft
  16225. && this._cache.orthoRight === this.orthoRight
  16226. && this._cache.orthoBottom === this.orthoBottom
  16227. && this._cache.orthoTop === this.orthoTop
  16228. && this._cache.renderWidth === engine.getRenderWidth()
  16229. && this._cache.renderHeight === engine.getRenderHeight();
  16230. }
  16231. return check;
  16232. };
  16233. // Controls
  16234. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16235. };
  16236. Camera.prototype.detachControl = function (element) {
  16237. };
  16238. Camera.prototype.update = function () {
  16239. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16240. this._updateRigCameras();
  16241. }
  16242. this._checkInputs();
  16243. };
  16244. Camera.prototype._checkInputs = function () {
  16245. };
  16246. Object.defineProperty(Camera.prototype, "rigCameras", {
  16247. get: function () {
  16248. return this._rigCameras;
  16249. },
  16250. enumerable: true,
  16251. configurable: true
  16252. });
  16253. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16254. get: function () {
  16255. return this._rigPostProcess;
  16256. },
  16257. enumerable: true,
  16258. configurable: true
  16259. });
  16260. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16261. // invalidate framebuffer
  16262. if (this._postProcesses.length > 0) {
  16263. this._postProcesses[0].markTextureDirty();
  16264. }
  16265. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16266. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16267. var cam = this._rigCameras[i];
  16268. var rigPostProcess = cam._rigPostProcess;
  16269. // for VR rig, there does not have to be a post process
  16270. if (rigPostProcess) {
  16271. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16272. if (isPass) {
  16273. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16274. cam.isIntermediate = this._postProcesses.length === 0;
  16275. }
  16276. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16277. rigPostProcess.markTextureDirty();
  16278. }
  16279. else {
  16280. cam._postProcesses = this._postProcesses.slice(0);
  16281. }
  16282. }
  16283. };
  16284. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16285. if (insertAt === void 0) { insertAt = null; }
  16286. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16287. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16288. return 0;
  16289. }
  16290. if (insertAt == null || insertAt < 0) {
  16291. this._postProcesses.push(postProcess);
  16292. }
  16293. else {
  16294. this._postProcesses.splice(insertAt, 0, postProcess);
  16295. }
  16296. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16297. return this._postProcesses.indexOf(postProcess);
  16298. };
  16299. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  16300. if (atIndices === void 0) { atIndices = null; }
  16301. var result = [];
  16302. var i;
  16303. var index;
  16304. if (!atIndices) {
  16305. var idx = this._postProcesses.indexOf(postProcess);
  16306. if (idx !== -1) {
  16307. this._postProcesses.splice(idx, 1);
  16308. }
  16309. }
  16310. else {
  16311. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  16312. // iterate descending, so can just splice as we go
  16313. for (i = atIndices.length - 1; i >= 0; i--) {
  16314. if (this._postProcesses[atIndices[i]] !== postProcess) {
  16315. result.push(i);
  16316. continue;
  16317. }
  16318. index = atIndices[i];
  16319. this._postProcesses.splice(index, 1);
  16320. }
  16321. }
  16322. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16323. return result;
  16324. };
  16325. Camera.prototype.getWorldMatrix = function () {
  16326. if (!this._worldMatrix) {
  16327. this._worldMatrix = BABYLON.Matrix.Identity();
  16328. }
  16329. var viewMatrix = this.getViewMatrix();
  16330. viewMatrix.invertToRef(this._worldMatrix);
  16331. return this._worldMatrix;
  16332. };
  16333. Camera.prototype._getViewMatrix = function () {
  16334. return BABYLON.Matrix.Identity();
  16335. };
  16336. Camera.prototype.getViewMatrix = function (force) {
  16337. this._computedViewMatrix = this._computeViewMatrix(force);
  16338. if (!force && this._isSynchronizedViewMatrix()) {
  16339. return this._computedViewMatrix;
  16340. }
  16341. this._refreshFrustumPlanes = true;
  16342. if (!this.parent || !this.parent.getWorldMatrix) {
  16343. this._globalPosition.copyFrom(this.position);
  16344. }
  16345. else {
  16346. if (!this._worldMatrix) {
  16347. this._worldMatrix = BABYLON.Matrix.Identity();
  16348. }
  16349. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16350. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16351. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16352. this._computedViewMatrix.invert();
  16353. this._markSyncedWithParent();
  16354. }
  16355. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16356. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16357. }
  16358. this._currentRenderId = this.getScene().getRenderId();
  16359. return this._computedViewMatrix;
  16360. };
  16361. Camera.prototype._computeViewMatrix = function (force) {
  16362. if (!force && this._isSynchronizedViewMatrix()) {
  16363. return this._computedViewMatrix;
  16364. }
  16365. this._computedViewMatrix = this._getViewMatrix();
  16366. this._currentRenderId = this.getScene().getRenderId();
  16367. return this._computedViewMatrix;
  16368. };
  16369. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16370. this._doNotComputeProjectionMatrix = true;
  16371. if (projection !== undefined) {
  16372. this._projectionMatrix = projection;
  16373. }
  16374. };
  16375. ;
  16376. Camera.prototype.unfreezeProjectionMatrix = function () {
  16377. this._doNotComputeProjectionMatrix = false;
  16378. };
  16379. ;
  16380. Camera.prototype.getProjectionMatrix = function (force) {
  16381. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16382. return this._projectionMatrix;
  16383. }
  16384. this._refreshFrustumPlanes = true;
  16385. var engine = this.getEngine();
  16386. var scene = this.getScene();
  16387. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16388. if (this.minZ <= 0) {
  16389. this.minZ = 0.1;
  16390. }
  16391. if (scene.useRightHandedSystem) {
  16392. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16393. }
  16394. else {
  16395. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16396. }
  16397. return this._projectionMatrix;
  16398. }
  16399. var halfWidth = engine.getRenderWidth() / 2.0;
  16400. var halfHeight = engine.getRenderHeight() / 2.0;
  16401. if (scene.useRightHandedSystem) {
  16402. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16403. }
  16404. else {
  16405. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16406. }
  16407. return this._projectionMatrix;
  16408. };
  16409. Camera.prototype.getTranformationMatrix = function () {
  16410. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16411. return this._transformMatrix;
  16412. };
  16413. Camera.prototype.updateFrustumPlanes = function () {
  16414. if (!this._refreshFrustumPlanes) {
  16415. return;
  16416. }
  16417. this.getTranformationMatrix();
  16418. if (!this._frustumPlanes) {
  16419. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16420. }
  16421. else {
  16422. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16423. }
  16424. this._refreshFrustumPlanes = false;
  16425. };
  16426. Camera.prototype.isInFrustum = function (target) {
  16427. this.updateFrustumPlanes();
  16428. return target.isInFrustum(this._frustumPlanes);
  16429. };
  16430. Camera.prototype.isCompletelyInFrustum = function (target) {
  16431. this.updateFrustumPlanes();
  16432. return target.isCompletelyInFrustum(this._frustumPlanes);
  16433. };
  16434. Camera.prototype.dispose = function () {
  16435. // Animations
  16436. this.getScene().stopAnimation(this);
  16437. // Remove from scene
  16438. this.getScene().removeCamera(this);
  16439. while (this._rigCameras.length > 0) {
  16440. this._rigCameras.pop().dispose();
  16441. }
  16442. // Postprocesses
  16443. var i = this._postProcesses.length;
  16444. while (--i >= 0) {
  16445. this._postProcesses[i].dispose(this);
  16446. }
  16447. _super.prototype.dispose.call(this);
  16448. };
  16449. // ---- Camera rigs section ----
  16450. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16451. while (this._rigCameras.length > 0) {
  16452. this._rigCameras.pop().dispose();
  16453. }
  16454. this.cameraRigMode = mode;
  16455. this._cameraRigParams = {};
  16456. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16457. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16458. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16459. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16460. // create the rig cameras, unless none
  16461. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16462. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  16463. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  16464. }
  16465. switch (this.cameraRigMode) {
  16466. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16467. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16468. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16469. break;
  16470. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16471. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16472. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16473. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16474. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16475. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16476. break;
  16477. case Camera.RIG_MODE_VR:
  16478. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16479. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16480. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16481. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16482. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16483. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16484. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16485. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16486. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16487. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16488. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16489. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16490. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16491. if (metrics.compensateDistortion) {
  16492. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16493. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16494. }
  16495. break;
  16496. case Camera.RIG_MODE_WEBVR:
  16497. if (rigParams.vrDisplay) {
  16498. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16499. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16500. //Left eye
  16501. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16502. this._rigCameras[0].setCameraRigParameter("left", true);
  16503. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16504. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16505. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16506. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16507. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16508. this._rigCameras[0].parent = this;
  16509. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16510. //Right eye
  16511. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16512. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16513. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16514. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16515. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16516. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16517. this._rigCameras[1].parent = this;
  16518. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16519. }
  16520. break;
  16521. }
  16522. this._cascadePostProcessesToRigCams();
  16523. this.
  16524. update();
  16525. };
  16526. Camera.prototype._getVRProjectionMatrix = function () {
  16527. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16528. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16529. return this._projectionMatrix;
  16530. };
  16531. Camera.prototype._updateCameraRotationMatrix = function () {
  16532. //Here for WebVR
  16533. };
  16534. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16535. //Here for WebVR
  16536. };
  16537. /**
  16538. * This function MUST be overwritten by the different WebVR cameras available.
  16539. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16540. */
  16541. Camera.prototype._getWebVRProjectionMatrix = function () {
  16542. return BABYLON.Matrix.Identity();
  16543. };
  16544. /**
  16545. * This function MUST be overwritten by the different WebVR cameras available.
  16546. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16547. */
  16548. Camera.prototype._getWebVRViewMatrix = function () {
  16549. return BABYLON.Matrix.Identity();
  16550. };
  16551. Camera.prototype.setCameraRigParameter = function (name, value) {
  16552. if (!this._cameraRigParams) {
  16553. this._cameraRigParams = {};
  16554. }
  16555. this._cameraRigParams[name] = value;
  16556. //provisionnally:
  16557. if (name === "interaxialDistance") {
  16558. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16559. }
  16560. };
  16561. /**
  16562. * needs to be overridden by children so sub has required properties to be copied
  16563. */
  16564. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16565. return null;
  16566. };
  16567. /**
  16568. * May need to be overridden by children
  16569. */
  16570. Camera.prototype._updateRigCameras = function () {
  16571. for (var i = 0; i < this._rigCameras.length; i++) {
  16572. this._rigCameras[i].minZ = this.minZ;
  16573. this._rigCameras[i].maxZ = this.maxZ;
  16574. this._rigCameras[i].fov = this.fov;
  16575. }
  16576. // only update viewport when ANAGLYPH
  16577. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16578. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16579. }
  16580. };
  16581. Camera.prototype._setupInputs = function () {
  16582. };
  16583. Camera.prototype.serialize = function () {
  16584. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16585. // Type
  16586. serializationObject.type = this.getClassName();
  16587. // Parent
  16588. if (this.parent) {
  16589. serializationObject.parentId = this.parent.id;
  16590. }
  16591. if (this.inputs) {
  16592. this.inputs.serialize(serializationObject);
  16593. }
  16594. // Animations
  16595. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16596. serializationObject.ranges = this.serializeAnimationRanges();
  16597. return serializationObject;
  16598. };
  16599. Camera.prototype.clone = function (name) {
  16600. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16601. };
  16602. Camera.prototype.getDirection = function (localAxis) {
  16603. var result = BABYLON.Vector3.Zero();
  16604. this.getDirectionToRef(localAxis, result);
  16605. return result;
  16606. };
  16607. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16608. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16609. };
  16610. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16611. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16612. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16613. switch (type) {
  16614. case "ArcRotateCamera":
  16615. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16616. case "DeviceOrientationCamera":
  16617. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16618. case "FollowCamera":
  16619. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16620. case "ArcFollowCamera":
  16621. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16622. case "GamepadCamera":
  16623. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16624. case "TouchCamera":
  16625. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16626. case "VirtualJoysticksCamera":
  16627. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16628. case "WebVRFreeCamera":
  16629. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16630. case "WebVRGamepadCamera":
  16631. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16632. case "VRDeviceOrientationFreeCamera":
  16633. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16634. case "VRDeviceOrientationGamepadCamera":
  16635. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16636. case "AnaglyphArcRotateCamera":
  16637. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16638. case "AnaglyphFreeCamera":
  16639. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16640. case "AnaglyphGamepadCamera":
  16641. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16642. case "AnaglyphUniversalCamera":
  16643. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16644. case "StereoscopicArcRotateCamera":
  16645. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16646. case "StereoscopicFreeCamera":
  16647. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16648. case "StereoscopicGamepadCamera":
  16649. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16650. case "StereoscopicUniversalCamera":
  16651. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16652. case "FreeCamera":
  16653. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16654. default:
  16655. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16656. }
  16657. };
  16658. Camera.Parse = function (parsedCamera, scene) {
  16659. var type = parsedCamera.type;
  16660. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16661. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16662. // Parent
  16663. if (parsedCamera.parentId) {
  16664. camera._waitingParentId = parsedCamera.parentId;
  16665. }
  16666. //If camera has an input manager, let it parse inputs settings
  16667. if (camera.inputs) {
  16668. camera.inputs.parse(parsedCamera);
  16669. camera._setupInputs();
  16670. }
  16671. // Target
  16672. if (parsedCamera.target) {
  16673. if (camera.setTarget) {
  16674. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16675. }
  16676. }
  16677. // Apply 3d rig, when found
  16678. if (parsedCamera.cameraRigMode) {
  16679. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16680. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16681. }
  16682. // Animations
  16683. if (parsedCamera.animations) {
  16684. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16685. var parsedAnimation = parsedCamera.animations[animationIndex];
  16686. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16687. }
  16688. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16689. }
  16690. if (parsedCamera.autoAnimate) {
  16691. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16692. }
  16693. return camera;
  16694. };
  16695. return Camera;
  16696. }(BABYLON.Node));
  16697. // Statics
  16698. Camera._PERSPECTIVE_CAMERA = 0;
  16699. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16700. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16701. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16702. Camera._RIG_MODE_NONE = 0;
  16703. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16704. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16705. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16706. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16707. Camera._RIG_MODE_VR = 20;
  16708. Camera._RIG_MODE_WEBVR = 21;
  16709. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16710. __decorate([
  16711. BABYLON.serializeAsVector3()
  16712. ], Camera.prototype, "position", void 0);
  16713. __decorate([
  16714. BABYLON.serializeAsVector3()
  16715. ], Camera.prototype, "upVector", void 0);
  16716. __decorate([
  16717. BABYLON.serialize()
  16718. ], Camera.prototype, "orthoLeft", void 0);
  16719. __decorate([
  16720. BABYLON.serialize()
  16721. ], Camera.prototype, "orthoRight", void 0);
  16722. __decorate([
  16723. BABYLON.serialize()
  16724. ], Camera.prototype, "orthoBottom", void 0);
  16725. __decorate([
  16726. BABYLON.serialize()
  16727. ], Camera.prototype, "orthoTop", void 0);
  16728. __decorate([
  16729. BABYLON.serialize()
  16730. ], Camera.prototype, "fov", void 0);
  16731. __decorate([
  16732. BABYLON.serialize()
  16733. ], Camera.prototype, "minZ", void 0);
  16734. __decorate([
  16735. BABYLON.serialize()
  16736. ], Camera.prototype, "maxZ", void 0);
  16737. __decorate([
  16738. BABYLON.serialize()
  16739. ], Camera.prototype, "inertia", void 0);
  16740. __decorate([
  16741. BABYLON.serialize()
  16742. ], Camera.prototype, "mode", void 0);
  16743. __decorate([
  16744. BABYLON.serialize()
  16745. ], Camera.prototype, "layerMask", void 0);
  16746. __decorate([
  16747. BABYLON.serialize()
  16748. ], Camera.prototype, "fovMode", void 0);
  16749. __decorate([
  16750. BABYLON.serialize()
  16751. ], Camera.prototype, "cameraRigMode", void 0);
  16752. __decorate([
  16753. BABYLON.serialize()
  16754. ], Camera.prototype, "interaxialDistance", void 0);
  16755. __decorate([
  16756. BABYLON.serialize()
  16757. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16758. BABYLON.Camera = Camera;
  16759. })(BABYLON || (BABYLON = {}));
  16760. //# sourceMappingURL=babylon.camera.js.map
  16761. var BABYLON;
  16762. (function (BABYLON) {
  16763. BABYLON.CameraInputTypes = {};
  16764. var CameraInputsManager = (function () {
  16765. function CameraInputsManager(camera) {
  16766. this.attached = {};
  16767. this.camera = camera;
  16768. this.checkInputs = function () { };
  16769. }
  16770. CameraInputsManager.prototype.add = function (input) {
  16771. var type = input.getSimpleName();
  16772. if (this.attached[type]) {
  16773. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  16774. return;
  16775. }
  16776. this.attached[type] = input;
  16777. input.camera = this.camera;
  16778. //for checkInputs, we are dynamically creating a function
  16779. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  16780. if (input.checkInputs) {
  16781. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16782. }
  16783. if (this.attachedElement) {
  16784. input.attachControl(this.attachedElement);
  16785. }
  16786. };
  16787. CameraInputsManager.prototype.remove = function (inputToRemove) {
  16788. for (var cam in this.attached) {
  16789. var input = this.attached[cam];
  16790. if (input === inputToRemove) {
  16791. input.detachControl(this.attachedElement);
  16792. delete this.attached[cam];
  16793. this.rebuildInputCheck();
  16794. }
  16795. }
  16796. };
  16797. CameraInputsManager.prototype.removeByType = function (inputType) {
  16798. for (var cam in this.attached) {
  16799. var input = this.attached[cam];
  16800. if (input.getTypeName() === inputType) {
  16801. input.detachControl(this.attachedElement);
  16802. delete this.attached[cam];
  16803. this.rebuildInputCheck();
  16804. }
  16805. }
  16806. };
  16807. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  16808. var current = this.checkInputs;
  16809. return function () {
  16810. current();
  16811. fn();
  16812. };
  16813. };
  16814. CameraInputsManager.prototype.attachInput = function (input) {
  16815. input.attachControl(this.attachedElement, this.noPreventDefault);
  16816. };
  16817. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  16818. if (this.attachedElement) {
  16819. return;
  16820. }
  16821. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  16822. this.attachedElement = element;
  16823. this.noPreventDefault = noPreventDefault;
  16824. for (var cam in this.attached) {
  16825. var input = this.attached[cam];
  16826. this.attached[cam].attachControl(element, noPreventDefault);
  16827. }
  16828. };
  16829. CameraInputsManager.prototype.detachElement = function (element) {
  16830. if (this.attachedElement !== element) {
  16831. return;
  16832. }
  16833. for (var cam in this.attached) {
  16834. var input = this.attached[cam];
  16835. this.attached[cam].detachControl(element);
  16836. }
  16837. this.attachedElement = null;
  16838. };
  16839. CameraInputsManager.prototype.rebuildInputCheck = function () {
  16840. this.checkInputs = function () { };
  16841. for (var cam in this.attached) {
  16842. var input = this.attached[cam];
  16843. if (input.checkInputs) {
  16844. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16845. }
  16846. }
  16847. };
  16848. CameraInputsManager.prototype.clear = function () {
  16849. if (this.attachedElement) {
  16850. this.detachElement(this.attachedElement);
  16851. }
  16852. this.attached = {};
  16853. this.attachedElement = null;
  16854. this.checkInputs = function () { };
  16855. };
  16856. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  16857. var inputs = {};
  16858. for (var cam in this.attached) {
  16859. var input = this.attached[cam];
  16860. var res = BABYLON.SerializationHelper.Serialize(input);
  16861. inputs[input.getTypeName()] = res;
  16862. }
  16863. serializedCamera.inputsmgr = inputs;
  16864. };
  16865. CameraInputsManager.prototype.parse = function (parsedCamera) {
  16866. var parsedInputs = parsedCamera.inputsmgr;
  16867. if (parsedInputs) {
  16868. this.clear();
  16869. for (var n in parsedInputs) {
  16870. var construct = BABYLON.CameraInputTypes[n];
  16871. if (construct) {
  16872. var parsedinput = parsedInputs[n];
  16873. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  16874. this.add(input);
  16875. }
  16876. }
  16877. }
  16878. else {
  16879. //2016-03-08 this part is for managing backward compatibility
  16880. for (var n in this.attached) {
  16881. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  16882. if (construct) {
  16883. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  16884. this.remove(this.attached[n]);
  16885. this.add(input);
  16886. }
  16887. }
  16888. }
  16889. };
  16890. return CameraInputsManager;
  16891. }());
  16892. BABYLON.CameraInputsManager = CameraInputsManager;
  16893. })(BABYLON || (BABYLON = {}));
  16894. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  16895. var BABYLON;
  16896. (function (BABYLON) {
  16897. var FreeCameraMouseInput = (function () {
  16898. function FreeCameraMouseInput(touchEnabled) {
  16899. if (touchEnabled === void 0) { touchEnabled = true; }
  16900. this.touchEnabled = touchEnabled;
  16901. this.buttons = [0, 1, 2];
  16902. this.angularSensibility = 2000.0;
  16903. }
  16904. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  16905. var _this = this;
  16906. var engine = this.camera.getEngine();
  16907. if (!this._pointerInput) {
  16908. this._pointerInput = function (p, s) {
  16909. var evt = p.event;
  16910. if (!_this.touchEnabled && evt.pointerType === "touch") {
  16911. return;
  16912. }
  16913. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  16914. return;
  16915. }
  16916. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16917. try {
  16918. evt.srcElement.setPointerCapture(evt.pointerId);
  16919. }
  16920. catch (e) {
  16921. //Nothing to do with the error. Execution will continue.
  16922. }
  16923. _this.previousPosition = {
  16924. x: evt.clientX,
  16925. y: evt.clientY
  16926. };
  16927. if (!noPreventDefault) {
  16928. evt.preventDefault();
  16929. element.focus();
  16930. }
  16931. }
  16932. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16933. try {
  16934. evt.srcElement.releasePointerCapture(evt.pointerId);
  16935. }
  16936. catch (e) {
  16937. //Nothing to do with the error.
  16938. }
  16939. _this.previousPosition = null;
  16940. if (!noPreventDefault) {
  16941. evt.preventDefault();
  16942. }
  16943. }
  16944. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16945. if (!_this.previousPosition || engine.isPointerLock) {
  16946. return;
  16947. }
  16948. var offsetX = evt.clientX - _this.previousPosition.x;
  16949. var offsetY = evt.clientY - _this.previousPosition.y;
  16950. if (_this.camera.getScene().useRightHandedSystem) {
  16951. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16952. }
  16953. else {
  16954. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16955. }
  16956. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16957. _this.previousPosition = {
  16958. x: evt.clientX,
  16959. y: evt.clientY
  16960. };
  16961. if (!noPreventDefault) {
  16962. evt.preventDefault();
  16963. }
  16964. }
  16965. };
  16966. }
  16967. this._onMouseMove = function (evt) {
  16968. if (!engine.isPointerLock) {
  16969. return;
  16970. }
  16971. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  16972. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  16973. if (_this.camera.getScene().useRightHandedSystem) {
  16974. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16975. }
  16976. else {
  16977. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16978. }
  16979. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16980. _this.previousPosition = null;
  16981. if (!noPreventDefault) {
  16982. evt.preventDefault();
  16983. }
  16984. };
  16985. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16986. element.addEventListener("mousemove", this._onMouseMove, false);
  16987. };
  16988. FreeCameraMouseInput.prototype.detachControl = function (element) {
  16989. if (this._observer && element) {
  16990. this.camera.getScene().onPointerObservable.remove(this._observer);
  16991. element.removeEventListener("mousemove", this._onMouseMove);
  16992. this._observer = null;
  16993. this._onMouseMove = null;
  16994. this.previousPosition = null;
  16995. }
  16996. };
  16997. FreeCameraMouseInput.prototype.getTypeName = function () {
  16998. return "FreeCameraMouseInput";
  16999. };
  17000. FreeCameraMouseInput.prototype.getSimpleName = function () {
  17001. return "mouse";
  17002. };
  17003. return FreeCameraMouseInput;
  17004. }());
  17005. __decorate([
  17006. BABYLON.serialize()
  17007. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  17008. __decorate([
  17009. BABYLON.serialize()
  17010. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  17011. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  17012. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  17013. })(BABYLON || (BABYLON = {}));
  17014. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  17015. var BABYLON;
  17016. (function (BABYLON) {
  17017. var FreeCameraKeyboardMoveInput = (function () {
  17018. function FreeCameraKeyboardMoveInput() {
  17019. this._keys = [];
  17020. this.keysUp = [38];
  17021. this.keysDown = [40];
  17022. this.keysLeft = [37];
  17023. this.keysRight = [39];
  17024. }
  17025. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  17026. var _this = this;
  17027. if (!this._onKeyDown) {
  17028. element.tabIndex = 1;
  17029. this._onKeyDown = function (evt) {
  17030. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17031. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17032. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17033. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17034. var index = _this._keys.indexOf(evt.keyCode);
  17035. if (index === -1) {
  17036. _this._keys.push(evt.keyCode);
  17037. }
  17038. if (!noPreventDefault) {
  17039. evt.preventDefault();
  17040. }
  17041. }
  17042. };
  17043. this._onKeyUp = function (evt) {
  17044. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17045. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17046. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17047. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17048. var index = _this._keys.indexOf(evt.keyCode);
  17049. if (index >= 0) {
  17050. _this._keys.splice(index, 1);
  17051. }
  17052. if (!noPreventDefault) {
  17053. evt.preventDefault();
  17054. }
  17055. }
  17056. };
  17057. element.addEventListener("keydown", this._onKeyDown, false);
  17058. element.addEventListener("keyup", this._onKeyUp, false);
  17059. BABYLON.Tools.RegisterTopRootEvents([
  17060. { name: "blur", handler: this._onLostFocus }
  17061. ]);
  17062. }
  17063. };
  17064. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  17065. if (this._onKeyDown) {
  17066. element.removeEventListener("keydown", this._onKeyDown);
  17067. element.removeEventListener("keyup", this._onKeyUp);
  17068. BABYLON.Tools.UnregisterTopRootEvents([
  17069. { name: "blur", handler: this._onLostFocus }
  17070. ]);
  17071. this._keys = [];
  17072. this._onKeyDown = null;
  17073. this._onKeyUp = null;
  17074. }
  17075. };
  17076. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  17077. if (this._onKeyDown) {
  17078. var camera = this.camera;
  17079. // Keyboard
  17080. for (var index = 0; index < this._keys.length; index++) {
  17081. var keyCode = this._keys[index];
  17082. var speed = camera._computeLocalCameraSpeed();
  17083. if (this.keysLeft.indexOf(keyCode) !== -1) {
  17084. camera._localDirection.copyFromFloats(-speed, 0, 0);
  17085. }
  17086. else if (this.keysUp.indexOf(keyCode) !== -1) {
  17087. camera._localDirection.copyFromFloats(0, 0, speed);
  17088. }
  17089. else if (this.keysRight.indexOf(keyCode) !== -1) {
  17090. camera._localDirection.copyFromFloats(speed, 0, 0);
  17091. }
  17092. else if (this.keysDown.indexOf(keyCode) !== -1) {
  17093. camera._localDirection.copyFromFloats(0, 0, -speed);
  17094. }
  17095. if (camera.getScene().useRightHandedSystem) {
  17096. camera._localDirection.z *= -1;
  17097. }
  17098. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  17099. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  17100. camera.cameraDirection.addInPlace(camera._transformedDirection);
  17101. }
  17102. }
  17103. };
  17104. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  17105. return "FreeCameraKeyboardMoveInput";
  17106. };
  17107. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  17108. this._keys = [];
  17109. };
  17110. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  17111. return "keyboard";
  17112. };
  17113. return FreeCameraKeyboardMoveInput;
  17114. }());
  17115. __decorate([
  17116. BABYLON.serialize()
  17117. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  17118. __decorate([
  17119. BABYLON.serialize()
  17120. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  17121. __decorate([
  17122. BABYLON.serialize()
  17123. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  17124. __decorate([
  17125. BABYLON.serialize()
  17126. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  17127. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  17128. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  17129. })(BABYLON || (BABYLON = {}));
  17130. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  17131. var BABYLON;
  17132. (function (BABYLON) {
  17133. var FreeCameraTouchInput = (function () {
  17134. function FreeCameraTouchInput() {
  17135. this._offsetX = null;
  17136. this._offsetY = null;
  17137. this._pointerCount = 0;
  17138. this._pointerPressed = [];
  17139. this.touchAngularSensibility = 200000.0;
  17140. this.touchMoveSensibility = 250.0;
  17141. }
  17142. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  17143. var _this = this;
  17144. var previousPosition;
  17145. if (this._pointerInput === undefined) {
  17146. this._onLostFocus = function (evt) {
  17147. _this._offsetX = null;
  17148. _this._offsetY = null;
  17149. };
  17150. this._pointerInput = function (p, s) {
  17151. var evt = p.event;
  17152. if (evt.pointerType === "mouse") {
  17153. return;
  17154. }
  17155. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  17156. if (!noPreventDefault) {
  17157. evt.preventDefault();
  17158. }
  17159. _this._pointerPressed.push(evt.pointerId);
  17160. if (_this._pointerPressed.length !== 1) {
  17161. return;
  17162. }
  17163. previousPosition = {
  17164. x: evt.clientX,
  17165. y: evt.clientY
  17166. };
  17167. }
  17168. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  17169. if (!noPreventDefault) {
  17170. evt.preventDefault();
  17171. }
  17172. var index = _this._pointerPressed.indexOf(evt.pointerId);
  17173. if (index === -1) {
  17174. return;
  17175. }
  17176. _this._pointerPressed.splice(index, 1);
  17177. if (index != 0) {
  17178. return;
  17179. }
  17180. previousPosition = null;
  17181. _this._offsetX = null;
  17182. _this._offsetY = null;
  17183. }
  17184. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  17185. if (!noPreventDefault) {
  17186. evt.preventDefault();
  17187. }
  17188. if (!previousPosition) {
  17189. return;
  17190. }
  17191. var index = _this._pointerPressed.indexOf(evt.pointerId);
  17192. if (index != 0) {
  17193. return;
  17194. }
  17195. _this._offsetX = evt.clientX - previousPosition.x;
  17196. _this._offsetY = -(evt.clientY - previousPosition.y);
  17197. }
  17198. };
  17199. }
  17200. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  17201. element.addEventListener("blur", this._onLostFocus);
  17202. };
  17203. FreeCameraTouchInput.prototype.detachControl = function (element) {
  17204. if (this._pointerInput && element) {
  17205. this.camera.getScene().onPointerObservable.remove(this._observer);
  17206. this._observer = null;
  17207. element.removeEventListener("blur", this._onLostFocus);
  17208. this._onLostFocus = null;
  17209. this._pointerPressed = [];
  17210. this._offsetX = null;
  17211. this._offsetY = null;
  17212. this._pointerCount = 0;
  17213. }
  17214. };
  17215. FreeCameraTouchInput.prototype.checkInputs = function () {
  17216. if (this._offsetX) {
  17217. var camera = this.camera;
  17218. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  17219. if (this._pointerPressed.length > 1) {
  17220. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  17221. }
  17222. else {
  17223. var speed = camera._computeLocalCameraSpeed();
  17224. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  17225. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  17226. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  17227. }
  17228. }
  17229. };
  17230. FreeCameraTouchInput.prototype.getTypeName = function () {
  17231. return "FreeCameraTouchInput";
  17232. };
  17233. FreeCameraTouchInput.prototype.getSimpleName = function () {
  17234. return "touch";
  17235. };
  17236. return FreeCameraTouchInput;
  17237. }());
  17238. __decorate([
  17239. BABYLON.serialize()
  17240. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  17241. __decorate([
  17242. BABYLON.serialize()
  17243. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  17244. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  17245. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  17246. })(BABYLON || (BABYLON = {}));
  17247. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  17248. var BABYLON;
  17249. (function (BABYLON) {
  17250. var FreeCameraDeviceOrientationInput = (function () {
  17251. function FreeCameraDeviceOrientationInput() {
  17252. var _this = this;
  17253. this._screenOrientationAngle = 0;
  17254. this._screenQuaternion = new BABYLON.Quaternion();
  17255. this._alpha = 0;
  17256. this._beta = 0;
  17257. this._gamma = 0;
  17258. this._orientationChanged = function () {
  17259. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  17260. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  17261. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  17262. };
  17263. this._deviceOrientation = function (evt) {
  17264. _this._alpha = evt.alpha;
  17265. _this._beta = evt.beta;
  17266. _this._gamma = evt.gamma;
  17267. };
  17268. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  17269. this._orientationChanged();
  17270. }
  17271. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  17272. get: function () {
  17273. return this._camera;
  17274. },
  17275. set: function (camera) {
  17276. this._camera = camera;
  17277. if (!this._camera.rotationQuaternion)
  17278. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  17279. },
  17280. enumerable: true,
  17281. configurable: true
  17282. });
  17283. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  17284. window.addEventListener("orientationchange", this._orientationChanged);
  17285. window.addEventListener("deviceorientation", this._deviceOrientation);
  17286. //In certain cases, the attach control is called AFTER orientation was changed,
  17287. //So this is needed.
  17288. this._orientationChanged();
  17289. };
  17290. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  17291. window.removeEventListener("orientationchange", this._orientationChanged);
  17292. window.removeEventListener("deviceorientation", this._deviceOrientation);
  17293. };
  17294. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  17295. //if no device orientation provided, don't update the rotation.
  17296. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  17297. if (!this._alpha)
  17298. return;
  17299. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  17300. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  17301. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  17302. //Mirror on XY Plane
  17303. this._camera.rotationQuaternion.z *= -1;
  17304. this._camera.rotationQuaternion.w *= -1;
  17305. };
  17306. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  17307. return "FreeCameraDeviceOrientationInput";
  17308. };
  17309. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  17310. return "deviceOrientation";
  17311. };
  17312. return FreeCameraDeviceOrientationInput;
  17313. }());
  17314. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  17315. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  17316. })(BABYLON || (BABYLON = {}));
  17317. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  17318. var BABYLON;
  17319. (function (BABYLON) {
  17320. var FreeCameraGamepadInput = (function () {
  17321. function FreeCameraGamepadInput() {
  17322. this.gamepadAngularSensibility = 200;
  17323. this.gamepadMoveSensibility = 40;
  17324. // private members
  17325. this._cameraTransform = BABYLON.Matrix.Identity();
  17326. this._deltaTransform = BABYLON.Vector3.Zero();
  17327. this._vector3 = BABYLON.Vector3.Zero();
  17328. this._vector2 = BABYLON.Vector2.Zero();
  17329. }
  17330. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  17331. var _this = this;
  17332. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  17333. };
  17334. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  17335. if (this._gamepads) {
  17336. this._gamepads.dispose();
  17337. }
  17338. this.gamepad = null;
  17339. };
  17340. FreeCameraGamepadInput.prototype.checkInputs = function () {
  17341. if (this.gamepad && this.gamepad.leftStick) {
  17342. var camera = this.camera;
  17343. var LSValues = this.gamepad.leftStick;
  17344. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  17345. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17346. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  17347. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  17348. var RSValues = this.gamepad.rightStick;
  17349. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  17350. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  17351. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  17352. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  17353. if (!camera.rotationQuaternion) {
  17354. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  17355. }
  17356. else {
  17357. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  17358. }
  17359. var speed = camera._computeLocalCameraSpeed() * 50.0;
  17360. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  17361. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  17362. camera.cameraDirection.addInPlace(this._deltaTransform);
  17363. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  17364. camera.cameraRotation.addInPlace(this._vector2);
  17365. }
  17366. };
  17367. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17368. // Only the first gamepad found can control the camera
  17369. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  17370. // prioritize XBOX gamepads.
  17371. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  17372. this.gamepad = gamepad;
  17373. }
  17374. }
  17375. };
  17376. FreeCameraGamepadInput.prototype.getTypeName = function () {
  17377. return "FreeCameraGamepadInput";
  17378. };
  17379. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  17380. return "gamepad";
  17381. };
  17382. return FreeCameraGamepadInput;
  17383. }());
  17384. __decorate([
  17385. BABYLON.serialize()
  17386. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  17387. __decorate([
  17388. BABYLON.serialize()
  17389. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17390. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  17391. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  17392. })(BABYLON || (BABYLON = {}));
  17393. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  17394. var BABYLON;
  17395. (function (BABYLON) {
  17396. var ArcRotateCameraKeyboardMoveInput = (function () {
  17397. function ArcRotateCameraKeyboardMoveInput() {
  17398. this._keys = [];
  17399. this.keysUp = [38];
  17400. this.keysDown = [40];
  17401. this.keysLeft = [37];
  17402. this.keysRight = [39];
  17403. }
  17404. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  17405. var _this = this;
  17406. element.tabIndex = 1;
  17407. this._onKeyDown = function (evt) {
  17408. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17409. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17410. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17411. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17412. var index = _this._keys.indexOf(evt.keyCode);
  17413. if (index === -1) {
  17414. _this._keys.push(evt.keyCode);
  17415. }
  17416. if (evt.preventDefault) {
  17417. if (!noPreventDefault) {
  17418. evt.preventDefault();
  17419. }
  17420. }
  17421. }
  17422. };
  17423. this._onKeyUp = function (evt) {
  17424. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17425. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17426. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17427. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17428. var index = _this._keys.indexOf(evt.keyCode);
  17429. if (index >= 0) {
  17430. _this._keys.splice(index, 1);
  17431. }
  17432. if (evt.preventDefault) {
  17433. if (!noPreventDefault) {
  17434. evt.preventDefault();
  17435. }
  17436. }
  17437. }
  17438. };
  17439. this._onLostFocus = function () {
  17440. _this._keys = [];
  17441. };
  17442. element.addEventListener("keydown", this._onKeyDown, false);
  17443. element.addEventListener("keyup", this._onKeyUp, false);
  17444. BABYLON.Tools.RegisterTopRootEvents([
  17445. { name: "blur", handler: this._onLostFocus }
  17446. ]);
  17447. };
  17448. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  17449. if (element) {
  17450. element.removeEventListener("keydown", this._onKeyDown);
  17451. element.removeEventListener("keyup", this._onKeyUp);
  17452. }
  17453. BABYLON.Tools.UnregisterTopRootEvents([
  17454. { name: "blur", handler: this._onLostFocus }
  17455. ]);
  17456. this._keys = [];
  17457. this._onKeyDown = null;
  17458. this._onKeyUp = null;
  17459. this._onLostFocus = null;
  17460. };
  17461. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  17462. if (this._onKeyDown) {
  17463. var camera = this.camera;
  17464. for (var index = 0; index < this._keys.length; index++) {
  17465. var keyCode = this._keys[index];
  17466. if (this.keysLeft.indexOf(keyCode) !== -1) {
  17467. camera.inertialAlphaOffset -= 0.01;
  17468. }
  17469. else if (this.keysUp.indexOf(keyCode) !== -1) {
  17470. camera.inertialBetaOffset -= 0.01;
  17471. }
  17472. else if (this.keysRight.indexOf(keyCode) !== -1) {
  17473. camera.inertialAlphaOffset += 0.01;
  17474. }
  17475. else if (this.keysDown.indexOf(keyCode) !== -1) {
  17476. camera.inertialBetaOffset += 0.01;
  17477. }
  17478. }
  17479. }
  17480. };
  17481. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  17482. return "ArcRotateCameraKeyboardMoveInput";
  17483. };
  17484. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  17485. return "keyboard";
  17486. };
  17487. return ArcRotateCameraKeyboardMoveInput;
  17488. }());
  17489. __decorate([
  17490. BABYLON.serialize()
  17491. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  17492. __decorate([
  17493. BABYLON.serialize()
  17494. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  17495. __decorate([
  17496. BABYLON.serialize()
  17497. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  17498. __decorate([
  17499. BABYLON.serialize()
  17500. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  17501. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  17502. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  17503. })(BABYLON || (BABYLON = {}));
  17504. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  17505. var BABYLON;
  17506. (function (BABYLON) {
  17507. var ArcRotateCameraMouseWheelInput = (function () {
  17508. function ArcRotateCameraMouseWheelInput() {
  17509. this.wheelPrecision = 3.0;
  17510. }
  17511. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  17512. var _this = this;
  17513. this._wheel = function (p, s) {
  17514. //sanity check - this should be a PointerWheel event.
  17515. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  17516. return;
  17517. var event = p.event;
  17518. var delta = 0;
  17519. if (event.wheelDelta) {
  17520. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  17521. }
  17522. else if (event.detail) {
  17523. delta = -event.detail / _this.wheelPrecision;
  17524. }
  17525. if (delta)
  17526. _this.camera.inertialRadiusOffset += delta;
  17527. if (event.preventDefault) {
  17528. if (!noPreventDefault) {
  17529. event.preventDefault();
  17530. }
  17531. }
  17532. };
  17533. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  17534. };
  17535. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  17536. if (this._observer && element) {
  17537. this.camera.getScene().onPointerObservable.remove(this._observer);
  17538. this._observer = null;
  17539. this._wheel = null;
  17540. }
  17541. };
  17542. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  17543. return "ArcRotateCameraMouseWheelInput";
  17544. };
  17545. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  17546. return "mousewheel";
  17547. };
  17548. return ArcRotateCameraMouseWheelInput;
  17549. }());
  17550. __decorate([
  17551. BABYLON.serialize()
  17552. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  17553. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  17554. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  17555. })(BABYLON || (BABYLON = {}));
  17556. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  17557. var BABYLON;
  17558. (function (BABYLON) {
  17559. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17560. var ArcRotateCameraPointersInput = (function () {
  17561. function ArcRotateCameraPointersInput() {
  17562. this.buttons = [0, 1, 2];
  17563. this.angularSensibilityX = 1000.0;
  17564. this.angularSensibilityY = 1000.0;
  17565. this.pinchPrecision = 6.0;
  17566. this.panningSensibility = 50.0;
  17567. this._isPanClick = false;
  17568. this.pinchInwards = true;
  17569. }
  17570. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  17571. var _this = this;
  17572. var engine = this.camera.getEngine();
  17573. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  17574. var pointA, pointB;
  17575. var previousPinchDistance = 0;
  17576. this._pointerInput = function (p, s) {
  17577. var evt = p.event;
  17578. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  17579. return;
  17580. }
  17581. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  17582. try {
  17583. evt.srcElement.setPointerCapture(evt.pointerId);
  17584. }
  17585. catch (e) {
  17586. //Nothing to do with the error. Execution will continue.
  17587. }
  17588. // Manage panning with pan button click
  17589. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  17590. // manage pointers
  17591. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  17592. if (pointA === undefined) {
  17593. pointA = cacheSoloPointer;
  17594. }
  17595. else if (pointB === undefined) {
  17596. pointB = cacheSoloPointer;
  17597. }
  17598. if (!noPreventDefault) {
  17599. evt.preventDefault();
  17600. element.focus();
  17601. }
  17602. }
  17603. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  17604. try {
  17605. evt.srcElement.releasePointerCapture(evt.pointerId);
  17606. }
  17607. catch (e) {
  17608. //Nothing to do with the error.
  17609. }
  17610. cacheSoloPointer = null;
  17611. previousPinchDistance = 0;
  17612. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  17613. //but emptying completly pointers collection is required to fix a bug on iPhone :
  17614. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  17615. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  17616. pointA = pointB = undefined;
  17617. if (!noPreventDefault) {
  17618. evt.preventDefault();
  17619. }
  17620. }
  17621. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  17622. if (!noPreventDefault) {
  17623. evt.preventDefault();
  17624. }
  17625. // One button down
  17626. if (pointA && pointB === undefined) {
  17627. if (_this.panningSensibility !== 0 &&
  17628. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  17629. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  17630. _this.camera
  17631. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  17632. _this.camera
  17633. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  17634. }
  17635. else {
  17636. var offsetX = evt.clientX - cacheSoloPointer.x;
  17637. var offsetY = evt.clientY - cacheSoloPointer.y;
  17638. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17639. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17640. }
  17641. cacheSoloPointer.x = evt.clientX;
  17642. cacheSoloPointer.y = evt.clientY;
  17643. }
  17644. else if (pointA && pointB) {
  17645. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  17646. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  17647. ed.x = evt.clientX;
  17648. ed.y = evt.clientY;
  17649. var direction = _this.pinchInwards ? 1 : -1;
  17650. var distX = pointA.x - pointB.x;
  17651. var distY = pointA.y - pointB.y;
  17652. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  17653. if (previousPinchDistance === 0) {
  17654. previousPinchDistance = pinchSquaredDistance;
  17655. return;
  17656. }
  17657. if (pinchSquaredDistance !== previousPinchDistance) {
  17658. _this.camera
  17659. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  17660. (_this.pinchPrecision *
  17661. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  17662. direction);
  17663. previousPinchDistance = pinchSquaredDistance;
  17664. }
  17665. }
  17666. }
  17667. };
  17668. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  17669. this._onContextMenu = function (evt) {
  17670. evt.preventDefault();
  17671. };
  17672. if (!this.camera._useCtrlForPanning) {
  17673. element.addEventListener("contextmenu", this._onContextMenu, false);
  17674. }
  17675. this._onLostFocus = function () {
  17676. //this._keys = [];
  17677. pointA = pointB = undefined;
  17678. previousPinchDistance = 0;
  17679. cacheSoloPointer = null;
  17680. };
  17681. this._onMouseMove = function (evt) {
  17682. if (!engine.isPointerLock) {
  17683. return;
  17684. }
  17685. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  17686. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  17687. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17688. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17689. if (!noPreventDefault) {
  17690. evt.preventDefault();
  17691. }
  17692. };
  17693. this._onGestureStart = function (e) {
  17694. if (window.MSGesture === undefined) {
  17695. return;
  17696. }
  17697. if (!_this._MSGestureHandler) {
  17698. _this._MSGestureHandler = new MSGesture();
  17699. _this._MSGestureHandler.target = element;
  17700. }
  17701. _this._MSGestureHandler.addPointer(e.pointerId);
  17702. };
  17703. this._onGesture = function (e) {
  17704. _this.camera.radius *= e.scale;
  17705. if (e.preventDefault) {
  17706. if (!noPreventDefault) {
  17707. e.stopPropagation();
  17708. e.preventDefault();
  17709. }
  17710. }
  17711. };
  17712. element.addEventListener("mousemove", this._onMouseMove, false);
  17713. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  17714. element.addEventListener("MSGestureChange", this._onGesture, false);
  17715. element.addEventListener("keydown", this._onKeyDown, false);
  17716. element.addEventListener("keyup", this._onKeyUp, false);
  17717. BABYLON.Tools.RegisterTopRootEvents([
  17718. { name: "blur", handler: this._onLostFocus }
  17719. ]);
  17720. };
  17721. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  17722. if (element && this._observer) {
  17723. this.camera.getScene().onPointerObservable.remove(this._observer);
  17724. this._observer = null;
  17725. element.removeEventListener("contextmenu", this._onContextMenu);
  17726. element.removeEventListener("mousemove", this._onMouseMove);
  17727. element.removeEventListener("MSPointerDown", this._onGestureStart);
  17728. element.removeEventListener("MSGestureChange", this._onGesture);
  17729. element.removeEventListener("keydown", this._onKeyDown);
  17730. element.removeEventListener("keyup", this._onKeyUp);
  17731. this._isPanClick = false;
  17732. this.pinchInwards = true;
  17733. this._onKeyDown = null;
  17734. this._onKeyUp = null;
  17735. this._onMouseMove = null;
  17736. this._onGestureStart = null;
  17737. this._onGesture = null;
  17738. this._MSGestureHandler = null;
  17739. this._onLostFocus = null;
  17740. this._onContextMenu = null;
  17741. }
  17742. BABYLON.Tools.UnregisterTopRootEvents([
  17743. { name: "blur", handler: this._onLostFocus }
  17744. ]);
  17745. };
  17746. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  17747. return "ArcRotateCameraPointersInput";
  17748. };
  17749. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  17750. return "pointers";
  17751. };
  17752. return ArcRotateCameraPointersInput;
  17753. }());
  17754. __decorate([
  17755. BABYLON.serialize()
  17756. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  17757. __decorate([
  17758. BABYLON.serialize()
  17759. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  17760. __decorate([
  17761. BABYLON.serialize()
  17762. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  17763. __decorate([
  17764. BABYLON.serialize()
  17765. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  17766. __decorate([
  17767. BABYLON.serialize()
  17768. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  17769. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  17770. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  17771. })(BABYLON || (BABYLON = {}));
  17772. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  17773. var BABYLON;
  17774. (function (BABYLON) {
  17775. var ArcRotateCameraGamepadInput = (function () {
  17776. function ArcRotateCameraGamepadInput() {
  17777. this.gamepadRotationSensibility = 80;
  17778. this.gamepadMoveSensibility = 40;
  17779. }
  17780. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  17781. var _this = this;
  17782. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  17783. };
  17784. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  17785. if (this._gamepads) {
  17786. this._gamepads.dispose();
  17787. }
  17788. this.gamepad = null;
  17789. };
  17790. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  17791. if (this.gamepad) {
  17792. var camera = this.camera;
  17793. var RSValues = this.gamepad.rightStick;
  17794. if (RSValues.x != 0) {
  17795. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  17796. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  17797. camera.inertialAlphaOffset += normalizedRX;
  17798. }
  17799. }
  17800. if (RSValues.y != 0) {
  17801. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  17802. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  17803. camera.inertialBetaOffset += normalizedRY;
  17804. }
  17805. }
  17806. var LSValues = this.gamepad.leftStick;
  17807. if (LSValues.y != 0) {
  17808. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17809. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  17810. this.camera.inertialRadiusOffset -= normalizedLY;
  17811. }
  17812. }
  17813. }
  17814. };
  17815. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17816. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  17817. // prioritize XBOX gamepads.
  17818. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  17819. this.gamepad = gamepad;
  17820. }
  17821. }
  17822. };
  17823. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  17824. return "ArcRotateCameraGamepadInput";
  17825. };
  17826. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  17827. return "gamepad";
  17828. };
  17829. return ArcRotateCameraGamepadInput;
  17830. }());
  17831. __decorate([
  17832. BABYLON.serialize()
  17833. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  17834. __decorate([
  17835. BABYLON.serialize()
  17836. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17837. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  17838. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  17839. })(BABYLON || (BABYLON = {}));
  17840. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  17841. var BABYLON;
  17842. (function (BABYLON) {
  17843. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  17844. function ArcRotateCameraVRDeviceOrientationInput() {
  17845. this.alphaCorrection = 1;
  17846. this.betaCorrection = 1;
  17847. this.gammaCorrection = 1;
  17848. this._alpha = 0;
  17849. this._beta = 0;
  17850. this._gamma = 0;
  17851. this._dirty = false;
  17852. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17853. }
  17854. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  17855. this.camera.attachControl(element, noPreventDefault);
  17856. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17857. };
  17858. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  17859. var camera = this.camera;
  17860. this._alpha = +evt.alpha | 0;
  17861. this._beta = +evt.beta | 0;
  17862. this._gamma = +evt.gamma | 0;
  17863. this._dirty = true;
  17864. };
  17865. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  17866. if (this._dirty) {
  17867. this._dirty = false;
  17868. if (this._gamma < 0) {
  17869. this._gamma = 180 + this._gamma;
  17870. }
  17871. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  17872. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  17873. }
  17874. };
  17875. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  17876. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17877. };
  17878. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  17879. return "ArcRotateCameraVRDeviceOrientationInput";
  17880. };
  17881. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  17882. return "VRDeviceOrientation";
  17883. };
  17884. return ArcRotateCameraVRDeviceOrientationInput;
  17885. }());
  17886. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  17887. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  17888. })(BABYLON || (BABYLON = {}));
  17889. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  17890. /// <reference path="babylon.camera.ts" />
  17891. var BABYLON;
  17892. (function (BABYLON) {
  17893. var TargetCamera = (function (_super) {
  17894. __extends(TargetCamera, _super);
  17895. function TargetCamera(name, position, scene) {
  17896. var _this = _super.call(this, name, position, scene) || this;
  17897. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17898. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  17899. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  17900. _this.speed = 2.0;
  17901. _this.noRotationConstraint = false;
  17902. _this.lockedTarget = null;
  17903. _this._currentTarget = BABYLON.Vector3.Zero();
  17904. _this._viewMatrix = BABYLON.Matrix.Zero();
  17905. _this._camMatrix = BABYLON.Matrix.Zero();
  17906. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  17907. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  17908. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  17909. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  17910. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  17911. _this._lookAtTemp = BABYLON.Matrix.Zero();
  17912. _this._tempMatrix = BABYLON.Matrix.Zero();
  17913. return _this;
  17914. }
  17915. TargetCamera.prototype.getFrontPosition = function (distance) {
  17916. var direction = this.getTarget().subtract(this.position);
  17917. direction.normalize();
  17918. direction.scaleInPlace(distance);
  17919. return this.globalPosition.add(direction);
  17920. };
  17921. TargetCamera.prototype._getLockedTargetPosition = function () {
  17922. if (!this.lockedTarget) {
  17923. return null;
  17924. }
  17925. if (this.lockedTarget.absolutePosition) {
  17926. this.lockedTarget.computeWorldMatrix();
  17927. }
  17928. return this.lockedTarget.absolutePosition || this.lockedTarget;
  17929. };
  17930. // Cache
  17931. TargetCamera.prototype._initCache = function () {
  17932. _super.prototype._initCache.call(this);
  17933. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17934. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17935. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17936. };
  17937. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  17938. if (!ignoreParentClass) {
  17939. _super.prototype._updateCache.call(this);
  17940. }
  17941. var lockedTargetPosition = this._getLockedTargetPosition();
  17942. if (!lockedTargetPosition) {
  17943. this._cache.lockedTarget = null;
  17944. }
  17945. else {
  17946. if (!this._cache.lockedTarget) {
  17947. this._cache.lockedTarget = lockedTargetPosition.clone();
  17948. }
  17949. else {
  17950. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  17951. }
  17952. }
  17953. this._cache.rotation.copyFrom(this.rotation);
  17954. if (this.rotationQuaternion)
  17955. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17956. };
  17957. // Synchronized
  17958. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  17959. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  17960. return false;
  17961. }
  17962. var lockedTargetPosition = this._getLockedTargetPosition();
  17963. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  17964. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  17965. };
  17966. // Methods
  17967. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  17968. var engine = this.getEngine();
  17969. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  17970. };
  17971. // Target
  17972. TargetCamera.prototype.setTarget = function (target) {
  17973. this.upVector.normalize();
  17974. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  17975. this._camMatrix.invert();
  17976. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  17977. var vDir = target.subtract(this.position);
  17978. if (vDir.x >= 0.0) {
  17979. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  17980. }
  17981. else {
  17982. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  17983. }
  17984. this.rotation.z = 0;
  17985. if (isNaN(this.rotation.x)) {
  17986. this.rotation.x = 0;
  17987. }
  17988. if (isNaN(this.rotation.y)) {
  17989. this.rotation.y = 0;
  17990. }
  17991. if (isNaN(this.rotation.z)) {
  17992. this.rotation.z = 0;
  17993. }
  17994. if (this.rotationQuaternion) {
  17995. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  17996. }
  17997. };
  17998. /**
  17999. * Return the current target position of the camera. This value is expressed in local space.
  18000. */
  18001. TargetCamera.prototype.getTarget = function () {
  18002. return this._currentTarget;
  18003. };
  18004. TargetCamera.prototype._decideIfNeedsToMove = function () {
  18005. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  18006. };
  18007. TargetCamera.prototype._updatePosition = function () {
  18008. if (this.parent) {
  18009. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  18010. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  18011. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  18012. return;
  18013. }
  18014. this.position.addInPlace(this.cameraDirection);
  18015. };
  18016. TargetCamera.prototype._checkInputs = function () {
  18017. var needToMove = this._decideIfNeedsToMove();
  18018. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  18019. // Move
  18020. if (needToMove) {
  18021. this._updatePosition();
  18022. }
  18023. // Rotate
  18024. if (needToRotate) {
  18025. this.rotation.x += this.cameraRotation.x;
  18026. this.rotation.y += this.cameraRotation.y;
  18027. //rotate, if quaternion is set and rotation was used
  18028. if (this.rotationQuaternion) {
  18029. var len = this.rotation.lengthSquared();
  18030. if (len) {
  18031. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  18032. }
  18033. }
  18034. if (!this.noRotationConstraint) {
  18035. var limit = (Math.PI / 2) * 0.95;
  18036. if (this.rotation.x > limit)
  18037. this.rotation.x = limit;
  18038. if (this.rotation.x < -limit)
  18039. this.rotation.x = -limit;
  18040. }
  18041. }
  18042. // Inertia
  18043. if (needToMove) {
  18044. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  18045. this.cameraDirection.x = 0;
  18046. }
  18047. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  18048. this.cameraDirection.y = 0;
  18049. }
  18050. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  18051. this.cameraDirection.z = 0;
  18052. }
  18053. this.cameraDirection.scaleInPlace(this.inertia);
  18054. }
  18055. if (needToRotate) {
  18056. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  18057. this.cameraRotation.x = 0;
  18058. }
  18059. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  18060. this.cameraRotation.y = 0;
  18061. }
  18062. this.cameraRotation.scaleInPlace(this.inertia);
  18063. }
  18064. _super.prototype._checkInputs.call(this);
  18065. };
  18066. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  18067. if (this.rotationQuaternion) {
  18068. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  18069. //update the up vector!
  18070. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  18071. }
  18072. else {
  18073. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  18074. }
  18075. };
  18076. TargetCamera.prototype._getViewMatrix = function () {
  18077. if (!this.lockedTarget) {
  18078. // Compute
  18079. this._updateCameraRotationMatrix();
  18080. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  18081. // Computing target and final matrix
  18082. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  18083. }
  18084. else {
  18085. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  18086. }
  18087. if (this.getScene().useRightHandedSystem) {
  18088. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  18089. }
  18090. else {
  18091. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  18092. }
  18093. return this._viewMatrix;
  18094. };
  18095. /**
  18096. * @override
  18097. * Override Camera.createRigCamera
  18098. */
  18099. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  18100. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  18101. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  18102. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  18103. if (!this.rotationQuaternion) {
  18104. this.rotationQuaternion = new BABYLON.Quaternion();
  18105. }
  18106. rigCamera._cameraRigParams = {};
  18107. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  18108. }
  18109. return rigCamera;
  18110. }
  18111. return null;
  18112. };
  18113. /**
  18114. * @override
  18115. * Override Camera._updateRigCameras
  18116. */
  18117. TargetCamera.prototype._updateRigCameras = function () {
  18118. var camLeft = this._rigCameras[0];
  18119. var camRight = this._rigCameras[1];
  18120. switch (this.cameraRigMode) {
  18121. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18122. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18123. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18124. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18125. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  18126. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  18127. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  18128. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  18129. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  18130. camLeft.setTarget(this.getTarget());
  18131. camRight.setTarget(this.getTarget());
  18132. break;
  18133. case BABYLON.Camera.RIG_MODE_VR:
  18134. if (camLeft.rotationQuaternion) {
  18135. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18136. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18137. }
  18138. else {
  18139. camLeft.rotation.copyFrom(this.rotation);
  18140. camRight.rotation.copyFrom(this.rotation);
  18141. }
  18142. camLeft.position.copyFrom(this.position);
  18143. camRight.position.copyFrom(this.position);
  18144. break;
  18145. }
  18146. _super.prototype._updateRigCameras.call(this);
  18147. };
  18148. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  18149. if (!this._rigCamTransformMatrix) {
  18150. this._rigCamTransformMatrix = new BABYLON.Matrix();
  18151. }
  18152. var target = this.getTarget();
  18153. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  18154. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  18155. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  18156. };
  18157. TargetCamera.prototype.getClassName = function () {
  18158. return "TargetCamera";
  18159. };
  18160. return TargetCamera;
  18161. }(BABYLON.Camera));
  18162. __decorate([
  18163. BABYLON.serializeAsVector3()
  18164. ], TargetCamera.prototype, "rotation", void 0);
  18165. __decorate([
  18166. BABYLON.serialize()
  18167. ], TargetCamera.prototype, "speed", void 0);
  18168. __decorate([
  18169. BABYLON.serializeAsMeshReference("lockedTargetId")
  18170. ], TargetCamera.prototype, "lockedTarget", void 0);
  18171. BABYLON.TargetCamera = TargetCamera;
  18172. })(BABYLON || (BABYLON = {}));
  18173. //# sourceMappingURL=babylon.targetCamera.js.map
  18174. var BABYLON;
  18175. (function (BABYLON) {
  18176. var FreeCamera = (function (_super) {
  18177. __extends(FreeCamera, _super);
  18178. function FreeCamera(name, position, scene) {
  18179. var _this = _super.call(this, name, position, scene) || this;
  18180. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  18181. _this.checkCollisions = false;
  18182. _this.applyGravity = false;
  18183. _this._collider = new BABYLON.Collider();
  18184. _this._needMoveForGravity = false;
  18185. _this._oldPosition = BABYLON.Vector3.Zero();
  18186. _this._diffPosition = BABYLON.Vector3.Zero();
  18187. _this._newPosition = BABYLON.Vector3.Zero();
  18188. // Collisions
  18189. _this._collisionMask = -1;
  18190. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18191. if (collidedMesh === void 0) { collidedMesh = null; }
  18192. //TODO move this to the collision coordinator!
  18193. if (_this.getScene().workerCollisions)
  18194. newPosition.multiplyInPlace(_this._collider.radius);
  18195. var updatePosition = function (newPos) {
  18196. _this._newPosition.copyFrom(newPos);
  18197. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  18198. var oldPosition = _this.position.clone();
  18199. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  18200. _this.position.addInPlace(_this._diffPosition);
  18201. if (_this.onCollide && collidedMesh) {
  18202. _this.onCollide(collidedMesh);
  18203. }
  18204. }
  18205. };
  18206. updatePosition(newPosition);
  18207. };
  18208. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  18209. _this.inputs.addKeyboard().addMouse();
  18210. return _this;
  18211. }
  18212. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  18213. //-- begin properties for backward compatibility for inputs
  18214. get: function () {
  18215. var mouse = this.inputs.attached["mouse"];
  18216. if (mouse)
  18217. return mouse.angularSensibility;
  18218. },
  18219. set: function (value) {
  18220. var mouse = this.inputs.attached["mouse"];
  18221. if (mouse)
  18222. mouse.angularSensibility = value;
  18223. },
  18224. enumerable: true,
  18225. configurable: true
  18226. });
  18227. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  18228. get: function () {
  18229. var keyboard = this.inputs.attached["keyboard"];
  18230. if (keyboard)
  18231. return keyboard.keysUp;
  18232. },
  18233. set: function (value) {
  18234. var keyboard = this.inputs.attached["keyboard"];
  18235. if (keyboard)
  18236. keyboard.keysUp = value;
  18237. },
  18238. enumerable: true,
  18239. configurable: true
  18240. });
  18241. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  18242. get: function () {
  18243. var keyboard = this.inputs.attached["keyboard"];
  18244. if (keyboard)
  18245. return keyboard.keysDown;
  18246. },
  18247. set: function (value) {
  18248. var keyboard = this.inputs.attached["keyboard"];
  18249. if (keyboard)
  18250. keyboard.keysDown = value;
  18251. },
  18252. enumerable: true,
  18253. configurable: true
  18254. });
  18255. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  18256. get: function () {
  18257. var keyboard = this.inputs.attached["keyboard"];
  18258. if (keyboard)
  18259. return keyboard.keysLeft;
  18260. },
  18261. set: function (value) {
  18262. var keyboard = this.inputs.attached["keyboard"];
  18263. if (keyboard)
  18264. keyboard.keysLeft = value;
  18265. },
  18266. enumerable: true,
  18267. configurable: true
  18268. });
  18269. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  18270. get: function () {
  18271. var keyboard = this.inputs.attached["keyboard"];
  18272. if (keyboard)
  18273. return keyboard.keysRight;
  18274. },
  18275. set: function (value) {
  18276. var keyboard = this.inputs.attached["keyboard"];
  18277. if (keyboard)
  18278. keyboard.keysRight = value;
  18279. },
  18280. enumerable: true,
  18281. configurable: true
  18282. });
  18283. // Controls
  18284. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  18285. this.inputs.attachElement(element, noPreventDefault);
  18286. };
  18287. FreeCamera.prototype.detachControl = function (element) {
  18288. this.inputs.detachElement(element);
  18289. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  18290. this.cameraRotation = new BABYLON.Vector2(0, 0);
  18291. };
  18292. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  18293. get: function () {
  18294. return this._collisionMask;
  18295. },
  18296. set: function (mask) {
  18297. this._collisionMask = !isNaN(mask) ? mask : -1;
  18298. },
  18299. enumerable: true,
  18300. configurable: true
  18301. });
  18302. FreeCamera.prototype._collideWithWorld = function (velocity) {
  18303. var globalPosition;
  18304. if (this.parent) {
  18305. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  18306. }
  18307. else {
  18308. globalPosition = this.position;
  18309. }
  18310. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  18311. this._collider.radius = this.ellipsoid;
  18312. this._collider.collisionMask = this._collisionMask;
  18313. //no need for clone, as long as gravity is not on.
  18314. var actualVelocity = velocity;
  18315. //add gravity to the velocity to prevent the dual-collision checking
  18316. if (this.applyGravity) {
  18317. //this prevents mending with cameraDirection, a global variable of the free camera class.
  18318. actualVelocity = velocity.add(this.getScene().gravity);
  18319. }
  18320. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  18321. };
  18322. FreeCamera.prototype._checkInputs = function () {
  18323. if (!this._localDirection) {
  18324. this._localDirection = BABYLON.Vector3.Zero();
  18325. this._transformedDirection = BABYLON.Vector3.Zero();
  18326. }
  18327. this.inputs.checkInputs();
  18328. _super.prototype._checkInputs.call(this);
  18329. };
  18330. FreeCamera.prototype._decideIfNeedsToMove = function () {
  18331. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  18332. };
  18333. FreeCamera.prototype._updatePosition = function () {
  18334. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  18335. this._collideWithWorld(this.cameraDirection);
  18336. }
  18337. else {
  18338. _super.prototype._updatePosition.call(this);
  18339. }
  18340. };
  18341. FreeCamera.prototype.dispose = function () {
  18342. this.inputs.clear();
  18343. _super.prototype.dispose.call(this);
  18344. };
  18345. FreeCamera.prototype.getClassName = function () {
  18346. return "FreeCamera";
  18347. };
  18348. return FreeCamera;
  18349. }(BABYLON.TargetCamera));
  18350. __decorate([
  18351. BABYLON.serializeAsVector3()
  18352. ], FreeCamera.prototype, "ellipsoid", void 0);
  18353. __decorate([
  18354. BABYLON.serialize()
  18355. ], FreeCamera.prototype, "checkCollisions", void 0);
  18356. __decorate([
  18357. BABYLON.serialize()
  18358. ], FreeCamera.prototype, "applyGravity", void 0);
  18359. BABYLON.FreeCamera = FreeCamera;
  18360. })(BABYLON || (BABYLON = {}));
  18361. //# sourceMappingURL=babylon.freeCamera.js.map
  18362. var BABYLON;
  18363. (function (BABYLON) {
  18364. var FreeCameraInputsManager = (function (_super) {
  18365. __extends(FreeCameraInputsManager, _super);
  18366. function FreeCameraInputsManager(camera) {
  18367. return _super.call(this, camera) || this;
  18368. }
  18369. FreeCameraInputsManager.prototype.addKeyboard = function () {
  18370. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  18371. return this;
  18372. };
  18373. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  18374. if (touchEnabled === void 0) { touchEnabled = true; }
  18375. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  18376. return this;
  18377. };
  18378. FreeCameraInputsManager.prototype.addGamepad = function () {
  18379. this.add(new BABYLON.FreeCameraGamepadInput());
  18380. return this;
  18381. };
  18382. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  18383. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  18384. return this;
  18385. };
  18386. FreeCameraInputsManager.prototype.addTouch = function () {
  18387. this.add(new BABYLON.FreeCameraTouchInput());
  18388. return this;
  18389. };
  18390. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  18391. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  18392. return this;
  18393. };
  18394. return FreeCameraInputsManager;
  18395. }(BABYLON.CameraInputsManager));
  18396. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  18397. })(BABYLON || (BABYLON = {}));
  18398. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  18399. /// <reference path="babylon.targetCamera.ts" />
  18400. var BABYLON;
  18401. (function (BABYLON) {
  18402. var FollowCamera = (function (_super) {
  18403. __extends(FollowCamera, _super);
  18404. function FollowCamera(name, position, scene, lockedTarget) {
  18405. var _this = _super.call(this, name, position, scene) || this;
  18406. _this.radius = 12;
  18407. _this.rotationOffset = 0;
  18408. _this.heightOffset = 4;
  18409. _this.cameraAcceleration = 0.05;
  18410. _this.maxCameraSpeed = 20;
  18411. _this.lockedTarget = lockedTarget;
  18412. return _this;
  18413. }
  18414. FollowCamera.prototype.getRadians = function (degrees) {
  18415. return degrees * Math.PI / 180;
  18416. };
  18417. FollowCamera.prototype.follow = function (cameraTarget) {
  18418. if (!cameraTarget)
  18419. return;
  18420. var yRotation;
  18421. if (cameraTarget.rotationQuaternion) {
  18422. var rotMatrix = new BABYLON.Matrix();
  18423. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  18424. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  18425. }
  18426. else {
  18427. yRotation = cameraTarget.rotation.y;
  18428. }
  18429. var radians = this.getRadians(this.rotationOffset) + yRotation;
  18430. var targetPosition = cameraTarget.getAbsolutePosition();
  18431. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  18432. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  18433. var dx = targetX - this.position.x;
  18434. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  18435. var dz = (targetZ) - this.position.z;
  18436. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  18437. var vy = dy * this.cameraAcceleration;
  18438. var vz = dz * this.cameraAcceleration * 2;
  18439. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  18440. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18441. }
  18442. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  18443. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18444. }
  18445. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  18446. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18447. }
  18448. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  18449. this.setTarget(targetPosition);
  18450. };
  18451. FollowCamera.prototype._checkInputs = function () {
  18452. _super.prototype._checkInputs.call(this);
  18453. this.follow(this.lockedTarget);
  18454. };
  18455. FollowCamera.prototype.getClassName = function () {
  18456. return "FollowCamera";
  18457. };
  18458. return FollowCamera;
  18459. }(BABYLON.TargetCamera));
  18460. __decorate([
  18461. BABYLON.serialize()
  18462. ], FollowCamera.prototype, "radius", void 0);
  18463. __decorate([
  18464. BABYLON.serialize()
  18465. ], FollowCamera.prototype, "rotationOffset", void 0);
  18466. __decorate([
  18467. BABYLON.serialize()
  18468. ], FollowCamera.prototype, "heightOffset", void 0);
  18469. __decorate([
  18470. BABYLON.serialize()
  18471. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  18472. __decorate([
  18473. BABYLON.serialize()
  18474. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  18475. __decorate([
  18476. BABYLON.serializeAsMeshReference("lockedTargetId")
  18477. ], FollowCamera.prototype, "lockedTarget", void 0);
  18478. BABYLON.FollowCamera = FollowCamera;
  18479. var ArcFollowCamera = (function (_super) {
  18480. __extends(ArcFollowCamera, _super);
  18481. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  18482. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18483. _this.alpha = alpha;
  18484. _this.beta = beta;
  18485. _this.radius = radius;
  18486. _this.target = target;
  18487. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  18488. _this.follow();
  18489. return _this;
  18490. }
  18491. ArcFollowCamera.prototype.follow = function () {
  18492. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  18493. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  18494. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  18495. var targetPosition = this.target.getAbsolutePosition();
  18496. this.position = targetPosition.add(this._cartesianCoordinates);
  18497. this.setTarget(targetPosition);
  18498. };
  18499. ArcFollowCamera.prototype._checkInputs = function () {
  18500. _super.prototype._checkInputs.call(this);
  18501. this.follow();
  18502. };
  18503. ArcFollowCamera.prototype.getClassName = function () {
  18504. return "ArcFollowCamera";
  18505. };
  18506. return ArcFollowCamera;
  18507. }(BABYLON.TargetCamera));
  18508. BABYLON.ArcFollowCamera = ArcFollowCamera;
  18509. })(BABYLON || (BABYLON = {}));
  18510. //# sourceMappingURL=babylon.followCamera.js.map
  18511. /// <reference path="babylon.freeCamera.ts" />
  18512. var BABYLON;
  18513. (function (BABYLON) {
  18514. // We're mainly based on the logic defined into the FreeCamera code
  18515. var TouchCamera = (function (_super) {
  18516. __extends(TouchCamera, _super);
  18517. //-- end properties for backward compatibility for inputs
  18518. function TouchCamera(name, position, scene) {
  18519. var _this = _super.call(this, name, position, scene) || this;
  18520. _this.inputs.addTouch();
  18521. _this._setupInputs();
  18522. return _this;
  18523. }
  18524. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  18525. //-- Begin properties for backward compatibility for inputs
  18526. get: function () {
  18527. var touch = this.inputs.attached["touch"];
  18528. if (touch)
  18529. return touch.touchAngularSensibility;
  18530. },
  18531. set: function (value) {
  18532. var touch = this.inputs.attached["touch"];
  18533. if (touch)
  18534. touch.touchAngularSensibility = value;
  18535. },
  18536. enumerable: true,
  18537. configurable: true
  18538. });
  18539. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  18540. get: function () {
  18541. var touch = this.inputs.attached["touch"];
  18542. if (touch)
  18543. return touch.touchMoveSensibility;
  18544. },
  18545. set: function (value) {
  18546. var touch = this.inputs.attached["touch"];
  18547. if (touch)
  18548. touch.touchMoveSensibility = value;
  18549. },
  18550. enumerable: true,
  18551. configurable: true
  18552. });
  18553. TouchCamera.prototype.getClassName = function () {
  18554. return "TouchCamera";
  18555. };
  18556. TouchCamera.prototype._setupInputs = function () {
  18557. var mouse = this.inputs.attached["mouse"];
  18558. if (mouse) {
  18559. mouse.touchEnabled = false;
  18560. }
  18561. };
  18562. return TouchCamera;
  18563. }(BABYLON.FreeCamera));
  18564. BABYLON.TouchCamera = TouchCamera;
  18565. })(BABYLON || (BABYLON = {}));
  18566. //# sourceMappingURL=babylon.touchCamera.js.map
  18567. /// <reference path="babylon.targetCamera.ts" />
  18568. /// <reference path="..\Tools\babylon.tools.ts" />
  18569. var BABYLON;
  18570. (function (BABYLON) {
  18571. var ArcRotateCamera = (function (_super) {
  18572. __extends(ArcRotateCamera, _super);
  18573. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  18574. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18575. _this.inertialAlphaOffset = 0;
  18576. _this.inertialBetaOffset = 0;
  18577. _this.inertialRadiusOffset = 0;
  18578. _this.lowerAlphaLimit = null;
  18579. _this.upperAlphaLimit = null;
  18580. _this.lowerBetaLimit = 0.01;
  18581. _this.upperBetaLimit = Math.PI;
  18582. _this.lowerRadiusLimit = null;
  18583. _this.upperRadiusLimit = null;
  18584. _this.inertialPanningX = 0;
  18585. _this.inertialPanningY = 0;
  18586. //-- end properties for backward compatibility for inputs
  18587. _this.zoomOnFactor = 1;
  18588. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  18589. _this.allowUpsideDown = true;
  18590. _this._viewMatrix = new BABYLON.Matrix();
  18591. // Panning
  18592. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  18593. _this.checkCollisions = false;
  18594. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  18595. _this._collider = new BABYLON.Collider();
  18596. _this._previousPosition = BABYLON.Vector3.Zero();
  18597. _this._collisionVelocity = BABYLON.Vector3.Zero();
  18598. _this._newPosition = BABYLON.Vector3.Zero();
  18599. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18600. if (collidedMesh === void 0) { collidedMesh = null; }
  18601. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  18602. newPosition.multiplyInPlace(_this._collider.radius);
  18603. }
  18604. if (!collidedMesh) {
  18605. _this._previousPosition.copyFrom(_this.position);
  18606. }
  18607. else {
  18608. _this.setPosition(newPosition);
  18609. if (_this.onCollide) {
  18610. _this.onCollide(collidedMesh);
  18611. }
  18612. }
  18613. // Recompute because of constraints
  18614. var cosa = Math.cos(_this.alpha);
  18615. var sina = Math.sin(_this.alpha);
  18616. var cosb = Math.cos(_this.beta);
  18617. var sinb = Math.sin(_this.beta);
  18618. if (sinb === 0) {
  18619. sinb = 0.0001;
  18620. }
  18621. var target = _this._getTargetPosition();
  18622. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  18623. _this.position.copyFrom(_this._newPosition);
  18624. var up = _this.upVector;
  18625. if (_this.allowUpsideDown && _this.beta < 0) {
  18626. up = up.clone();
  18627. up = up.negate();
  18628. }
  18629. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  18630. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  18631. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  18632. _this._collisionTriggered = false;
  18633. };
  18634. if (!target) {
  18635. _this.target = BABYLON.Vector3.Zero();
  18636. }
  18637. else {
  18638. _this.target = target;
  18639. }
  18640. _this.alpha = alpha;
  18641. _this.beta = beta;
  18642. _this.radius = radius;
  18643. _this.getViewMatrix();
  18644. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  18645. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  18646. return _this;
  18647. }
  18648. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  18649. //-- begin properties for backward compatibility for inputs
  18650. get: function () {
  18651. var pointers = this.inputs.attached["pointers"];
  18652. if (pointers)
  18653. return pointers.angularSensibilityX;
  18654. },
  18655. set: function (value) {
  18656. var pointers = this.inputs.attached["pointers"];
  18657. if (pointers) {
  18658. pointers.angularSensibilityX = value;
  18659. }
  18660. },
  18661. enumerable: true,
  18662. configurable: true
  18663. });
  18664. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  18665. get: function () {
  18666. var pointers = this.inputs.attached["pointers"];
  18667. if (pointers)
  18668. return pointers.angularSensibilityY;
  18669. },
  18670. set: function (value) {
  18671. var pointers = this.inputs.attached["pointers"];
  18672. if (pointers) {
  18673. pointers.angularSensibilityY = value;
  18674. }
  18675. },
  18676. enumerable: true,
  18677. configurable: true
  18678. });
  18679. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  18680. get: function () {
  18681. var pointers = this.inputs.attached["pointers"];
  18682. if (pointers)
  18683. return pointers.pinchPrecision;
  18684. },
  18685. set: function (value) {
  18686. var pointers = this.inputs.attached["pointers"];
  18687. if (pointers) {
  18688. pointers.pinchPrecision = value;
  18689. }
  18690. },
  18691. enumerable: true,
  18692. configurable: true
  18693. });
  18694. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  18695. get: function () {
  18696. var pointers = this.inputs.attached["pointers"];
  18697. if (pointers)
  18698. return pointers.panningSensibility;
  18699. },
  18700. set: function (value) {
  18701. var pointers = this.inputs.attached["pointers"];
  18702. if (pointers) {
  18703. pointers.panningSensibility = value;
  18704. }
  18705. },
  18706. enumerable: true,
  18707. configurable: true
  18708. });
  18709. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  18710. get: function () {
  18711. var keyboard = this.inputs.attached["keyboard"];
  18712. if (keyboard)
  18713. return keyboard.keysUp;
  18714. },
  18715. set: function (value) {
  18716. var keyboard = this.inputs.attached["keyboard"];
  18717. if (keyboard)
  18718. keyboard.keysUp = value;
  18719. },
  18720. enumerable: true,
  18721. configurable: true
  18722. });
  18723. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  18724. get: function () {
  18725. var keyboard = this.inputs.attached["keyboard"];
  18726. if (keyboard)
  18727. return keyboard.keysDown;
  18728. },
  18729. set: function (value) {
  18730. var keyboard = this.inputs.attached["keyboard"];
  18731. if (keyboard)
  18732. keyboard.keysDown = value;
  18733. },
  18734. enumerable: true,
  18735. configurable: true
  18736. });
  18737. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  18738. get: function () {
  18739. var keyboard = this.inputs.attached["keyboard"];
  18740. if (keyboard)
  18741. return keyboard.keysLeft;
  18742. },
  18743. set: function (value) {
  18744. var keyboard = this.inputs.attached["keyboard"];
  18745. if (keyboard)
  18746. keyboard.keysLeft = value;
  18747. },
  18748. enumerable: true,
  18749. configurable: true
  18750. });
  18751. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  18752. get: function () {
  18753. var keyboard = this.inputs.attached["keyboard"];
  18754. if (keyboard)
  18755. return keyboard.keysRight;
  18756. },
  18757. set: function (value) {
  18758. var keyboard = this.inputs.attached["keyboard"];
  18759. if (keyboard)
  18760. keyboard.keysRight = value;
  18761. },
  18762. enumerable: true,
  18763. configurable: true
  18764. });
  18765. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  18766. get: function () {
  18767. var mousewheel = this.inputs.attached["mousewheel"];
  18768. if (mousewheel)
  18769. return mousewheel.wheelPrecision;
  18770. },
  18771. set: function (value) {
  18772. var mousewheel = this.inputs.attached["mousewheel"];
  18773. if (mousewheel)
  18774. mousewheel.wheelPrecision = value;
  18775. },
  18776. enumerable: true,
  18777. configurable: true
  18778. });
  18779. // Cache
  18780. ArcRotateCamera.prototype._initCache = function () {
  18781. _super.prototype._initCache.call(this);
  18782. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18783. this._cache.alpha = undefined;
  18784. this._cache.beta = undefined;
  18785. this._cache.radius = undefined;
  18786. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  18787. };
  18788. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  18789. if (!ignoreParentClass) {
  18790. _super.prototype._updateCache.call(this);
  18791. }
  18792. this._cache.target.copyFrom(this._getTargetPosition());
  18793. this._cache.alpha = this.alpha;
  18794. this._cache.beta = this.beta;
  18795. this._cache.radius = this.radius;
  18796. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  18797. };
  18798. ArcRotateCamera.prototype._getTargetPosition = function () {
  18799. if (this.target.getAbsolutePosition) {
  18800. var pos = this.target.getAbsolutePosition();
  18801. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  18802. }
  18803. return this.target;
  18804. };
  18805. // Synchronized
  18806. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  18807. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  18808. return false;
  18809. return this._cache.target.equals(this.target)
  18810. && this._cache.alpha === this.alpha
  18811. && this._cache.beta === this.beta
  18812. && this._cache.radius === this.radius
  18813. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  18814. };
  18815. // Methods
  18816. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  18817. var _this = this;
  18818. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  18819. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  18820. this._useCtrlForPanning = useCtrlForPanning;
  18821. this._panningMouseButton = panningMouseButton;
  18822. this.inputs.attachElement(element, noPreventDefault);
  18823. this._reset = function () {
  18824. _this.inertialAlphaOffset = 0;
  18825. _this.inertialBetaOffset = 0;
  18826. _this.inertialRadiusOffset = 0;
  18827. };
  18828. };
  18829. ArcRotateCamera.prototype.detachControl = function (element) {
  18830. this.inputs.detachElement(element);
  18831. if (this._reset) {
  18832. this._reset();
  18833. }
  18834. };
  18835. ArcRotateCamera.prototype._checkInputs = function () {
  18836. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  18837. if (this._collisionTriggered) {
  18838. return;
  18839. }
  18840. this.inputs.checkInputs();
  18841. // Inertia
  18842. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  18843. if (this.getScene().useRightHandedSystem) {
  18844. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18845. }
  18846. else {
  18847. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18848. }
  18849. this.beta += this.inertialBetaOffset;
  18850. this.radius -= this.inertialRadiusOffset;
  18851. this.inertialAlphaOffset *= this.inertia;
  18852. this.inertialBetaOffset *= this.inertia;
  18853. this.inertialRadiusOffset *= this.inertia;
  18854. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  18855. this.inertialAlphaOffset = 0;
  18856. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  18857. this.inertialBetaOffset = 0;
  18858. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  18859. this.inertialRadiusOffset = 0;
  18860. }
  18861. // Panning inertia
  18862. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  18863. if (!this._localDirection) {
  18864. this._localDirection = BABYLON.Vector3.Zero();
  18865. this._transformedDirection = BABYLON.Vector3.Zero();
  18866. }
  18867. this.inertialPanningX *= this.inertia;
  18868. this.inertialPanningY *= this.inertia;
  18869. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  18870. this.inertialPanningX = 0;
  18871. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  18872. this.inertialPanningY = 0;
  18873. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  18874. this._localDirection.multiplyInPlace(this.panningAxis);
  18875. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  18876. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  18877. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  18878. if (!this.panningAxis.y) {
  18879. this._transformedDirection.y = 0;
  18880. }
  18881. if (!this.target.getAbsolutePosition) {
  18882. this.target.addInPlace(this._transformedDirection);
  18883. }
  18884. }
  18885. // Limits
  18886. this._checkLimits();
  18887. _super.prototype._checkInputs.call(this);
  18888. };
  18889. ArcRotateCamera.prototype._checkLimits = function () {
  18890. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  18891. if (this.allowUpsideDown && this.beta > Math.PI) {
  18892. this.beta = this.beta - (2 * Math.PI);
  18893. }
  18894. }
  18895. else {
  18896. if (this.beta < this.lowerBetaLimit) {
  18897. this.beta = this.lowerBetaLimit;
  18898. }
  18899. }
  18900. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  18901. if (this.allowUpsideDown && this.beta < -Math.PI) {
  18902. this.beta = this.beta + (2 * Math.PI);
  18903. }
  18904. }
  18905. else {
  18906. if (this.beta > this.upperBetaLimit) {
  18907. this.beta = this.upperBetaLimit;
  18908. }
  18909. }
  18910. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  18911. this.alpha = this.lowerAlphaLimit;
  18912. }
  18913. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  18914. this.alpha = this.upperAlphaLimit;
  18915. }
  18916. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  18917. this.radius = this.lowerRadiusLimit;
  18918. }
  18919. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  18920. this.radius = this.upperRadiusLimit;
  18921. }
  18922. };
  18923. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  18924. var radiusv3 = this.position.subtract(this._getTargetPosition());
  18925. this.radius = radiusv3.length();
  18926. // Alpha
  18927. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  18928. if (radiusv3.z < 0) {
  18929. this.alpha = 2 * Math.PI - this.alpha;
  18930. }
  18931. // Beta
  18932. this.beta = Math.acos(radiusv3.y / this.radius);
  18933. this._checkLimits();
  18934. };
  18935. ArcRotateCamera.prototype.setPosition = function (position) {
  18936. if (this.position.equals(position)) {
  18937. return;
  18938. }
  18939. this.position.copyFrom(position);
  18940. this.rebuildAnglesAndRadius();
  18941. };
  18942. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  18943. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  18944. if (allowSamePosition === void 0) { allowSamePosition = false; }
  18945. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  18946. return;
  18947. }
  18948. if (toBoundingCenter && target.getBoundingInfo) {
  18949. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  18950. }
  18951. else {
  18952. this._targetBoundingCenter = null;
  18953. }
  18954. this.target = target;
  18955. this.rebuildAnglesAndRadius();
  18956. };
  18957. ArcRotateCamera.prototype._getViewMatrix = function () {
  18958. // Compute
  18959. var cosa = Math.cos(this.alpha);
  18960. var sina = Math.sin(this.alpha);
  18961. var cosb = Math.cos(this.beta);
  18962. var sinb = Math.sin(this.beta);
  18963. if (sinb === 0) {
  18964. sinb = 0.0001;
  18965. }
  18966. var target = this._getTargetPosition();
  18967. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  18968. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  18969. this._collider.radius = this.collisionRadius;
  18970. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  18971. this._collisionTriggered = true;
  18972. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  18973. }
  18974. else {
  18975. this.position.copyFrom(this._newPosition);
  18976. var up = this.upVector;
  18977. if (this.allowUpsideDown && sinb < 0) {
  18978. up = up.clone();
  18979. up = up.negate();
  18980. }
  18981. if (this.getScene().useRightHandedSystem) {
  18982. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  18983. }
  18984. else {
  18985. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  18986. }
  18987. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  18988. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  18989. }
  18990. this._currentTarget = target;
  18991. return this._viewMatrix;
  18992. };
  18993. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  18994. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18995. meshes = meshes || this.getScene().meshes;
  18996. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  18997. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  18998. this.radius = distance * this.zoomOnFactor;
  18999. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  19000. };
  19001. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  19002. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  19003. var meshesOrMinMaxVector;
  19004. var distance;
  19005. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  19006. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  19007. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  19008. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  19009. }
  19010. else {
  19011. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  19012. distance = meshesOrMinMaxVectorAndDistance.distance;
  19013. }
  19014. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  19015. if (!doNotUpdateMaxZ) {
  19016. this.maxZ = distance * 2;
  19017. }
  19018. };
  19019. /**
  19020. * @override
  19021. * Override Camera.createRigCamera
  19022. */
  19023. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  19024. var alphaShift;
  19025. switch (this.cameraRigMode) {
  19026. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19027. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19028. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19029. case BABYLON.Camera.RIG_MODE_VR:
  19030. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  19031. break;
  19032. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19033. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  19034. break;
  19035. }
  19036. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  19037. rigCam._cameraRigParams = {};
  19038. return rigCam;
  19039. };
  19040. /**
  19041. * @override
  19042. * Override Camera._updateRigCameras
  19043. */
  19044. ArcRotateCamera.prototype._updateRigCameras = function () {
  19045. var camLeft = this._rigCameras[0];
  19046. var camRight = this._rigCameras[1];
  19047. camLeft.beta = camRight.beta = this.beta;
  19048. camLeft.radius = camRight.radius = this.radius;
  19049. switch (this.cameraRigMode) {
  19050. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19051. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19052. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19053. case BABYLON.Camera.RIG_MODE_VR:
  19054. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  19055. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  19056. break;
  19057. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19058. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  19059. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  19060. break;
  19061. }
  19062. _super.prototype._updateRigCameras.call(this);
  19063. };
  19064. ArcRotateCamera.prototype.dispose = function () {
  19065. this.inputs.clear();
  19066. _super.prototype.dispose.call(this);
  19067. };
  19068. ArcRotateCamera.prototype.getClassName = function () {
  19069. return "ArcRotateCamera";
  19070. };
  19071. return ArcRotateCamera;
  19072. }(BABYLON.TargetCamera));
  19073. __decorate([
  19074. BABYLON.serialize()
  19075. ], ArcRotateCamera.prototype, "alpha", void 0);
  19076. __decorate([
  19077. BABYLON.serialize()
  19078. ], ArcRotateCamera.prototype, "beta", void 0);
  19079. __decorate([
  19080. BABYLON.serialize()
  19081. ], ArcRotateCamera.prototype, "radius", void 0);
  19082. __decorate([
  19083. BABYLON.serializeAsVector3()
  19084. ], ArcRotateCamera.prototype, "target", void 0);
  19085. __decorate([
  19086. BABYLON.serialize()
  19087. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  19088. __decorate([
  19089. BABYLON.serialize()
  19090. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  19091. __decorate([
  19092. BABYLON.serialize()
  19093. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  19094. __decorate([
  19095. BABYLON.serialize()
  19096. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  19097. __decorate([
  19098. BABYLON.serialize()
  19099. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  19100. __decorate([
  19101. BABYLON.serialize()
  19102. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  19103. __decorate([
  19104. BABYLON.serialize()
  19105. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  19106. __decorate([
  19107. BABYLON.serialize()
  19108. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  19109. __decorate([
  19110. BABYLON.serialize()
  19111. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  19112. __decorate([
  19113. BABYLON.serialize()
  19114. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  19115. __decorate([
  19116. BABYLON.serialize()
  19117. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  19118. __decorate([
  19119. BABYLON.serialize()
  19120. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  19121. __decorate([
  19122. BABYLON.serialize()
  19123. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  19124. BABYLON.ArcRotateCamera = ArcRotateCamera;
  19125. })(BABYLON || (BABYLON = {}));
  19126. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  19127. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  19128. var BABYLON;
  19129. (function (BABYLON) {
  19130. var ArcRotateCameraInputsManager = (function (_super) {
  19131. __extends(ArcRotateCameraInputsManager, _super);
  19132. function ArcRotateCameraInputsManager(camera) {
  19133. return _super.call(this, camera) || this;
  19134. }
  19135. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  19136. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  19137. return this;
  19138. };
  19139. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  19140. this.add(new BABYLON.ArcRotateCameraPointersInput());
  19141. return this;
  19142. };
  19143. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  19144. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  19145. return this;
  19146. };
  19147. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  19148. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  19149. return this;
  19150. };
  19151. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  19152. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  19153. return this;
  19154. };
  19155. return ArcRotateCameraInputsManager;
  19156. }(BABYLON.CameraInputsManager));
  19157. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  19158. })(BABYLON || (BABYLON = {}));
  19159. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  19160. var BABYLON;
  19161. (function (BABYLON) {
  19162. var RenderingManager = (function () {
  19163. function RenderingManager(scene) {
  19164. this._renderingGroups = new Array();
  19165. this._autoClearDepthStencil = {};
  19166. this._customOpaqueSortCompareFn = {};
  19167. this._customAlphaTestSortCompareFn = {};
  19168. this._customTransparentSortCompareFn = {};
  19169. this._renderinGroupInfo = null;
  19170. this._scene = scene;
  19171. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  19172. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  19173. }
  19174. }
  19175. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  19176. if (depth === void 0) { depth = true; }
  19177. if (stencil === void 0) { stencil = true; }
  19178. if (this._depthStencilBufferAlreadyCleaned) {
  19179. return;
  19180. }
  19181. this._scene.getEngine().clear(null, false, depth, stencil);
  19182. this._depthStencilBufferAlreadyCleaned = true;
  19183. };
  19184. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  19185. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  19186. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  19187. var info = null;
  19188. if (observable) {
  19189. if (!this._renderinGroupInfo) {
  19190. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  19191. }
  19192. info = this._renderinGroupInfo;
  19193. info.scene = this._scene;
  19194. info.camera = this._scene.activeCamera;
  19195. }
  19196. // Dispatch sprites
  19197. if (renderSprites) {
  19198. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  19199. var manager = this._scene.spriteManagers[index];
  19200. this.dispatchSprites(manager);
  19201. }
  19202. }
  19203. // Render
  19204. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19205. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  19206. var renderingGroup = this._renderingGroups[index];
  19207. if (!renderingGroup && !observable)
  19208. continue;
  19209. this._currentIndex = index;
  19210. var renderingGroupMask = 0;
  19211. // Fire PRECLEAR stage
  19212. if (observable) {
  19213. renderingGroupMask = Math.pow(2, index);
  19214. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  19215. info.renderingGroupId = index;
  19216. observable.notifyObservers(info, renderingGroupMask);
  19217. }
  19218. // Clear depth/stencil if needed
  19219. var autoClear = this._autoClearDepthStencil[index];
  19220. if (autoClear && autoClear.autoClear) {
  19221. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  19222. }
  19223. if (observable) {
  19224. // Fire PREOPAQUE stage
  19225. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  19226. observable.notifyObservers(info, renderingGroupMask);
  19227. // Fire PRETRANSPARENT stage
  19228. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  19229. observable.notifyObservers(info, renderingGroupMask);
  19230. }
  19231. if (renderingGroup)
  19232. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  19233. // Fire POSTTRANSPARENT stage
  19234. if (observable) {
  19235. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  19236. observable.notifyObservers(info, renderingGroupMask);
  19237. }
  19238. }
  19239. };
  19240. RenderingManager.prototype.reset = function () {
  19241. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19242. var renderingGroup = this._renderingGroups[index];
  19243. if (renderingGroup) {
  19244. renderingGroup.prepare();
  19245. }
  19246. }
  19247. };
  19248. RenderingManager.prototype.dispose = function () {
  19249. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19250. var renderingGroup = this._renderingGroups[index];
  19251. if (renderingGroup) {
  19252. renderingGroup.dispose();
  19253. }
  19254. }
  19255. this._renderingGroups.length = 0;
  19256. };
  19257. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  19258. if (!this._renderingGroups[renderingGroupId]) {
  19259. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  19260. }
  19261. };
  19262. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  19263. var renderingGroupId = spriteManager.renderingGroupId || 0;
  19264. this._prepareRenderingGroup(renderingGroupId);
  19265. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  19266. };
  19267. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  19268. var renderingGroupId = particleSystem.renderingGroupId || 0;
  19269. this._prepareRenderingGroup(renderingGroupId);
  19270. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  19271. };
  19272. RenderingManager.prototype.dispatch = function (subMesh) {
  19273. var mesh = subMesh.getMesh();
  19274. var renderingGroupId = mesh.renderingGroupId || 0;
  19275. this._prepareRenderingGroup(renderingGroupId);
  19276. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  19277. };
  19278. /**
  19279. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19280. * This allowed control for front to back rendering or reversly depending of the special needs.
  19281. *
  19282. * @param renderingGroupId The rendering group id corresponding to its index
  19283. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19284. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19285. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19286. */
  19287. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19288. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19289. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19290. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19291. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  19292. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  19293. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  19294. if (this._renderingGroups[renderingGroupId]) {
  19295. var group = this._renderingGroups[renderingGroupId];
  19296. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  19297. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  19298. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  19299. }
  19300. };
  19301. /**
  19302. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19303. *
  19304. * @param renderingGroupId The rendering group id corresponding to its index
  19305. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19306. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19307. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19308. */
  19309. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19310. if (depth === void 0) { depth = true; }
  19311. if (stencil === void 0) { stencil = true; }
  19312. this._autoClearDepthStencil[renderingGroupId] = {
  19313. autoClear: autoClearDepthStencil,
  19314. depth: depth,
  19315. stencil: stencil
  19316. };
  19317. };
  19318. return RenderingManager;
  19319. }());
  19320. /**
  19321. * The max id used for rendering groups (not included)
  19322. */
  19323. RenderingManager.MAX_RENDERINGGROUPS = 4;
  19324. /**
  19325. * The min id used for rendering groups (included)
  19326. */
  19327. RenderingManager.MIN_RENDERINGGROUPS = 0;
  19328. BABYLON.RenderingManager = RenderingManager;
  19329. })(BABYLON || (BABYLON = {}));
  19330. //# sourceMappingURL=babylon.renderingManager.js.map
  19331. var BABYLON;
  19332. (function (BABYLON) {
  19333. var RenderingGroup = (function () {
  19334. /**
  19335. * Creates a new rendering group.
  19336. * @param index The rendering group index
  19337. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19338. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19339. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19340. */
  19341. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19342. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19343. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19344. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19345. this.index = index;
  19346. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19347. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19348. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19349. this._particleSystems = new BABYLON.SmartArray(256);
  19350. this._spriteManagers = new BABYLON.SmartArray(256);
  19351. this._scene = scene;
  19352. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19353. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19354. this.transparentSortCompareFn = transparentSortCompareFn;
  19355. }
  19356. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19357. /**
  19358. * Set the opaque sort comparison function.
  19359. * If null the sub meshes will be render in the order they were created
  19360. */
  19361. set: function (value) {
  19362. this._opaqueSortCompareFn = value;
  19363. if (value) {
  19364. this._renderOpaque = this.renderOpaqueSorted;
  19365. }
  19366. else {
  19367. this._renderOpaque = RenderingGroup.renderUnsorted;
  19368. }
  19369. },
  19370. enumerable: true,
  19371. configurable: true
  19372. });
  19373. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19374. /**
  19375. * Set the alpha test sort comparison function.
  19376. * If null the sub meshes will be render in the order they were created
  19377. */
  19378. set: function (value) {
  19379. this._alphaTestSortCompareFn = value;
  19380. if (value) {
  19381. this._renderAlphaTest = this.renderAlphaTestSorted;
  19382. }
  19383. else {
  19384. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19385. }
  19386. },
  19387. enumerable: true,
  19388. configurable: true
  19389. });
  19390. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19391. /**
  19392. * Set the transparent sort comparison function.
  19393. * If null the sub meshes will be render in the order they were created
  19394. */
  19395. set: function (value) {
  19396. if (value) {
  19397. this._transparentSortCompareFn = value;
  19398. }
  19399. else {
  19400. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19401. }
  19402. this._renderTransparent = this.renderTransparentSorted;
  19403. },
  19404. enumerable: true,
  19405. configurable: true
  19406. });
  19407. /**
  19408. * Render all the sub meshes contained in the group.
  19409. * @param customRenderFunction Used to override the default render behaviour of the group.
  19410. * @returns true if rendered some submeshes.
  19411. */
  19412. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19413. if (customRenderFunction) {
  19414. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  19415. return;
  19416. }
  19417. var engine = this._scene.getEngine();
  19418. // Opaque
  19419. if (this._opaqueSubMeshes.length !== 0) {
  19420. this._renderOpaque(this._opaqueSubMeshes);
  19421. }
  19422. // Alpha test
  19423. if (this._alphaTestSubMeshes.length !== 0) {
  19424. engine.setAlphaTesting(true);
  19425. this._renderAlphaTest(this._alphaTestSubMeshes);
  19426. engine.setAlphaTesting(false);
  19427. }
  19428. // Sprites
  19429. if (renderSprites) {
  19430. this._renderSprites();
  19431. }
  19432. // Particles
  19433. if (renderParticles) {
  19434. this._renderParticles(activeMeshes);
  19435. }
  19436. if (this.onBeforeTransparentRendering) {
  19437. this.onBeforeTransparentRendering();
  19438. }
  19439. // Transparent
  19440. if (this._transparentSubMeshes.length !== 0) {
  19441. this._renderTransparent(this._transparentSubMeshes);
  19442. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19443. }
  19444. };
  19445. /**
  19446. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19447. * @param subMeshes The submeshes to render
  19448. */
  19449. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19450. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  19451. };
  19452. /**
  19453. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19454. * @param subMeshes The submeshes to render
  19455. */
  19456. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19457. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  19458. };
  19459. /**
  19460. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19461. * @param subMeshes The submeshes to render
  19462. */
  19463. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19464. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  19465. };
  19466. /**
  19467. * Renders the submeshes in a specified order.
  19468. * @param subMeshes The submeshes to sort before render
  19469. * @param sortCompareFn The comparison function use to sort
  19470. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19471. * @param transparent Specifies to activate blending if true
  19472. */
  19473. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  19474. var subIndex = 0;
  19475. var subMesh;
  19476. for (; subIndex < subMeshes.length; subIndex++) {
  19477. subMesh = subMeshes.data[subIndex];
  19478. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19479. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19480. }
  19481. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19482. sortedArray.sort(sortCompareFn);
  19483. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19484. subMesh = sortedArray[subIndex];
  19485. subMesh.render(transparent);
  19486. }
  19487. };
  19488. /**
  19489. * Renders the submeshes in the order they were dispatched (no sort applied).
  19490. * @param subMeshes The submeshes to render
  19491. */
  19492. RenderingGroup.renderUnsorted = function (subMeshes) {
  19493. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19494. var submesh = subMeshes.data[subIndex];
  19495. submesh.render(false);
  19496. }
  19497. };
  19498. /**
  19499. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19500. * are rendered back to front if in the same alpha index.
  19501. *
  19502. * @param a The first submesh
  19503. * @param b The second submesh
  19504. * @returns The result of the comparison
  19505. */
  19506. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19507. // Alpha index first
  19508. if (a._alphaIndex > b._alphaIndex) {
  19509. return 1;
  19510. }
  19511. if (a._alphaIndex < b._alphaIndex) {
  19512. return -1;
  19513. }
  19514. // Then distance to camera
  19515. return RenderingGroup.backToFrontSortCompare(a, b);
  19516. };
  19517. /**
  19518. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19519. * are rendered back to front.
  19520. *
  19521. * @param a The first submesh
  19522. * @param b The second submesh
  19523. * @returns The result of the comparison
  19524. */
  19525. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19526. // Then distance to camera
  19527. if (a._distanceToCamera < b._distanceToCamera) {
  19528. return 1;
  19529. }
  19530. if (a._distanceToCamera > b._distanceToCamera) {
  19531. return -1;
  19532. }
  19533. return 0;
  19534. };
  19535. /**
  19536. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19537. * are rendered front to back (prevent overdraw).
  19538. *
  19539. * @param a The first submesh
  19540. * @param b The second submesh
  19541. * @returns The result of the comparison
  19542. */
  19543. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19544. // Then distance to camera
  19545. if (a._distanceToCamera < b._distanceToCamera) {
  19546. return -1;
  19547. }
  19548. if (a._distanceToCamera > b._distanceToCamera) {
  19549. return 1;
  19550. }
  19551. return 0;
  19552. };
  19553. /**
  19554. * Resets the different lists of submeshes to prepare a new frame.
  19555. */
  19556. RenderingGroup.prototype.prepare = function () {
  19557. this._opaqueSubMeshes.reset();
  19558. this._transparentSubMeshes.reset();
  19559. this._alphaTestSubMeshes.reset();
  19560. this._particleSystems.reset();
  19561. this._spriteManagers.reset();
  19562. };
  19563. RenderingGroup.prototype.dispose = function () {
  19564. this._opaqueSubMeshes.dispose();
  19565. this._transparentSubMeshes.dispose();
  19566. this._alphaTestSubMeshes.dispose();
  19567. this._particleSystems.dispose();
  19568. this._spriteManagers.dispose();
  19569. };
  19570. /**
  19571. * Inserts the submesh in its correct queue depending on its material.
  19572. * @param subMesh The submesh to dispatch
  19573. */
  19574. RenderingGroup.prototype.dispatch = function (subMesh) {
  19575. var material = subMesh.getMaterial();
  19576. var mesh = subMesh.getMesh();
  19577. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  19578. this._transparentSubMeshes.push(subMesh);
  19579. }
  19580. else if (material.needAlphaTesting()) {
  19581. this._alphaTestSubMeshes.push(subMesh);
  19582. }
  19583. else {
  19584. this._opaqueSubMeshes.push(subMesh); // Opaque
  19585. }
  19586. };
  19587. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19588. this._spriteManagers.push(spriteManager);
  19589. };
  19590. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19591. this._particleSystems.push(particleSystem);
  19592. };
  19593. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19594. if (this._particleSystems.length === 0) {
  19595. return;
  19596. }
  19597. // Particles
  19598. var activeCamera = this._scene.activeCamera;
  19599. this._scene._particlesDuration.beginMonitoring();
  19600. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19601. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19602. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19603. continue;
  19604. }
  19605. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  19606. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19607. }
  19608. }
  19609. this._scene._particlesDuration.endMonitoring(false);
  19610. };
  19611. RenderingGroup.prototype._renderSprites = function () {
  19612. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19613. return;
  19614. }
  19615. // Sprites
  19616. var activeCamera = this._scene.activeCamera;
  19617. this._scene._spritesDuration.beginMonitoring();
  19618. for (var id = 0; id < this._spriteManagers.length; id++) {
  19619. var spriteManager = this._spriteManagers.data[id];
  19620. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19621. spriteManager.render();
  19622. }
  19623. }
  19624. this._scene._spritesDuration.endMonitoring(false);
  19625. };
  19626. return RenderingGroup;
  19627. }());
  19628. BABYLON.RenderingGroup = RenderingGroup;
  19629. })(BABYLON || (BABYLON = {}));
  19630. //# sourceMappingURL=babylon.renderingGroup.js.map
  19631. var BABYLON;
  19632. (function (BABYLON) {
  19633. var ClickInfo = (function () {
  19634. function ClickInfo() {
  19635. this._singleClick = false;
  19636. this._doubleClick = false;
  19637. this._hasSwiped = false;
  19638. this._ignore = false;
  19639. }
  19640. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19641. get: function () {
  19642. return this._singleClick;
  19643. },
  19644. set: function (b) {
  19645. this._singleClick = b;
  19646. },
  19647. enumerable: true,
  19648. configurable: true
  19649. });
  19650. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19651. get: function () {
  19652. return this._doubleClick;
  19653. },
  19654. set: function (b) {
  19655. this._doubleClick = b;
  19656. },
  19657. enumerable: true,
  19658. configurable: true
  19659. });
  19660. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19661. get: function () {
  19662. return this._hasSwiped;
  19663. },
  19664. set: function (b) {
  19665. this._hasSwiped = b;
  19666. },
  19667. enumerable: true,
  19668. configurable: true
  19669. });
  19670. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19671. get: function () {
  19672. return this._ignore;
  19673. },
  19674. set: function (b) {
  19675. this._ignore = b;
  19676. },
  19677. enumerable: true,
  19678. configurable: true
  19679. });
  19680. return ClickInfo;
  19681. }());
  19682. var PointerEventTypes = (function () {
  19683. function PointerEventTypes() {
  19684. }
  19685. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  19686. get: function () {
  19687. return PointerEventTypes._POINTERDOWN;
  19688. },
  19689. enumerable: true,
  19690. configurable: true
  19691. });
  19692. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  19693. get: function () {
  19694. return PointerEventTypes._POINTERUP;
  19695. },
  19696. enumerable: true,
  19697. configurable: true
  19698. });
  19699. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  19700. get: function () {
  19701. return PointerEventTypes._POINTERMOVE;
  19702. },
  19703. enumerable: true,
  19704. configurable: true
  19705. });
  19706. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  19707. get: function () {
  19708. return PointerEventTypes._POINTERWHEEL;
  19709. },
  19710. enumerable: true,
  19711. configurable: true
  19712. });
  19713. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  19714. get: function () {
  19715. return PointerEventTypes._POINTERPICK;
  19716. },
  19717. enumerable: true,
  19718. configurable: true
  19719. });
  19720. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  19721. get: function () {
  19722. return PointerEventTypes._POINTERTAP;
  19723. },
  19724. enumerable: true,
  19725. configurable: true
  19726. });
  19727. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  19728. get: function () {
  19729. return PointerEventTypes._POINTERDOUBLETAP;
  19730. },
  19731. enumerable: true,
  19732. configurable: true
  19733. });
  19734. return PointerEventTypes;
  19735. }());
  19736. PointerEventTypes._POINTERDOWN = 0x01;
  19737. PointerEventTypes._POINTERUP = 0x02;
  19738. PointerEventTypes._POINTERMOVE = 0x04;
  19739. PointerEventTypes._POINTERWHEEL = 0x08;
  19740. PointerEventTypes._POINTERPICK = 0x10;
  19741. PointerEventTypes._POINTERTAP = 0x20;
  19742. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  19743. BABYLON.PointerEventTypes = PointerEventTypes;
  19744. var PointerInfoBase = (function () {
  19745. function PointerInfoBase(type, event) {
  19746. this.type = type;
  19747. this.event = event;
  19748. }
  19749. return PointerInfoBase;
  19750. }());
  19751. BABYLON.PointerInfoBase = PointerInfoBase;
  19752. /**
  19753. * This class is used to store pointer related info for the onPrePointerObservable event.
  19754. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  19755. */
  19756. var PointerInfoPre = (function (_super) {
  19757. __extends(PointerInfoPre, _super);
  19758. function PointerInfoPre(type, event, localX, localY) {
  19759. var _this = _super.call(this, type, event) || this;
  19760. _this.skipOnPointerObservable = false;
  19761. _this.localPosition = new BABYLON.Vector2(localX, localY);
  19762. return _this;
  19763. }
  19764. return PointerInfoPre;
  19765. }(PointerInfoBase));
  19766. BABYLON.PointerInfoPre = PointerInfoPre;
  19767. /**
  19768. * This type contains all the data related to a pointer event in Babylon.js.
  19769. * 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.
  19770. */
  19771. var PointerInfo = (function (_super) {
  19772. __extends(PointerInfo, _super);
  19773. function PointerInfo(type, event, pickInfo) {
  19774. var _this = _super.call(this, type, event) || this;
  19775. _this.pickInfo = pickInfo;
  19776. return _this;
  19777. }
  19778. return PointerInfo;
  19779. }(PointerInfoBase));
  19780. BABYLON.PointerInfo = PointerInfo;
  19781. /**
  19782. * This class is used by the onRenderingGroupObservable
  19783. */
  19784. var RenderingGroupInfo = (function () {
  19785. function RenderingGroupInfo() {
  19786. }
  19787. return RenderingGroupInfo;
  19788. }());
  19789. /**
  19790. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19791. * This stage will be fired no matter what
  19792. */
  19793. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19794. /**
  19795. * Called before opaque object are rendered.
  19796. * This stage will be fired only if there's 3D Opaque content to render
  19797. */
  19798. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19799. /**
  19800. * Called after the opaque objects are rendered and before the transparent ones
  19801. * This stage will be fired only if there's 3D transparent content to render
  19802. */
  19803. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19804. /**
  19805. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19806. * This stage will be fired no matter what
  19807. */
  19808. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19809. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19810. /**
  19811. * Represents a scene to be rendered by the engine.
  19812. * @see http://doc.babylonjs.com/page.php?p=21911
  19813. */
  19814. var Scene = (function () {
  19815. /**
  19816. * @constructor
  19817. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19818. */
  19819. function Scene(engine) {
  19820. // Members
  19821. this.autoClear = true;
  19822. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19823. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19824. this.forceWireframe = false;
  19825. this._forcePointsCloud = false;
  19826. this.forceShowBoundingBoxes = false;
  19827. this.animationsEnabled = true;
  19828. this.constantlyUpdateMeshUnderPointer = false;
  19829. this.useRightHandedSystem = false;
  19830. this.hoverCursor = "pointer";
  19831. // Metadata
  19832. this.metadata = null;
  19833. // Events
  19834. /**
  19835. * An event triggered when the scene is disposed.
  19836. * @type {BABYLON.Observable}
  19837. */
  19838. this.onDisposeObservable = new BABYLON.Observable();
  19839. /**
  19840. * An event triggered before rendering the scene
  19841. * @type {BABYLON.Observable}
  19842. */
  19843. this.onBeforeRenderObservable = new BABYLON.Observable();
  19844. /**
  19845. * An event triggered after rendering the scene
  19846. * @type {BABYLON.Observable}
  19847. */
  19848. this.onAfterRenderObservable = new BABYLON.Observable();
  19849. /**
  19850. * An event triggered when the scene is ready
  19851. * @type {BABYLON.Observable}
  19852. */
  19853. this.onReadyObservable = new BABYLON.Observable();
  19854. /**
  19855. * An event triggered before rendering a camera
  19856. * @type {BABYLON.Observable}
  19857. */
  19858. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19859. /**
  19860. * An event triggered after rendering a camera
  19861. * @type {BABYLON.Observable}
  19862. */
  19863. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19864. /**
  19865. * An event triggered when a camera is created
  19866. * @type {BABYLON.Observable}
  19867. */
  19868. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19869. /**
  19870. * An event triggered when a camera is removed
  19871. * @type {BABYLON.Observable}
  19872. */
  19873. this.onCameraRemovedObservable = new BABYLON.Observable();
  19874. /**
  19875. * An event triggered when a light is created
  19876. * @type {BABYLON.Observable}
  19877. */
  19878. this.onNewLightAddedObservable = new BABYLON.Observable();
  19879. /**
  19880. * An event triggered when a light is removed
  19881. * @type {BABYLON.Observable}
  19882. */
  19883. this.onLightRemovedObservable = new BABYLON.Observable();
  19884. /**
  19885. * An event triggered when a geometry is created
  19886. * @type {BABYLON.Observable}
  19887. */
  19888. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19889. /**
  19890. * An event triggered when a geometry is removed
  19891. * @type {BABYLON.Observable}
  19892. */
  19893. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19894. /**
  19895. * An event triggered when a mesh is created
  19896. * @type {BABYLON.Observable}
  19897. */
  19898. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19899. /**
  19900. * An event triggered when a mesh is removed
  19901. * @type {BABYLON.Observable}
  19902. */
  19903. this.onMeshRemovedObservable = new BABYLON.Observable();
  19904. /**
  19905. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19906. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19907. * 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)
  19908. */
  19909. this.onRenderingGroupObservable = new BABYLON.Observable();
  19910. // Animations
  19911. this.animations = [];
  19912. /**
  19913. * 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).
  19914. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  19915. */
  19916. this.onPrePointerObservable = new BABYLON.Observable();
  19917. /**
  19918. * Observable event triggered each time an input event is received from the rendering canvas
  19919. */
  19920. this.onPointerObservable = new BABYLON.Observable();
  19921. this._meshPickProceed = false;
  19922. this._previousHasSwiped = false;
  19923. this._currentPickResult = null;
  19924. this._previousPickResult = null;
  19925. this._isButtonPressed = false;
  19926. this._doubleClickOccured = false;
  19927. 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
  19928. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19929. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19930. this._startingPointerTime = 0;
  19931. this._previousStartingPointerTime = 0;
  19932. // Fog
  19933. /**
  19934. * is fog enabled on this scene.
  19935. * @type {boolean}
  19936. */
  19937. this._fogEnabled = true;
  19938. this._fogMode = Scene.FOGMODE_NONE;
  19939. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19940. this.fogDensity = 0.1;
  19941. this.fogStart = 0;
  19942. this.fogEnd = 1000.0;
  19943. // Lights
  19944. /**
  19945. * is shadow enabled on this scene.
  19946. * @type {boolean}
  19947. */
  19948. this._shadowsEnabled = true;
  19949. /**
  19950. * is light enabled on this scene.
  19951. * @type {boolean}
  19952. */
  19953. this._lightsEnabled = true;
  19954. /**
  19955. * All of the lights added to this scene.
  19956. * @see BABYLON.Light
  19957. * @type {BABYLON.Light[]}
  19958. */
  19959. this.lights = new Array();
  19960. // Cameras
  19961. /**
  19962. * All of the cameras added to this scene.
  19963. * @see BABYLON.Camera
  19964. * @type {BABYLON.Camera[]}
  19965. */
  19966. this.cameras = new Array();
  19967. this.activeCameras = new Array();
  19968. // Meshes
  19969. /**
  19970. * All of the (abstract) meshes added to this scene.
  19971. * @see BABYLON.AbstractMesh
  19972. * @type {BABYLON.AbstractMesh[]}
  19973. */
  19974. this.meshes = new Array();
  19975. // Geometries
  19976. this._geometries = new Array();
  19977. this.materials = new Array();
  19978. this.multiMaterials = new Array();
  19979. // Textures
  19980. this._texturesEnabled = true;
  19981. this.textures = new Array();
  19982. // Particles
  19983. this.particlesEnabled = true;
  19984. this.particleSystems = new Array();
  19985. // Sprites
  19986. this.spritesEnabled = true;
  19987. this.spriteManagers = new Array();
  19988. // Layers
  19989. this.layers = new Array();
  19990. this.highlightLayers = new Array();
  19991. // Skeletons
  19992. this._skeletonsEnabled = true;
  19993. this.skeletons = new Array();
  19994. // Lens flares
  19995. this.lensFlaresEnabled = true;
  19996. this.lensFlareSystems = new Array();
  19997. // Collisions
  19998. this.collisionsEnabled = true;
  19999. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20000. // Postprocesses
  20001. this.postProcessesEnabled = true;
  20002. // Customs render targets
  20003. this.renderTargetsEnabled = true;
  20004. this.dumpNextRenderTargets = false;
  20005. this.customRenderTargets = new Array();
  20006. // Imported meshes
  20007. this.importedMeshesFiles = new Array();
  20008. // Probes
  20009. this.probesEnabled = true;
  20010. this.reflectionProbes = new Array();
  20011. this._actionManagers = new Array();
  20012. this._meshesForIntersections = new BABYLON.SmartArray(256);
  20013. // Procedural textures
  20014. this.proceduralTexturesEnabled = true;
  20015. this._proceduralTextures = new Array();
  20016. this.soundTracks = new Array();
  20017. this._audioEnabled = true;
  20018. this._headphone = false;
  20019. // Performance counters
  20020. this._totalMeshesCounter = new BABYLON.PerfCounter();
  20021. this._totalLightsCounter = new BABYLON.PerfCounter();
  20022. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  20023. this._totalTexturesCounter = new BABYLON.PerfCounter();
  20024. this._totalVertices = new BABYLON.PerfCounter();
  20025. this._activeIndices = new BABYLON.PerfCounter();
  20026. this._activeParticles = new BABYLON.PerfCounter();
  20027. this._lastFrameDuration = new BABYLON.PerfCounter();
  20028. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  20029. this._renderTargetsDuration = new BABYLON.PerfCounter();
  20030. this._particlesDuration = new BABYLON.PerfCounter();
  20031. this._renderDuration = new BABYLON.PerfCounter();
  20032. this._spritesDuration = new BABYLON.PerfCounter();
  20033. this._activeBones = new BABYLON.PerfCounter();
  20034. this._animationTime = 0;
  20035. this.animationTimeScale = 1;
  20036. this._renderId = 0;
  20037. this._executeWhenReadyTimeoutId = -1;
  20038. this._intermediateRendering = false;
  20039. this._toBeDisposed = new BABYLON.SmartArray(256);
  20040. this._pendingData = []; //ANY
  20041. this._activeMeshes = new BABYLON.SmartArray(256);
  20042. this._processedMaterials = new BABYLON.SmartArray(256);
  20043. this._renderTargets = new BABYLON.SmartArray(256);
  20044. this._activeParticleSystems = new BABYLON.SmartArray(256);
  20045. this._activeSkeletons = new BABYLON.SmartArray(32);
  20046. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  20047. this._activeAnimatables = new Array();
  20048. this._transformMatrix = BABYLON.Matrix.Zero();
  20049. this._edgesRenderers = new BABYLON.SmartArray(16);
  20050. this._uniqueIdCounter = 0;
  20051. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  20052. this._engine.scenes.push(this);
  20053. this._externalData = new BABYLON.StringDictionary();
  20054. this._uid = null;
  20055. this._renderingManager = new BABYLON.RenderingManager(this);
  20056. this.postProcessManager = new BABYLON.PostProcessManager(this);
  20057. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  20058. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20059. if (BABYLON.OutlineRenderer) {
  20060. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  20061. }
  20062. this.attachControl();
  20063. if (BABYLON.SoundTrack) {
  20064. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  20065. }
  20066. //simplification queue
  20067. if (BABYLON.SimplificationQueue) {
  20068. this.simplificationQueue = new BABYLON.SimplificationQueue();
  20069. }
  20070. //collision coordinator initialization. For now legacy per default.
  20071. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  20072. }
  20073. Object.defineProperty(Scene, "FOGMODE_NONE", {
  20074. get: function () {
  20075. return Scene._FOGMODE_NONE;
  20076. },
  20077. enumerable: true,
  20078. configurable: true
  20079. });
  20080. Object.defineProperty(Scene, "FOGMODE_EXP", {
  20081. get: function () {
  20082. return Scene._FOGMODE_EXP;
  20083. },
  20084. enumerable: true,
  20085. configurable: true
  20086. });
  20087. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  20088. get: function () {
  20089. return Scene._FOGMODE_EXP2;
  20090. },
  20091. enumerable: true,
  20092. configurable: true
  20093. });
  20094. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  20095. get: function () {
  20096. return Scene._FOGMODE_LINEAR;
  20097. },
  20098. enumerable: true,
  20099. configurable: true
  20100. });
  20101. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  20102. get: function () {
  20103. return this._forcePointsCloud;
  20104. },
  20105. set: function (value) {
  20106. if (this._forcePointsCloud === value) {
  20107. return;
  20108. }
  20109. this._forcePointsCloud = value;
  20110. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20111. },
  20112. enumerable: true,
  20113. configurable: true
  20114. });
  20115. Object.defineProperty(Scene.prototype, "onDispose", {
  20116. set: function (callback) {
  20117. if (this._onDisposeObserver) {
  20118. this.onDisposeObservable.remove(this._onDisposeObserver);
  20119. }
  20120. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20121. },
  20122. enumerable: true,
  20123. configurable: true
  20124. });
  20125. Object.defineProperty(Scene.prototype, "beforeRender", {
  20126. set: function (callback) {
  20127. if (this._onBeforeRenderObserver) {
  20128. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  20129. }
  20130. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  20131. },
  20132. enumerable: true,
  20133. configurable: true
  20134. });
  20135. Object.defineProperty(Scene.prototype, "afterRender", {
  20136. set: function (callback) {
  20137. if (this._onAfterRenderObserver) {
  20138. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  20139. }
  20140. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  20141. },
  20142. enumerable: true,
  20143. configurable: true
  20144. });
  20145. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  20146. set: function (callback) {
  20147. if (this._onBeforeCameraRenderObserver) {
  20148. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  20149. }
  20150. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  20151. },
  20152. enumerable: true,
  20153. configurable: true
  20154. });
  20155. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  20156. set: function (callback) {
  20157. if (this._onAfterCameraRenderObserver) {
  20158. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  20159. }
  20160. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  20161. },
  20162. enumerable: true,
  20163. configurable: true
  20164. });
  20165. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  20166. get: function () {
  20167. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  20168. },
  20169. enumerable: true,
  20170. configurable: true
  20171. });
  20172. Object.defineProperty(Scene.prototype, "fogEnabled", {
  20173. get: function () {
  20174. return this._fogEnabled;
  20175. },
  20176. set: function (value) {
  20177. if (this._fogEnabled === value) {
  20178. return;
  20179. }
  20180. this._fogEnabled = value;
  20181. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20182. },
  20183. enumerable: true,
  20184. configurable: true
  20185. });
  20186. Object.defineProperty(Scene.prototype, "fogMode", {
  20187. get: function () {
  20188. return this._fogMode;
  20189. },
  20190. set: function (value) {
  20191. if (this._fogMode === value) {
  20192. return;
  20193. }
  20194. this._fogMode = value;
  20195. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20196. },
  20197. enumerable: true,
  20198. configurable: true
  20199. });
  20200. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  20201. get: function () {
  20202. return this._shadowsEnabled;
  20203. },
  20204. set: function (value) {
  20205. if (this._shadowsEnabled === value) {
  20206. return;
  20207. }
  20208. this._shadowsEnabled = value;
  20209. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20210. },
  20211. enumerable: true,
  20212. configurable: true
  20213. });
  20214. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  20215. get: function () {
  20216. return this._lightsEnabled;
  20217. },
  20218. set: function (value) {
  20219. if (this._lightsEnabled === value) {
  20220. return;
  20221. }
  20222. this._lightsEnabled = value;
  20223. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20224. },
  20225. enumerable: true,
  20226. configurable: true
  20227. });
  20228. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  20229. get: function () {
  20230. if (!this._defaultMaterial) {
  20231. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  20232. }
  20233. return this._defaultMaterial;
  20234. },
  20235. enumerable: true,
  20236. configurable: true
  20237. });
  20238. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  20239. get: function () {
  20240. return this._texturesEnabled;
  20241. },
  20242. set: function (value) {
  20243. if (this._texturesEnabled === value) {
  20244. return;
  20245. }
  20246. this._texturesEnabled = value;
  20247. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20248. },
  20249. enumerable: true,
  20250. configurable: true
  20251. });
  20252. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  20253. get: function () {
  20254. return this._skeletonsEnabled;
  20255. },
  20256. set: function (value) {
  20257. if (this._skeletonsEnabled === value) {
  20258. return;
  20259. }
  20260. this._skeletonsEnabled = value;
  20261. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  20262. },
  20263. enumerable: true,
  20264. configurable: true
  20265. });
  20266. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  20267. get: function () {
  20268. return this._frustumPlanes;
  20269. },
  20270. enumerable: true,
  20271. configurable: true
  20272. });
  20273. Object.defineProperty(Scene.prototype, "debugLayer", {
  20274. // Properties
  20275. get: function () {
  20276. if (!this._debugLayer) {
  20277. this._debugLayer = new BABYLON.DebugLayer(this);
  20278. }
  20279. return this._debugLayer;
  20280. },
  20281. enumerable: true,
  20282. configurable: true
  20283. });
  20284. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20285. get: function () {
  20286. return this._workerCollisions;
  20287. },
  20288. set: function (enabled) {
  20289. enabled = (enabled && !!Worker);
  20290. this._workerCollisions = enabled;
  20291. if (this.collisionCoordinator) {
  20292. this.collisionCoordinator.destroy();
  20293. }
  20294. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20295. this.collisionCoordinator.init(this);
  20296. },
  20297. enumerable: true,
  20298. configurable: true
  20299. });
  20300. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  20301. get: function () {
  20302. return this._selectionOctree;
  20303. },
  20304. enumerable: true,
  20305. configurable: true
  20306. });
  20307. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20308. /**
  20309. * The mesh that is currently under the pointer.
  20310. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20311. */
  20312. get: function () {
  20313. return this._pointerOverMesh;
  20314. },
  20315. enumerable: true,
  20316. configurable: true
  20317. });
  20318. Object.defineProperty(Scene.prototype, "pointerX", {
  20319. /**
  20320. * Current on-screen X position of the pointer
  20321. * @return {number} X position of the pointer
  20322. */
  20323. get: function () {
  20324. return this._pointerX;
  20325. },
  20326. enumerable: true,
  20327. configurable: true
  20328. });
  20329. Object.defineProperty(Scene.prototype, "pointerY", {
  20330. /**
  20331. * Current on-screen Y position of the pointer
  20332. * @return {number} Y position of the pointer
  20333. */
  20334. get: function () {
  20335. return this._pointerY;
  20336. },
  20337. enumerable: true,
  20338. configurable: true
  20339. });
  20340. Scene.prototype.getCachedMaterial = function () {
  20341. return this._cachedMaterial;
  20342. };
  20343. Scene.prototype.getBoundingBoxRenderer = function () {
  20344. return this._boundingBoxRenderer;
  20345. };
  20346. Scene.prototype.getOutlineRenderer = function () {
  20347. return this._outlineRenderer;
  20348. };
  20349. Scene.prototype.getEngine = function () {
  20350. return this._engine;
  20351. };
  20352. Scene.prototype.getTotalVertices = function () {
  20353. return this._totalVertices.current;
  20354. };
  20355. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20356. get: function () {
  20357. return this._totalVertices;
  20358. },
  20359. enumerable: true,
  20360. configurable: true
  20361. });
  20362. Scene.prototype.getActiveIndices = function () {
  20363. return this._activeIndices.current;
  20364. };
  20365. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20366. get: function () {
  20367. return this._activeIndices;
  20368. },
  20369. enumerable: true,
  20370. configurable: true
  20371. });
  20372. Scene.prototype.getActiveParticles = function () {
  20373. return this._activeParticles.current;
  20374. };
  20375. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20376. get: function () {
  20377. return this._activeParticles;
  20378. },
  20379. enumerable: true,
  20380. configurable: true
  20381. });
  20382. Scene.prototype.getActiveBones = function () {
  20383. return this._activeBones.current;
  20384. };
  20385. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20386. get: function () {
  20387. return this._activeBones;
  20388. },
  20389. enumerable: true,
  20390. configurable: true
  20391. });
  20392. // Stats
  20393. Scene.prototype.getLastFrameDuration = function () {
  20394. return this._lastFrameDuration.current;
  20395. };
  20396. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20397. get: function () {
  20398. return this._lastFrameDuration;
  20399. },
  20400. enumerable: true,
  20401. configurable: true
  20402. });
  20403. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20404. return this._evaluateActiveMeshesDuration.current;
  20405. };
  20406. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20407. get: function () {
  20408. return this._evaluateActiveMeshesDuration;
  20409. },
  20410. enumerable: true,
  20411. configurable: true
  20412. });
  20413. Scene.prototype.getActiveMeshes = function () {
  20414. return this._activeMeshes;
  20415. };
  20416. Scene.prototype.getRenderTargetsDuration = function () {
  20417. return this._renderTargetsDuration.current;
  20418. };
  20419. Scene.prototype.getRenderDuration = function () {
  20420. return this._renderDuration.current;
  20421. };
  20422. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20423. get: function () {
  20424. return this._renderDuration;
  20425. },
  20426. enumerable: true,
  20427. configurable: true
  20428. });
  20429. Scene.prototype.getParticlesDuration = function () {
  20430. return this._particlesDuration.current;
  20431. };
  20432. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20433. get: function () {
  20434. return this._particlesDuration;
  20435. },
  20436. enumerable: true,
  20437. configurable: true
  20438. });
  20439. Scene.prototype.getSpritesDuration = function () {
  20440. return this._spritesDuration.current;
  20441. };
  20442. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20443. get: function () {
  20444. return this._spritesDuration;
  20445. },
  20446. enumerable: true,
  20447. configurable: true
  20448. });
  20449. Scene.prototype.getAnimationRatio = function () {
  20450. return this._animationRatio;
  20451. };
  20452. Scene.prototype.getRenderId = function () {
  20453. return this._renderId;
  20454. };
  20455. Scene.prototype.incrementRenderId = function () {
  20456. this._renderId++;
  20457. };
  20458. Scene.prototype._updatePointerPosition = function (evt) {
  20459. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20460. this._pointerX = evt.clientX - canvasRect.left;
  20461. this._pointerY = evt.clientY - canvasRect.top;
  20462. this._unTranslatedPointerX = this._pointerX;
  20463. this._unTranslatedPointerY = this._pointerY;
  20464. if (this.cameraToUseForPointers) {
  20465. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  20466. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  20467. }
  20468. };
  20469. // Pointers handling
  20470. /**
  20471. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20472. * @param attachUp defines if you want to attach events to pointerup
  20473. * @param attachDown defines if you want to attach events to pointerdown
  20474. * @param attachMove defines if you want to attach events to pointermove
  20475. */
  20476. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20477. var _this = this;
  20478. if (attachUp === void 0) { attachUp = true; }
  20479. if (attachDown === void 0) { attachDown = true; }
  20480. if (attachMove === void 0) { attachMove = true; }
  20481. this._initActionManager = function (act, clickInfo) {
  20482. if (!_this._meshPickProceed) {
  20483. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20484. _this._currentPickResult = pickResult;
  20485. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20486. _this._meshPickProceed = true;
  20487. }
  20488. return act;
  20489. };
  20490. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20491. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20492. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20493. btn !== _this._previousButtonPressed) {
  20494. _this._doubleClickOccured = false;
  20495. clickInfo.singleClick = true;
  20496. clickInfo.ignore = false;
  20497. cb(clickInfo, _this._currentPickResult);
  20498. }
  20499. };
  20500. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20501. var clickInfo = new ClickInfo();
  20502. _this._currentPickResult = null;
  20503. var act;
  20504. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  20505. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  20506. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20507. if (!checkPicking && BABYLON.ActionManager.HasPickTriggers) {
  20508. act = _this._initActionManager(act, clickInfo);
  20509. if (act)
  20510. checkPicking = act.hasPickTriggers;
  20511. }
  20512. if (checkPicking) {
  20513. var btn = evt.button;
  20514. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20515. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20516. if (!clickInfo.hasSwiped) {
  20517. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20518. if (!checkSingleClickImmediately) {
  20519. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  20520. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20521. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20522. act = _this._initActionManager(act, clickInfo);
  20523. if (act)
  20524. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20525. }
  20526. }
  20527. if (checkSingleClickImmediately) {
  20528. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20529. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20530. btn !== _this._previousButtonPressed) {
  20531. clickInfo.singleClick = true;
  20532. cb(clickInfo, _this._currentPickResult);
  20533. }
  20534. }
  20535. else {
  20536. // wait that no double click has been raised during the double click delay
  20537. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20538. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20539. }
  20540. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  20541. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20542. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20543. act = _this._initActionManager(act, clickInfo);
  20544. if (act)
  20545. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20546. }
  20547. if (checkDoubleClick) {
  20548. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20549. if (btn === _this._previousButtonPressed &&
  20550. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20551. !_this._doubleClickOccured) {
  20552. // pointer has not moved for 2 clicks, it's a double click
  20553. if (!clickInfo.hasSwiped &&
  20554. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20555. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20556. _this._previousStartingPointerTime = 0;
  20557. _this._doubleClickOccured = true;
  20558. clickInfo.doubleClick = true;
  20559. clickInfo.ignore = false;
  20560. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  20561. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  20562. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20563. cb(clickInfo, _this._currentPickResult);
  20564. }
  20565. else {
  20566. _this._doubleClickOccured = false;
  20567. _this._previousStartingPointerTime = _this._startingPointerTime;
  20568. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20569. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20570. _this._previousButtonPressed = btn;
  20571. _this._previousHasSwiped = clickInfo.hasSwiped;
  20572. if (Scene.ExclusiveDoubleClickMode) {
  20573. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  20574. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  20575. }
  20576. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20577. cb(clickInfo, _this._previousPickResult);
  20578. }
  20579. else {
  20580. cb(clickInfo, _this._currentPickResult);
  20581. }
  20582. }
  20583. }
  20584. else {
  20585. _this._doubleClickOccured = false;
  20586. _this._previousStartingPointerTime = _this._startingPointerTime;
  20587. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20588. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20589. _this._previousButtonPressed = btn;
  20590. _this._previousHasSwiped = clickInfo.hasSwiped;
  20591. }
  20592. }
  20593. }
  20594. }
  20595. clickInfo.ignore = true;
  20596. cb(clickInfo, _this._currentPickResult);
  20597. };
  20598. var spritePredicate = function (sprite) {
  20599. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20600. };
  20601. this._onPointerMove = function (evt) {
  20602. _this._updatePointerPosition(evt);
  20603. // PreObservable support
  20604. if (_this.onPrePointerObservable.hasObservers()) {
  20605. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  20606. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20607. _this.onPrePointerObservable.notifyObservers(pi, type);
  20608. if (pi.skipOnPointerObservable) {
  20609. return;
  20610. }
  20611. }
  20612. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20613. return;
  20614. }
  20615. var canvas = _this._engine.getRenderingCanvas();
  20616. if (!_this.pointerMovePredicate) {
  20617. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20618. }
  20619. // Meshes
  20620. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20621. if (pickResult.hit && pickResult.pickedMesh) {
  20622. _this.setPointerOverSprite(null);
  20623. _this.setPointerOverMesh(pickResult.pickedMesh);
  20624. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20625. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  20626. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  20627. }
  20628. else {
  20629. canvas.style.cursor = _this.hoverCursor;
  20630. }
  20631. }
  20632. else {
  20633. canvas.style.cursor = "";
  20634. }
  20635. }
  20636. else {
  20637. _this.setPointerOverMesh(null);
  20638. // Sprites
  20639. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  20640. if (pickResult.hit && pickResult.pickedSprite) {
  20641. _this.setPointerOverSprite(pickResult.pickedSprite);
  20642. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  20643. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  20644. }
  20645. else {
  20646. canvas.style.cursor = _this.hoverCursor;
  20647. }
  20648. }
  20649. else {
  20650. _this.setPointerOverSprite(null);
  20651. // Restore pointer
  20652. canvas.style.cursor = "";
  20653. }
  20654. }
  20655. if (_this.onPointerMove) {
  20656. _this.onPointerMove(evt, pickResult);
  20657. }
  20658. if (_this.onPointerObservable.hasObservers()) {
  20659. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  20660. var pi = new PointerInfo(type, evt, pickResult);
  20661. _this.onPointerObservable.notifyObservers(pi, type);
  20662. }
  20663. };
  20664. this._onPointerDown = function (evt) {
  20665. _this._isButtonPressed = true;
  20666. _this._pickedDownMesh = null;
  20667. _this._meshPickProceed = false;
  20668. _this._updatePointerPosition(evt);
  20669. // PreObservable support
  20670. if (_this.onPrePointerObservable.hasObservers()) {
  20671. var type = PointerEventTypes.POINTERDOWN;
  20672. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20673. _this.onPrePointerObservable.notifyObservers(pi, type);
  20674. if (pi.skipOnPointerObservable) {
  20675. return;
  20676. }
  20677. }
  20678. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20679. return;
  20680. }
  20681. _this._startingPointerPosition.x = _this._pointerX;
  20682. _this._startingPointerPosition.y = _this._pointerY;
  20683. _this._startingPointerTime = new Date().getTime();
  20684. if (!_this.pointerDownPredicate) {
  20685. _this.pointerDownPredicate = function (mesh) {
  20686. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  20687. };
  20688. }
  20689. // Meshes
  20690. _this._pickedDownMesh = null;
  20691. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20692. if (pickResult.hit && pickResult.pickedMesh) {
  20693. _this._pickedDownMesh = pickResult.pickedMesh;
  20694. var actionManager = pickResult.pickedMesh.actionManager;
  20695. if (actionManager) {
  20696. if (actionManager.hasPickTriggers) {
  20697. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20698. switch (evt.button) {
  20699. case 0:
  20700. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20701. break;
  20702. case 1:
  20703. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20704. break;
  20705. case 2:
  20706. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20707. break;
  20708. }
  20709. }
  20710. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20711. window.setTimeout((function () {
  20712. var _this = this;
  20713. 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);
  20714. if (pickResult.hit && pickResult.pickedMesh) {
  20715. if (this._isButtonPressed &&
  20716. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  20717. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  20718. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  20719. this._startingPointerTime = 0;
  20720. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20721. }
  20722. }
  20723. }).bind(_this), Scene.LongPressDelay);
  20724. }
  20725. }
  20726. }
  20727. if (_this.onPointerDown) {
  20728. _this.onPointerDown(evt, pickResult);
  20729. }
  20730. if (_this.onPointerObservable.hasObservers()) {
  20731. var type = PointerEventTypes.POINTERDOWN;
  20732. var pi = new PointerInfo(type, evt, pickResult);
  20733. _this.onPointerObservable.notifyObservers(pi, type);
  20734. }
  20735. // Sprites
  20736. _this._pickedDownSprite = null;
  20737. if (_this.spriteManagers.length > 0) {
  20738. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  20739. if (pickResult.hit && pickResult.pickedSprite) {
  20740. if (pickResult.pickedSprite.actionManager) {
  20741. _this._pickedDownSprite = pickResult.pickedSprite;
  20742. switch (evt.button) {
  20743. case 0:
  20744. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20745. break;
  20746. case 1:
  20747. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20748. break;
  20749. case 2:
  20750. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20751. break;
  20752. }
  20753. if (pickResult.pickedSprite.actionManager) {
  20754. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20755. }
  20756. }
  20757. }
  20758. }
  20759. };
  20760. this._onPointerUp = function (evt) {
  20761. _this._isButtonPressed = false;
  20762. _this._pickedUpMesh = null;
  20763. _this._meshPickProceed = false;
  20764. _this._updatePointerPosition(evt);
  20765. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  20766. // PreObservable support
  20767. if (this.onPrePointerObservable.hasObservers()) {
  20768. if (!clickInfo.ignore) {
  20769. if (!clickInfo.hasSwiped) {
  20770. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  20771. var type = PointerEventTypes.POINTERTAP;
  20772. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20773. this.onPrePointerObservable.notifyObservers(pi, type);
  20774. if (pi.skipOnPointerObservable) {
  20775. return;
  20776. }
  20777. }
  20778. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  20779. var type = PointerEventTypes.POINTERDOUBLETAP;
  20780. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20781. this.onPrePointerObservable.notifyObservers(pi, type);
  20782. if (pi.skipOnPointerObservable) {
  20783. return;
  20784. }
  20785. }
  20786. }
  20787. }
  20788. else {
  20789. var type = PointerEventTypes.POINTERUP;
  20790. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20791. this.onPrePointerObservable.notifyObservers(pi, type);
  20792. if (pi.skipOnPointerObservable) {
  20793. return;
  20794. }
  20795. }
  20796. }
  20797. if (!this.cameraToUseForPointers && !this.activeCamera) {
  20798. return;
  20799. }
  20800. if (!this.pointerUpPredicate) {
  20801. this.pointerUpPredicate = function (mesh) {
  20802. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  20803. };
  20804. }
  20805. // Meshes
  20806. if (!this._meshPickProceed && (BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  20807. this._initActionManager(null, clickInfo);
  20808. }
  20809. if (!pickResult) {
  20810. pickResult = this._currentPickResult;
  20811. }
  20812. if (pickResult && pickResult.pickedMesh) {
  20813. this._pickedUpMesh = pickResult.pickedMesh;
  20814. if (this._pickedDownMesh === this._pickedUpMesh) {
  20815. if (this.onPointerPick) {
  20816. this.onPointerPick(evt, pickResult);
  20817. }
  20818. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20819. var type = PointerEventTypes.POINTERPICK;
  20820. var pi = new PointerInfo(type, evt, pickResult);
  20821. this.onPointerObservable.notifyObservers(pi, type);
  20822. }
  20823. }
  20824. if (pickResult.pickedMesh.actionManager) {
  20825. if (clickInfo.ignore) {
  20826. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20827. }
  20828. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20829. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20830. }
  20831. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20832. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20833. }
  20834. }
  20835. }
  20836. if (this._pickedDownMesh &&
  20837. this._pickedDownMesh.actionManager &&
  20838. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20839. this._pickedDownMesh !== this._pickedUpMesh) {
  20840. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20841. }
  20842. if (this.onPointerUp) {
  20843. this.onPointerUp(evt, pickResult);
  20844. }
  20845. if (this.onPointerObservable.hasObservers()) {
  20846. if (!clickInfo.ignore) {
  20847. if (!clickInfo.hasSwiped) {
  20848. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  20849. var type = PointerEventTypes.POINTERTAP;
  20850. var pi = new PointerInfo(type, evt, pickResult);
  20851. this.onPointerObservable.notifyObservers(pi, type);
  20852. }
  20853. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  20854. var type = PointerEventTypes.POINTERDOUBLETAP;
  20855. var pi = new PointerInfo(type, evt, pickResult);
  20856. this.onPointerObservable.notifyObservers(pi, type);
  20857. }
  20858. }
  20859. }
  20860. else {
  20861. var type = PointerEventTypes.POINTERUP;
  20862. var pi = new PointerInfo(type, evt, pickResult);
  20863. this.onPointerObservable.notifyObservers(pi, type);
  20864. }
  20865. }
  20866. // Sprites
  20867. if (this.spriteManagers.length > 0) {
  20868. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  20869. if (pickResult.hit && pickResult.pickedSprite) {
  20870. if (pickResult.pickedSprite.actionManager) {
  20871. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  20872. if (pickResult.pickedSprite.actionManager) {
  20873. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  20874. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  20875. }
  20876. }
  20877. }
  20878. }
  20879. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  20880. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  20881. }
  20882. }
  20883. this._previousPickResult = this._currentPickResult;
  20884. }).bind(_this));
  20885. };
  20886. this._onKeyDown = function (evt) {
  20887. if (_this.actionManager) {
  20888. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20889. }
  20890. };
  20891. this._onKeyUp = function (evt) {
  20892. if (_this.actionManager) {
  20893. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20894. }
  20895. };
  20896. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20897. var canvas = this._engine.getRenderingCanvas();
  20898. if (attachMove) {
  20899. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20900. // Wheel
  20901. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20902. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20903. }
  20904. if (attachDown) {
  20905. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20906. }
  20907. if (attachUp) {
  20908. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20909. }
  20910. canvas.tabIndex = 1;
  20911. canvas.addEventListener("keydown", this._onKeyDown, false);
  20912. canvas.addEventListener("keyup", this._onKeyUp, false);
  20913. };
  20914. Scene.prototype.detachControl = function () {
  20915. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20916. var canvas = this._engine.getRenderingCanvas();
  20917. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20918. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20919. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20920. // Wheel
  20921. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20922. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20923. canvas.removeEventListener("keydown", this._onKeyDown);
  20924. canvas.removeEventListener("keyup", this._onKeyUp);
  20925. };
  20926. // Ready
  20927. Scene.prototype.isReady = function () {
  20928. if (this._pendingData.length > 0) {
  20929. return false;
  20930. }
  20931. var index;
  20932. for (index = 0; index < this._geometries.length; index++) {
  20933. var geometry = this._geometries[index];
  20934. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20935. return false;
  20936. }
  20937. }
  20938. for (index = 0; index < this.meshes.length; index++) {
  20939. var mesh = this.meshes[index];
  20940. if (!mesh.isEnabled()) {
  20941. continue;
  20942. }
  20943. if (!mesh.isReady()) {
  20944. return false;
  20945. }
  20946. var mat = mesh.material;
  20947. if (mat) {
  20948. if (!mat.isReady(mesh)) {
  20949. return false;
  20950. }
  20951. }
  20952. }
  20953. return true;
  20954. };
  20955. Scene.prototype.resetCachedMaterial = function () {
  20956. this._cachedMaterial = null;
  20957. };
  20958. Scene.prototype.registerBeforeRender = function (func) {
  20959. this.onBeforeRenderObservable.add(func);
  20960. };
  20961. Scene.prototype.unregisterBeforeRender = function (func) {
  20962. this.onBeforeRenderObservable.removeCallback(func);
  20963. };
  20964. Scene.prototype.registerAfterRender = function (func) {
  20965. this.onAfterRenderObservable.add(func);
  20966. };
  20967. Scene.prototype.unregisterAfterRender = function (func) {
  20968. this.onAfterRenderObservable.removeCallback(func);
  20969. };
  20970. Scene.prototype._addPendingData = function (data) {
  20971. this._pendingData.push(data);
  20972. };
  20973. Scene.prototype._removePendingData = function (data) {
  20974. var index = this._pendingData.indexOf(data);
  20975. if (index !== -1) {
  20976. this._pendingData.splice(index, 1);
  20977. }
  20978. };
  20979. Scene.prototype.getWaitingItemsCount = function () {
  20980. return this._pendingData.length;
  20981. };
  20982. /**
  20983. * Registers a function to be executed when the scene is ready.
  20984. * @param {Function} func - the function to be executed.
  20985. */
  20986. Scene.prototype.executeWhenReady = function (func) {
  20987. var _this = this;
  20988. this.onReadyObservable.add(func);
  20989. if (this._executeWhenReadyTimeoutId !== -1) {
  20990. return;
  20991. }
  20992. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20993. _this._checkIsReady();
  20994. }, 150);
  20995. };
  20996. Scene.prototype._checkIsReady = function () {
  20997. var _this = this;
  20998. if (this.isReady()) {
  20999. this.onReadyObservable.notifyObservers(this);
  21000. this.onReadyObservable.clear();
  21001. this._executeWhenReadyTimeoutId = -1;
  21002. return;
  21003. }
  21004. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21005. _this._checkIsReady();
  21006. }, 150);
  21007. };
  21008. // Animations
  21009. /**
  21010. * Will start the animation sequence of a given target
  21011. * @param target - the target
  21012. * @param {number} from - from which frame should animation start
  21013. * @param {number} to - till which frame should animation run.
  21014. * @param {boolean} [loop] - should the animation loop
  21015. * @param {number} [speedRatio] - the speed in which to run the animation
  21016. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  21017. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  21018. * @return {BABYLON.Animatable} the animatable object created for this animation
  21019. * @see BABYLON.Animatable
  21020. * @see http://doc.babylonjs.com/page.php?p=22081
  21021. */
  21022. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  21023. if (speedRatio === void 0) { speedRatio = 1.0; }
  21024. this.stopAnimation(target);
  21025. if (!animatable) {
  21026. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  21027. }
  21028. // Local animations
  21029. if (target.animations) {
  21030. animatable.appendAnimations(target, target.animations);
  21031. }
  21032. // Children animations
  21033. if (target.getAnimatables) {
  21034. var animatables = target.getAnimatables();
  21035. for (var index = 0; index < animatables.length; index++) {
  21036. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  21037. }
  21038. }
  21039. animatable.reset();
  21040. return animatable;
  21041. };
  21042. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21043. if (speedRatio === undefined) {
  21044. speedRatio = 1.0;
  21045. }
  21046. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21047. return animatable;
  21048. };
  21049. Scene.prototype.getAnimatableByTarget = function (target) {
  21050. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21051. if (this._activeAnimatables[index].target === target) {
  21052. return this._activeAnimatables[index];
  21053. }
  21054. }
  21055. return null;
  21056. };
  21057. Object.defineProperty(Scene.prototype, "Animatables", {
  21058. get: function () {
  21059. return this._activeAnimatables;
  21060. },
  21061. enumerable: true,
  21062. configurable: true
  21063. });
  21064. /**
  21065. * Will stop the animation of the given target
  21066. * @param target - the target
  21067. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21068. * @see beginAnimation
  21069. */
  21070. Scene.prototype.stopAnimation = function (target, animationName) {
  21071. var animatable = this.getAnimatableByTarget(target);
  21072. if (animatable) {
  21073. animatable.stop(animationName);
  21074. }
  21075. };
  21076. Scene.prototype._animate = function () {
  21077. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21078. return;
  21079. }
  21080. // Getting time
  21081. var now = BABYLON.Tools.Now;
  21082. if (!this._animationTimeLast) {
  21083. if (this._pendingData.length > 0) {
  21084. return;
  21085. }
  21086. this._animationTimeLast = now;
  21087. }
  21088. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  21089. this._animationTime += deltaTime;
  21090. this._animationTimeLast = now;
  21091. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21092. this._activeAnimatables[index]._animate(this._animationTime);
  21093. }
  21094. };
  21095. // Matrix
  21096. Scene.prototype.getViewMatrix = function () {
  21097. return this._viewMatrix;
  21098. };
  21099. Scene.prototype.getProjectionMatrix = function () {
  21100. return this._projectionMatrix;
  21101. };
  21102. Scene.prototype.getTransformMatrix = function () {
  21103. return this._transformMatrix;
  21104. };
  21105. Scene.prototype.setTransformMatrix = function (view, projection) {
  21106. this._viewMatrix = view;
  21107. this._projectionMatrix = projection;
  21108. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21109. // Update frustum
  21110. if (!this._frustumPlanes) {
  21111. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21112. }
  21113. else {
  21114. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21115. }
  21116. };
  21117. // Methods
  21118. Scene.prototype.addMesh = function (newMesh) {
  21119. newMesh.uniqueId = this._uniqueIdCounter++;
  21120. var position = this.meshes.push(newMesh);
  21121. //notify the collision coordinator
  21122. this.collisionCoordinator.onMeshAdded(newMesh);
  21123. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21124. };
  21125. Scene.prototype.removeMesh = function (toRemove) {
  21126. var index = this.meshes.indexOf(toRemove);
  21127. if (index !== -1) {
  21128. // Remove from the scene if mesh found
  21129. this.meshes.splice(index, 1);
  21130. }
  21131. //notify the collision coordinator
  21132. this.collisionCoordinator.onMeshRemoved(toRemove);
  21133. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21134. return index;
  21135. };
  21136. Scene.prototype.removeSkeleton = function (toRemove) {
  21137. var index = this.skeletons.indexOf(toRemove);
  21138. if (index !== -1) {
  21139. // Remove from the scene if mesh found
  21140. this.skeletons.splice(index, 1);
  21141. }
  21142. return index;
  21143. };
  21144. Scene.prototype.removeLight = function (toRemove) {
  21145. var index = this.lights.indexOf(toRemove);
  21146. if (index !== -1) {
  21147. // Remove from the scene if mesh found
  21148. this.lights.splice(index, 1);
  21149. }
  21150. this.onLightRemovedObservable.notifyObservers(toRemove);
  21151. return index;
  21152. };
  21153. Scene.prototype.removeCamera = function (toRemove) {
  21154. var index = this.cameras.indexOf(toRemove);
  21155. if (index !== -1) {
  21156. // Remove from the scene if mesh found
  21157. this.cameras.splice(index, 1);
  21158. }
  21159. // Remove from activeCameras
  21160. var index2 = this.activeCameras.indexOf(toRemove);
  21161. if (index2 !== -1) {
  21162. // Remove from the scene if mesh found
  21163. this.activeCameras.splice(index2, 1);
  21164. }
  21165. // Reset the activeCamera
  21166. if (this.activeCamera === toRemove) {
  21167. if (this.cameras.length > 0) {
  21168. this.activeCamera = this.cameras[0];
  21169. }
  21170. else {
  21171. this.activeCamera = null;
  21172. }
  21173. }
  21174. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21175. return index;
  21176. };
  21177. Scene.prototype.addLight = function (newLight) {
  21178. newLight.uniqueId = this._uniqueIdCounter++;
  21179. var position = this.lights.push(newLight);
  21180. this.onNewLightAddedObservable.notifyObservers(newLight);
  21181. };
  21182. Scene.prototype.addCamera = function (newCamera) {
  21183. newCamera.uniqueId = this._uniqueIdCounter++;
  21184. var position = this.cameras.push(newCamera);
  21185. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21186. };
  21187. /**
  21188. * Switch active camera
  21189. * @param {Camera} newCamera - new active camera
  21190. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21191. */
  21192. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21193. if (attachControl === void 0) { attachControl = true; }
  21194. var canvas = this._engine.getRenderingCanvas();
  21195. this.activeCamera.detachControl(canvas);
  21196. this.activeCamera = newCamera;
  21197. if (attachControl) {
  21198. newCamera.attachControl(canvas);
  21199. }
  21200. };
  21201. /**
  21202. * sets the active camera of the scene using its ID
  21203. * @param {string} id - the camera's ID
  21204. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21205. * @see activeCamera
  21206. */
  21207. Scene.prototype.setActiveCameraByID = function (id) {
  21208. var camera = this.getCameraByID(id);
  21209. if (camera) {
  21210. this.activeCamera = camera;
  21211. return camera;
  21212. }
  21213. return null;
  21214. };
  21215. /**
  21216. * sets the active camera of the scene using its name
  21217. * @param {string} name - the camera's name
  21218. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21219. * @see activeCamera
  21220. */
  21221. Scene.prototype.setActiveCameraByName = function (name) {
  21222. var camera = this.getCameraByName(name);
  21223. if (camera) {
  21224. this.activeCamera = camera;
  21225. return camera;
  21226. }
  21227. return null;
  21228. };
  21229. /**
  21230. * get a material using its id
  21231. * @param {string} the material's ID
  21232. * @return {BABYLON.Material|null} the material or null if none found.
  21233. */
  21234. Scene.prototype.getMaterialByID = function (id) {
  21235. for (var index = 0; index < this.materials.length; index++) {
  21236. if (this.materials[index].id === id) {
  21237. return this.materials[index];
  21238. }
  21239. }
  21240. return null;
  21241. };
  21242. /**
  21243. * get a material using its name
  21244. * @param {string} the material's name
  21245. * @return {BABYLON.Material|null} the material or null if none found.
  21246. */
  21247. Scene.prototype.getMaterialByName = function (name) {
  21248. for (var index = 0; index < this.materials.length; index++) {
  21249. if (this.materials[index].name === name) {
  21250. return this.materials[index];
  21251. }
  21252. }
  21253. return null;
  21254. };
  21255. Scene.prototype.getLensFlareSystemByName = function (name) {
  21256. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21257. if (this.lensFlareSystems[index].name === name) {
  21258. return this.lensFlareSystems[index];
  21259. }
  21260. }
  21261. return null;
  21262. };
  21263. Scene.prototype.getLensFlareSystemByID = function (id) {
  21264. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21265. if (this.lensFlareSystems[index].id === id) {
  21266. return this.lensFlareSystems[index];
  21267. }
  21268. }
  21269. return null;
  21270. };
  21271. Scene.prototype.getCameraByID = function (id) {
  21272. for (var index = 0; index < this.cameras.length; index++) {
  21273. if (this.cameras[index].id === id) {
  21274. return this.cameras[index];
  21275. }
  21276. }
  21277. return null;
  21278. };
  21279. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21280. for (var index = 0; index < this.cameras.length; index++) {
  21281. if (this.cameras[index].uniqueId === uniqueId) {
  21282. return this.cameras[index];
  21283. }
  21284. }
  21285. return null;
  21286. };
  21287. /**
  21288. * get a camera using its name
  21289. * @param {string} the camera's name
  21290. * @return {BABYLON.Camera|null} the camera or null if none found.
  21291. */
  21292. Scene.prototype.getCameraByName = function (name) {
  21293. for (var index = 0; index < this.cameras.length; index++) {
  21294. if (this.cameras[index].name === name) {
  21295. return this.cameras[index];
  21296. }
  21297. }
  21298. return null;
  21299. };
  21300. /**
  21301. * get a bone using its id
  21302. * @param {string} the bone's id
  21303. * @return {BABYLON.Bone|null} the bone or null if not found
  21304. */
  21305. Scene.prototype.getBoneByID = function (id) {
  21306. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21307. var skeleton = this.skeletons[skeletonIndex];
  21308. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21309. if (skeleton.bones[boneIndex].id === id) {
  21310. return skeleton.bones[boneIndex];
  21311. }
  21312. }
  21313. }
  21314. return null;
  21315. };
  21316. /**
  21317. * get a bone using its id
  21318. * @param {string} the bone's name
  21319. * @return {BABYLON.Bone|null} the bone or null if not found
  21320. */
  21321. Scene.prototype.getBoneByName = function (name) {
  21322. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21323. var skeleton = this.skeletons[skeletonIndex];
  21324. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21325. if (skeleton.bones[boneIndex].name === name) {
  21326. return skeleton.bones[boneIndex];
  21327. }
  21328. }
  21329. }
  21330. return null;
  21331. };
  21332. /**
  21333. * get a light node using its name
  21334. * @param {string} the light's name
  21335. * @return {BABYLON.Light|null} the light or null if none found.
  21336. */
  21337. Scene.prototype.getLightByName = function (name) {
  21338. for (var index = 0; index < this.lights.length; index++) {
  21339. if (this.lights[index].name === name) {
  21340. return this.lights[index];
  21341. }
  21342. }
  21343. return null;
  21344. };
  21345. /**
  21346. * get a light node using its ID
  21347. * @param {string} the light's id
  21348. * @return {BABYLON.Light|null} the light or null if none found.
  21349. */
  21350. Scene.prototype.getLightByID = function (id) {
  21351. for (var index = 0; index < this.lights.length; index++) {
  21352. if (this.lights[index].id === id) {
  21353. return this.lights[index];
  21354. }
  21355. }
  21356. return null;
  21357. };
  21358. /**
  21359. * get a light node using its scene-generated unique ID
  21360. * @param {number} the light's unique id
  21361. * @return {BABYLON.Light|null} the light or null if none found.
  21362. */
  21363. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21364. for (var index = 0; index < this.lights.length; index++) {
  21365. if (this.lights[index].uniqueId === uniqueId) {
  21366. return this.lights[index];
  21367. }
  21368. }
  21369. return null;
  21370. };
  21371. /**
  21372. * get a particle system by id
  21373. * @param id {number} the particle system id
  21374. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  21375. */
  21376. Scene.prototype.getParticleSystemByID = function (id) {
  21377. for (var index = 0; index < this.particleSystems.length; index++) {
  21378. if (this.particleSystems[index].id === id) {
  21379. return this.particleSystems[index];
  21380. }
  21381. }
  21382. return null;
  21383. };
  21384. /**
  21385. * get a geometry using its ID
  21386. * @param {string} the geometry's id
  21387. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21388. */
  21389. Scene.prototype.getGeometryByID = function (id) {
  21390. for (var index = 0; index < this._geometries.length; index++) {
  21391. if (this._geometries[index].id === id) {
  21392. return this._geometries[index];
  21393. }
  21394. }
  21395. return null;
  21396. };
  21397. /**
  21398. * add a new geometry to this scene.
  21399. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21400. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21401. * @return {boolean} was the geometry added or not
  21402. */
  21403. Scene.prototype.pushGeometry = function (geometry, force) {
  21404. if (!force && this.getGeometryByID(geometry.id)) {
  21405. return false;
  21406. }
  21407. this._geometries.push(geometry);
  21408. //notify the collision coordinator
  21409. this.collisionCoordinator.onGeometryAdded(geometry);
  21410. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21411. return true;
  21412. };
  21413. /**
  21414. * Removes an existing geometry
  21415. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21416. * @return {boolean} was the geometry removed or not
  21417. */
  21418. Scene.prototype.removeGeometry = function (geometry) {
  21419. var index = this._geometries.indexOf(geometry);
  21420. if (index > -1) {
  21421. this._geometries.splice(index, 1);
  21422. //notify the collision coordinator
  21423. this.collisionCoordinator.onGeometryDeleted(geometry);
  21424. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21425. return true;
  21426. }
  21427. return false;
  21428. };
  21429. Scene.prototype.getGeometries = function () {
  21430. return this._geometries;
  21431. };
  21432. /**
  21433. * Get the first added mesh found of a given ID
  21434. * @param {string} id - the id to search for
  21435. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21436. */
  21437. Scene.prototype.getMeshByID = function (id) {
  21438. for (var index = 0; index < this.meshes.length; index++) {
  21439. if (this.meshes[index].id === id) {
  21440. return this.meshes[index];
  21441. }
  21442. }
  21443. return null;
  21444. };
  21445. Scene.prototype.getMeshesByID = function (id) {
  21446. return this.meshes.filter(function (m) {
  21447. return m.id === id;
  21448. });
  21449. };
  21450. /**
  21451. * Get a mesh with its auto-generated unique id
  21452. * @param {number} uniqueId - the unique id to search for
  21453. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21454. */
  21455. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21456. for (var index = 0; index < this.meshes.length; index++) {
  21457. if (this.meshes[index].uniqueId === uniqueId) {
  21458. return this.meshes[index];
  21459. }
  21460. }
  21461. return null;
  21462. };
  21463. /**
  21464. * Get a the last added mesh found of a given ID
  21465. * @param {string} id - the id to search for
  21466. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21467. */
  21468. Scene.prototype.getLastMeshByID = function (id) {
  21469. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21470. if (this.meshes[index].id === id) {
  21471. return this.meshes[index];
  21472. }
  21473. }
  21474. return null;
  21475. };
  21476. /**
  21477. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21478. * @param {string} id - the id to search for
  21479. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21480. */
  21481. Scene.prototype.getLastEntryByID = function (id) {
  21482. var index;
  21483. for (index = this.meshes.length - 1; index >= 0; index--) {
  21484. if (this.meshes[index].id === id) {
  21485. return this.meshes[index];
  21486. }
  21487. }
  21488. for (index = this.cameras.length - 1; index >= 0; index--) {
  21489. if (this.cameras[index].id === id) {
  21490. return this.cameras[index];
  21491. }
  21492. }
  21493. for (index = this.lights.length - 1; index >= 0; index--) {
  21494. if (this.lights[index].id === id) {
  21495. return this.lights[index];
  21496. }
  21497. }
  21498. return null;
  21499. };
  21500. Scene.prototype.getNodeByID = function (id) {
  21501. var mesh = this.getMeshByID(id);
  21502. if (mesh) {
  21503. return mesh;
  21504. }
  21505. var light = this.getLightByID(id);
  21506. if (light) {
  21507. return light;
  21508. }
  21509. var camera = this.getCameraByID(id);
  21510. if (camera) {
  21511. return camera;
  21512. }
  21513. var bone = this.getBoneByID(id);
  21514. return bone;
  21515. };
  21516. Scene.prototype.getNodeByName = function (name) {
  21517. var mesh = this.getMeshByName(name);
  21518. if (mesh) {
  21519. return mesh;
  21520. }
  21521. var light = this.getLightByName(name);
  21522. if (light) {
  21523. return light;
  21524. }
  21525. var camera = this.getCameraByName(name);
  21526. if (camera) {
  21527. return camera;
  21528. }
  21529. var bone = this.getBoneByName(name);
  21530. return bone;
  21531. };
  21532. Scene.prototype.getMeshByName = function (name) {
  21533. for (var index = 0; index < this.meshes.length; index++) {
  21534. if (this.meshes[index].name === name) {
  21535. return this.meshes[index];
  21536. }
  21537. }
  21538. return null;
  21539. };
  21540. Scene.prototype.getSoundByName = function (name) {
  21541. var index;
  21542. if (BABYLON.AudioEngine) {
  21543. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21544. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21545. return this.mainSoundTrack.soundCollection[index];
  21546. }
  21547. }
  21548. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21549. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21550. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21551. return this.soundTracks[sdIndex].soundCollection[index];
  21552. }
  21553. }
  21554. }
  21555. }
  21556. return null;
  21557. };
  21558. Scene.prototype.getLastSkeletonByID = function (id) {
  21559. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21560. if (this.skeletons[index].id === id) {
  21561. return this.skeletons[index];
  21562. }
  21563. }
  21564. return null;
  21565. };
  21566. Scene.prototype.getSkeletonById = function (id) {
  21567. for (var index = 0; index < this.skeletons.length; index++) {
  21568. if (this.skeletons[index].id === id) {
  21569. return this.skeletons[index];
  21570. }
  21571. }
  21572. return null;
  21573. };
  21574. Scene.prototype.getSkeletonByName = function (name) {
  21575. for (var index = 0; index < this.skeletons.length; index++) {
  21576. if (this.skeletons[index].name === name) {
  21577. return this.skeletons[index];
  21578. }
  21579. }
  21580. return null;
  21581. };
  21582. Scene.prototype.isActiveMesh = function (mesh) {
  21583. return (this._activeMeshes.indexOf(mesh) !== -1);
  21584. };
  21585. /**
  21586. * Return a the first highlight layer of the scene with a given name.
  21587. * @param name The name of the highlight layer to look for.
  21588. * @return The highlight layer if found otherwise null.
  21589. */
  21590. Scene.prototype.getHighlightLayerByName = function (name) {
  21591. for (var index = 0; index < this.highlightLayers.length; index++) {
  21592. if (this.highlightLayers[index].name === name) {
  21593. return this.highlightLayers[index];
  21594. }
  21595. }
  21596. return null;
  21597. };
  21598. Object.defineProperty(Scene.prototype, "uid", {
  21599. /**
  21600. * Return a unique id as a string which can serve as an identifier for the scene
  21601. */
  21602. get: function () {
  21603. if (!this._uid) {
  21604. this._uid = BABYLON.Tools.RandomId();
  21605. }
  21606. return this._uid;
  21607. },
  21608. enumerable: true,
  21609. configurable: true
  21610. });
  21611. /**
  21612. * Add an externaly attached data from its key.
  21613. * This method call will fail and return false, if such key already exists.
  21614. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21615. * @param key the unique key that identifies the data
  21616. * @param data the data object to associate to the key for this Engine instance
  21617. * @return true if no such key were already present and the data was added successfully, false otherwise
  21618. */
  21619. Scene.prototype.addExternalData = function (key, data) {
  21620. return this._externalData.add(key, data);
  21621. };
  21622. /**
  21623. * Get an externaly attached data from its key
  21624. * @param key the unique key that identifies the data
  21625. * @return the associated data, if present (can be null), or undefined if not present
  21626. */
  21627. Scene.prototype.getExternalData = function (key) {
  21628. return this._externalData.get(key);
  21629. };
  21630. /**
  21631. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21632. * @param key the unique key that identifies the data
  21633. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21634. * @return the associated data, can be null if the factory returned null.
  21635. */
  21636. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21637. return this._externalData.getOrAddWithFactory(key, factory);
  21638. };
  21639. /**
  21640. * Remove an externaly attached data from the Engine instance
  21641. * @param key the unique key that identifies the data
  21642. * @return true if the data was successfully removed, false if it doesn't exist
  21643. */
  21644. Scene.prototype.removeExternalData = function (key) {
  21645. return this._externalData.remove(key);
  21646. };
  21647. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21648. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21649. var material = subMesh.getMaterial();
  21650. if (mesh.showSubMeshesBoundingBox) {
  21651. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  21652. }
  21653. if (material) {
  21654. // Render targets
  21655. if (material.getRenderTargetTextures) {
  21656. if (this._processedMaterials.indexOf(material) === -1) {
  21657. this._processedMaterials.push(material);
  21658. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21659. }
  21660. }
  21661. // Dispatch
  21662. this._activeIndices.addCount(subMesh.indexCount, false);
  21663. this._renderingManager.dispatch(subMesh);
  21664. }
  21665. }
  21666. };
  21667. Scene.prototype._isInIntermediateRendering = function () {
  21668. return this._intermediateRendering;
  21669. };
  21670. Scene.prototype._evaluateActiveMeshes = function () {
  21671. this.activeCamera._activeMeshes.reset();
  21672. this._activeMeshes.reset();
  21673. this._renderingManager.reset();
  21674. this._processedMaterials.reset();
  21675. this._activeParticleSystems.reset();
  21676. this._activeSkeletons.reset();
  21677. this._softwareSkinnedMeshes.reset();
  21678. this._boundingBoxRenderer.reset();
  21679. this._edgesRenderers.reset();
  21680. // Meshes
  21681. var meshes;
  21682. var len;
  21683. if (this._selectionOctree) {
  21684. var selection = this._selectionOctree.select(this._frustumPlanes);
  21685. meshes = selection.data;
  21686. len = selection.length;
  21687. }
  21688. else {
  21689. len = this.meshes.length;
  21690. meshes = this.meshes;
  21691. }
  21692. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  21693. var mesh = meshes[meshIndex];
  21694. if (mesh.isBlocked) {
  21695. continue;
  21696. }
  21697. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21698. if (!mesh.isReady() || !mesh.isEnabled()) {
  21699. continue;
  21700. }
  21701. mesh.computeWorldMatrix();
  21702. // Intersections
  21703. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21704. this._meshesForIntersections.pushNoDuplicate(mesh);
  21705. }
  21706. // Switch to current LOD
  21707. var meshLOD = mesh.getLOD(this.activeCamera);
  21708. if (!meshLOD) {
  21709. continue;
  21710. }
  21711. mesh._preActivate();
  21712. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21713. this._activeMeshes.push(mesh);
  21714. this.activeCamera._activeMeshes.push(mesh);
  21715. mesh._activate(this._renderId);
  21716. this._activeMesh(mesh, meshLOD);
  21717. }
  21718. }
  21719. // Particle systems
  21720. this._particlesDuration.beginMonitoring();
  21721. var beforeParticlesDate = BABYLON.Tools.Now;
  21722. if (this.particlesEnabled) {
  21723. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  21724. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21725. var particleSystem = this.particleSystems[particleIndex];
  21726. if (!particleSystem.isStarted()) {
  21727. continue;
  21728. }
  21729. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  21730. this._activeParticleSystems.push(particleSystem);
  21731. particleSystem.animate();
  21732. this._renderingManager.dispatchParticles(particleSystem);
  21733. }
  21734. }
  21735. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  21736. }
  21737. this._particlesDuration.endMonitoring(false);
  21738. };
  21739. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21740. if (mesh.skeleton && this.skeletonsEnabled) {
  21741. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21742. mesh.skeleton.prepare();
  21743. }
  21744. if (!mesh.computeBonesUsingShaders) {
  21745. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21746. }
  21747. }
  21748. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21749. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  21750. }
  21751. if (sourceMesh._edgesRenderer) {
  21752. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  21753. }
  21754. if (mesh && mesh.subMeshes) {
  21755. // Submeshes Octrees
  21756. var len;
  21757. var subMeshes;
  21758. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  21759. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21760. len = intersections.length;
  21761. subMeshes = intersections.data;
  21762. }
  21763. else {
  21764. subMeshes = mesh.subMeshes;
  21765. len = subMeshes.length;
  21766. }
  21767. for (var subIndex = 0; subIndex < len; subIndex++) {
  21768. var subMesh = subMeshes[subIndex];
  21769. this._evaluateSubMesh(subMesh, mesh);
  21770. }
  21771. }
  21772. };
  21773. Scene.prototype.updateTransformMatrix = function (force) {
  21774. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21775. };
  21776. Scene.prototype._renderForCamera = function (camera) {
  21777. var engine = this._engine;
  21778. var startTime = BABYLON.Tools.Now;
  21779. this.activeCamera = camera;
  21780. if (!this.activeCamera)
  21781. throw new Error("Active camera not set");
  21782. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21783. // Viewport
  21784. engine.setViewport(this.activeCamera.viewport);
  21785. // Camera
  21786. this.resetCachedMaterial();
  21787. this._renderId++;
  21788. this.updateTransformMatrix();
  21789. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21790. // Meshes
  21791. this._evaluateActiveMeshesDuration.beginMonitoring();
  21792. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  21793. this._evaluateActiveMeshes();
  21794. this._evaluateActiveMeshesDuration.endMonitoring(false);
  21795. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  21796. // Software skinning
  21797. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21798. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21799. mesh.applySkeleton(mesh.skeleton);
  21800. }
  21801. // Render targets
  21802. this._renderTargetsDuration.beginMonitoring();
  21803. var needsRestoreFrameBuffer = false;
  21804. var beforeRenderTargetDate = BABYLON.Tools.Now;
  21805. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21806. this._intermediateRendering = true;
  21807. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21808. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21809. var renderTarget = this._renderTargets.data[renderIndex];
  21810. if (renderTarget._shouldRender()) {
  21811. this._renderId++;
  21812. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21813. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21814. }
  21815. }
  21816. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21817. this._intermediateRendering = false;
  21818. this._renderId++;
  21819. needsRestoreFrameBuffer = true; // Restore back buffer
  21820. }
  21821. // Render HighlightLayer Texture
  21822. var stencilState = this._engine.getStencilBuffer();
  21823. var renderhighlights = false;
  21824. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21825. this._intermediateRendering = true;
  21826. for (var i = 0; i < this.highlightLayers.length; i++) {
  21827. var highlightLayer = this.highlightLayers[i];
  21828. if (highlightLayer.shouldRender() &&
  21829. (!highlightLayer.camera ||
  21830. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  21831. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  21832. renderhighlights = true;
  21833. var renderTarget = highlightLayer._mainTexture;
  21834. if (renderTarget._shouldRender()) {
  21835. this._renderId++;
  21836. renderTarget.render(false, false);
  21837. needsRestoreFrameBuffer = true;
  21838. }
  21839. }
  21840. }
  21841. this._intermediateRendering = false;
  21842. this._renderId++;
  21843. }
  21844. if (needsRestoreFrameBuffer) {
  21845. engine.restoreDefaultFramebuffer();
  21846. }
  21847. this._renderTargetsDuration.endMonitoring(false);
  21848. // Prepare Frame
  21849. this.postProcessManager._prepareFrame();
  21850. this._renderDuration.beginMonitoring();
  21851. // Backgrounds
  21852. var layerIndex;
  21853. var layer;
  21854. if (this.layers.length) {
  21855. engine.setDepthBuffer(false);
  21856. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21857. layer = this.layers[layerIndex];
  21858. if (layer.isBackground) {
  21859. layer.render();
  21860. }
  21861. }
  21862. engine.setDepthBuffer(true);
  21863. }
  21864. // Render
  21865. BABYLON.Tools.StartPerformanceCounter("Main render");
  21866. // Activate HighlightLayer stencil
  21867. if (renderhighlights) {
  21868. this._engine.setStencilBuffer(true);
  21869. }
  21870. this._renderingManager.render(null, null, true, true);
  21871. // Restore HighlightLayer stencil
  21872. if (renderhighlights) {
  21873. this._engine.setStencilBuffer(stencilState);
  21874. }
  21875. BABYLON.Tools.EndPerformanceCounter("Main render");
  21876. // Bounding boxes
  21877. this._boundingBoxRenderer.render();
  21878. // Edges
  21879. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21880. this._edgesRenderers.data[edgesRendererIndex].render();
  21881. }
  21882. // Lens flares
  21883. if (this.lensFlaresEnabled) {
  21884. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21885. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  21886. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  21887. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  21888. lensFlareSystem.render();
  21889. }
  21890. }
  21891. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21892. }
  21893. // Foregrounds
  21894. if (this.layers.length) {
  21895. engine.setDepthBuffer(false);
  21896. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21897. layer = this.layers[layerIndex];
  21898. if (!layer.isBackground) {
  21899. layer.render();
  21900. }
  21901. }
  21902. engine.setDepthBuffer(true);
  21903. }
  21904. // Highlight Layer
  21905. if (renderhighlights) {
  21906. engine.setDepthBuffer(false);
  21907. for (var i = 0; i < this.highlightLayers.length; i++) {
  21908. if (this.highlightLayers[i].shouldRender()) {
  21909. this.highlightLayers[i].render();
  21910. }
  21911. }
  21912. engine.setDepthBuffer(true);
  21913. }
  21914. this._renderDuration.endMonitoring(false);
  21915. // Finalize frame
  21916. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  21917. // Update camera
  21918. this.activeCamera._updateFromScene();
  21919. // Reset some special arrays
  21920. this._renderTargets.reset();
  21921. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  21922. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21923. };
  21924. Scene.prototype._processSubCameras = function (camera) {
  21925. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  21926. this._renderForCamera(camera);
  21927. return;
  21928. }
  21929. // rig cameras
  21930. for (var index = 0; index < camera._rigCameras.length; index++) {
  21931. this._renderForCamera(camera._rigCameras[index]);
  21932. }
  21933. this.activeCamera = camera;
  21934. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  21935. // Update camera
  21936. this.activeCamera._updateFromScene();
  21937. };
  21938. Scene.prototype._checkIntersections = function () {
  21939. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  21940. var sourceMesh = this._meshesForIntersections.data[index];
  21941. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  21942. var action = sourceMesh.actionManager.actions[actionIndex];
  21943. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21944. var parameters = action.getTriggerParameter();
  21945. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  21946. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  21947. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  21948. if (areIntersecting && currentIntersectionInProgress === -1) {
  21949. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  21950. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  21951. sourceMesh._intersectionsInProgress.push(otherMesh);
  21952. }
  21953. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21954. sourceMesh._intersectionsInProgress.push(otherMesh);
  21955. }
  21956. }
  21957. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  21958. //They intersected, and now they don't.
  21959. //is this trigger an exit trigger? execute an event.
  21960. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21961. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  21962. }
  21963. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  21964. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21965. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  21966. }
  21967. }
  21968. }
  21969. }
  21970. }
  21971. };
  21972. Scene.prototype.render = function () {
  21973. if (this.isDisposed) {
  21974. return;
  21975. }
  21976. this._lastFrameDuration.beginMonitoring();
  21977. this._particlesDuration.fetchNewFrame();
  21978. this._spritesDuration.fetchNewFrame();
  21979. this._activeParticles.fetchNewFrame();
  21980. this._renderDuration.fetchNewFrame();
  21981. this._renderTargetsDuration.fetchNewFrame();
  21982. this._evaluateActiveMeshesDuration.fetchNewFrame();
  21983. this._totalVertices.fetchNewFrame();
  21984. this._activeIndices.fetchNewFrame();
  21985. this._activeBones.fetchNewFrame();
  21986. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  21987. this._meshesForIntersections.reset();
  21988. this.resetCachedMaterial();
  21989. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  21990. // Actions
  21991. if (this.actionManager) {
  21992. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  21993. }
  21994. //Simplification Queue
  21995. if (this.simplificationQueue && !this.simplificationQueue.running) {
  21996. this.simplificationQueue.executeNext();
  21997. }
  21998. // Animations
  21999. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22000. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22001. this._animate();
  22002. // Physics
  22003. if (this._physicsEngine) {
  22004. BABYLON.Tools.StartPerformanceCounter("Physics");
  22005. this._physicsEngine._step(deltaTime / 1000.0);
  22006. BABYLON.Tools.EndPerformanceCounter("Physics");
  22007. }
  22008. // Before render
  22009. this.onBeforeRenderObservable.notifyObservers(this);
  22010. // Customs render targets
  22011. this._renderTargetsDuration.beginMonitoring();
  22012. var beforeRenderTargetDate = BABYLON.Tools.Now;
  22013. var engine = this.getEngine();
  22014. var currentActiveCamera = this.activeCamera;
  22015. if (this.renderTargetsEnabled) {
  22016. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22017. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22018. var renderTarget = this.customRenderTargets[customIndex];
  22019. if (renderTarget._shouldRender()) {
  22020. this._renderId++;
  22021. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22022. if (!this.activeCamera)
  22023. throw new Error("Active camera not set");
  22024. // Viewport
  22025. engine.setViewport(this.activeCamera.viewport);
  22026. // Camera
  22027. this.updateTransformMatrix();
  22028. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22029. }
  22030. }
  22031. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22032. this._renderId++;
  22033. }
  22034. if (this.customRenderTargets.length > 0) {
  22035. engine.restoreDefaultFramebuffer();
  22036. }
  22037. this._renderTargetsDuration.endMonitoring();
  22038. this.activeCamera = currentActiveCamera;
  22039. // Procedural textures
  22040. if (this.proceduralTexturesEnabled) {
  22041. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22042. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22043. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22044. if (proceduralTexture._shouldRender()) {
  22045. proceduralTexture.render();
  22046. }
  22047. }
  22048. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22049. }
  22050. // Clear
  22051. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  22052. // Shadows
  22053. if (this.shadowsEnabled) {
  22054. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22055. var light = this.lights[lightIndex];
  22056. var shadowGenerator = light.getShadowGenerator();
  22057. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  22058. this._renderTargets.push(shadowGenerator.getShadowMap());
  22059. }
  22060. }
  22061. }
  22062. // Depth renderer
  22063. if (this._depthRenderer) {
  22064. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22065. }
  22066. // RenderPipeline
  22067. this.postProcessRenderPipelineManager.update();
  22068. // Multi-cameras?
  22069. if (this.activeCameras.length > 0) {
  22070. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22071. if (cameraIndex > 0) {
  22072. this._engine.clear(null, false, true, true);
  22073. }
  22074. this._processSubCameras(this.activeCameras[cameraIndex]);
  22075. }
  22076. }
  22077. else {
  22078. if (!this.activeCamera) {
  22079. throw new Error("No camera defined");
  22080. }
  22081. this._processSubCameras(this.activeCamera);
  22082. }
  22083. // Intersection checks
  22084. this._checkIntersections();
  22085. // Update the audio listener attached to the camera
  22086. if (BABYLON.AudioEngine) {
  22087. this._updateAudioParameters();
  22088. }
  22089. // After render
  22090. if (this.afterRender) {
  22091. this.afterRender();
  22092. }
  22093. this.onAfterRenderObservable.notifyObservers(this);
  22094. // Cleaning
  22095. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22096. this._toBeDisposed.data[index].dispose();
  22097. this._toBeDisposed[index] = null;
  22098. }
  22099. this._toBeDisposed.reset();
  22100. if (this.dumpNextRenderTargets) {
  22101. this.dumpNextRenderTargets = false;
  22102. }
  22103. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  22104. this._lastFrameDuration.endMonitoring();
  22105. this._totalMeshesCounter.addCount(this.meshes.length, true);
  22106. this._totalLightsCounter.addCount(this.lights.length, true);
  22107. this._totalMaterialsCounter.addCount(this.materials.length, true);
  22108. this._totalTexturesCounter.addCount(this.textures.length, true);
  22109. this._activeBones.addCount(0, true);
  22110. this._activeIndices.addCount(0, true);
  22111. this._activeParticles.addCount(0, true);
  22112. };
  22113. Scene.prototype._updateAudioParameters = function () {
  22114. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22115. return;
  22116. }
  22117. var listeningCamera;
  22118. var audioEngine = BABYLON.Engine.audioEngine;
  22119. if (this.activeCameras.length > 0) {
  22120. listeningCamera = this.activeCameras[0];
  22121. }
  22122. else {
  22123. listeningCamera = this.activeCamera;
  22124. }
  22125. if (listeningCamera && audioEngine.canUseWebAudio) {
  22126. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22127. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22128. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22129. cameraDirection.normalize();
  22130. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22131. var i;
  22132. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22133. var sound = this.mainSoundTrack.soundCollection[i];
  22134. if (sound.useCustomAttenuation) {
  22135. sound.updateDistanceFromListener();
  22136. }
  22137. }
  22138. for (i = 0; i < this.soundTracks.length; i++) {
  22139. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22140. sound = this.soundTracks[i].soundCollection[j];
  22141. if (sound.useCustomAttenuation) {
  22142. sound.updateDistanceFromListener();
  22143. }
  22144. }
  22145. }
  22146. }
  22147. };
  22148. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22149. // Audio
  22150. get: function () {
  22151. return this._audioEnabled;
  22152. },
  22153. set: function (value) {
  22154. this._audioEnabled = value;
  22155. if (BABYLON.AudioEngine) {
  22156. if (this._audioEnabled) {
  22157. this._enableAudio();
  22158. }
  22159. else {
  22160. this._disableAudio();
  22161. }
  22162. }
  22163. },
  22164. enumerable: true,
  22165. configurable: true
  22166. });
  22167. Scene.prototype._disableAudio = function () {
  22168. var i;
  22169. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22170. this.mainSoundTrack.soundCollection[i].pause();
  22171. }
  22172. for (i = 0; i < this.soundTracks.length; i++) {
  22173. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22174. this.soundTracks[i].soundCollection[j].pause();
  22175. }
  22176. }
  22177. };
  22178. Scene.prototype._enableAudio = function () {
  22179. var i;
  22180. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22181. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22182. this.mainSoundTrack.soundCollection[i].play();
  22183. }
  22184. }
  22185. for (i = 0; i < this.soundTracks.length; i++) {
  22186. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22187. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22188. this.soundTracks[i].soundCollection[j].play();
  22189. }
  22190. }
  22191. }
  22192. };
  22193. Object.defineProperty(Scene.prototype, "headphone", {
  22194. get: function () {
  22195. return this._headphone;
  22196. },
  22197. set: function (value) {
  22198. this._headphone = value;
  22199. if (BABYLON.AudioEngine) {
  22200. if (this._headphone) {
  22201. this._switchAudioModeForHeadphones();
  22202. }
  22203. else {
  22204. this._switchAudioModeForNormalSpeakers();
  22205. }
  22206. }
  22207. },
  22208. enumerable: true,
  22209. configurable: true
  22210. });
  22211. Scene.prototype._switchAudioModeForHeadphones = function () {
  22212. this.mainSoundTrack.switchPanningModelToHRTF();
  22213. for (var i = 0; i < this.soundTracks.length; i++) {
  22214. this.soundTracks[i].switchPanningModelToHRTF();
  22215. }
  22216. };
  22217. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22218. this.mainSoundTrack.switchPanningModelToEqualPower();
  22219. for (var i = 0; i < this.soundTracks.length; i++) {
  22220. this.soundTracks[i].switchPanningModelToEqualPower();
  22221. }
  22222. };
  22223. Scene.prototype.enableDepthRenderer = function () {
  22224. if (this._depthRenderer) {
  22225. return this._depthRenderer;
  22226. }
  22227. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22228. return this._depthRenderer;
  22229. };
  22230. Scene.prototype.disableDepthRenderer = function () {
  22231. if (!this._depthRenderer) {
  22232. return;
  22233. }
  22234. this._depthRenderer.dispose();
  22235. this._depthRenderer = null;
  22236. };
  22237. Scene.prototype.freezeMaterials = function () {
  22238. for (var i = 0; i < this.materials.length; i++) {
  22239. this.materials[i].freeze();
  22240. }
  22241. };
  22242. Scene.prototype.unfreezeMaterials = function () {
  22243. for (var i = 0; i < this.materials.length; i++) {
  22244. this.materials[i].unfreeze();
  22245. }
  22246. };
  22247. Scene.prototype.dispose = function () {
  22248. this.beforeRender = null;
  22249. this.afterRender = null;
  22250. this.skeletons = [];
  22251. this._boundingBoxRenderer.dispose();
  22252. if (this._depthRenderer) {
  22253. this._depthRenderer.dispose();
  22254. }
  22255. // Smart arrays
  22256. if (this.activeCamera) {
  22257. this.activeCamera._activeMeshes.dispose();
  22258. this.activeCamera = null;
  22259. }
  22260. this._activeMeshes.dispose();
  22261. this._renderingManager.dispose();
  22262. this._processedMaterials.dispose();
  22263. this._activeParticleSystems.dispose();
  22264. this._activeSkeletons.dispose();
  22265. this._softwareSkinnedMeshes.dispose();
  22266. this._boundingBoxRenderer.dispose();
  22267. this._edgesRenderers.dispose();
  22268. this._meshesForIntersections.dispose();
  22269. this._toBeDisposed.dispose();
  22270. // Debug layer
  22271. if (this._debugLayer) {
  22272. this._debugLayer.hide();
  22273. }
  22274. // Events
  22275. this.onDisposeObservable.notifyObservers(this);
  22276. this.onDisposeObservable.clear();
  22277. this.onBeforeRenderObservable.clear();
  22278. this.onAfterRenderObservable.clear();
  22279. this.detachControl();
  22280. // Release sounds & sounds tracks
  22281. if (BABYLON.AudioEngine) {
  22282. this.disposeSounds();
  22283. }
  22284. // Detach cameras
  22285. var canvas = this._engine.getRenderingCanvas();
  22286. var index;
  22287. for (index = 0; index < this.cameras.length; index++) {
  22288. this.cameras[index].detachControl(canvas);
  22289. }
  22290. // Release lights
  22291. while (this.lights.length) {
  22292. this.lights[0].dispose();
  22293. }
  22294. // Release meshes
  22295. while (this.meshes.length) {
  22296. this.meshes[0].dispose(true);
  22297. }
  22298. // Release cameras
  22299. while (this.cameras.length) {
  22300. this.cameras[0].dispose();
  22301. }
  22302. // Release materials
  22303. while (this.materials.length) {
  22304. this.materials[0].dispose();
  22305. }
  22306. // Release particles
  22307. while (this.particleSystems.length) {
  22308. this.particleSystems[0].dispose();
  22309. }
  22310. // Release sprites
  22311. while (this.spriteManagers.length) {
  22312. this.spriteManagers[0].dispose();
  22313. }
  22314. // Release layers
  22315. while (this.layers.length) {
  22316. this.layers[0].dispose();
  22317. }
  22318. while (this.highlightLayers.length) {
  22319. this.highlightLayers[0].dispose();
  22320. }
  22321. // Release textures
  22322. while (this.textures.length) {
  22323. this.textures[0].dispose();
  22324. }
  22325. // Post-processes
  22326. this.postProcessManager.dispose();
  22327. // Physics
  22328. if (this._physicsEngine) {
  22329. this.disablePhysicsEngine();
  22330. }
  22331. // Remove from engine
  22332. index = this._engine.scenes.indexOf(this);
  22333. if (index > -1) {
  22334. this._engine.scenes.splice(index, 1);
  22335. }
  22336. this._engine.wipeCaches();
  22337. this._engine = null;
  22338. };
  22339. Object.defineProperty(Scene.prototype, "isDisposed", {
  22340. get: function () {
  22341. return !this._engine;
  22342. },
  22343. enumerable: true,
  22344. configurable: true
  22345. });
  22346. // Release sounds & sounds tracks
  22347. Scene.prototype.disposeSounds = function () {
  22348. this.mainSoundTrack.dispose();
  22349. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22350. this.soundTracks[scIndex].dispose();
  22351. }
  22352. };
  22353. // Octrees
  22354. Scene.prototype.getWorldExtends = function () {
  22355. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22356. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22357. for (var index = 0; index < this.meshes.length; index++) {
  22358. var mesh = this.meshes[index];
  22359. mesh.computeWorldMatrix(true);
  22360. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  22361. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  22362. BABYLON.Tools.CheckExtends(minBox, min, max);
  22363. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22364. }
  22365. return {
  22366. min: min,
  22367. max: max
  22368. };
  22369. };
  22370. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22371. if (maxCapacity === void 0) { maxCapacity = 64; }
  22372. if (maxDepth === void 0) { maxDepth = 2; }
  22373. if (!this._selectionOctree) {
  22374. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22375. }
  22376. var worldExtends = this.getWorldExtends();
  22377. // Update octree
  22378. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22379. return this._selectionOctree;
  22380. };
  22381. // Picking
  22382. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22383. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22384. var engine = this._engine;
  22385. if (!camera) {
  22386. if (!this.activeCamera)
  22387. throw new Error("Active camera not set");
  22388. camera = this.activeCamera;
  22389. }
  22390. var cameraViewport = camera.viewport;
  22391. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22392. // Moving coordinates to local viewport world
  22393. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22394. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22395. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22396. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  22397. };
  22398. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22399. var engine = this._engine;
  22400. if (!camera) {
  22401. if (!this.activeCamera)
  22402. throw new Error("Active camera not set");
  22403. camera = this.activeCamera;
  22404. }
  22405. var cameraViewport = camera.viewport;
  22406. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22407. var identity = BABYLON.Matrix.Identity();
  22408. // Moving coordinates to local viewport world
  22409. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22410. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22411. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22412. };
  22413. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22414. var pickingInfo = null;
  22415. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22416. var mesh = this.meshes[meshIndex];
  22417. if (predicate) {
  22418. if (!predicate(mesh)) {
  22419. continue;
  22420. }
  22421. }
  22422. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22423. continue;
  22424. }
  22425. var world = mesh.getWorldMatrix();
  22426. var ray = rayFunction(world);
  22427. var result = mesh.intersects(ray, fastCheck);
  22428. if (!result || !result.hit)
  22429. continue;
  22430. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22431. continue;
  22432. pickingInfo = result;
  22433. if (fastCheck) {
  22434. break;
  22435. }
  22436. }
  22437. return pickingInfo || new BABYLON.PickingInfo();
  22438. };
  22439. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22440. var pickingInfos = new Array();
  22441. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22442. var mesh = this.meshes[meshIndex];
  22443. if (predicate) {
  22444. if (!predicate(mesh)) {
  22445. continue;
  22446. }
  22447. }
  22448. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22449. continue;
  22450. }
  22451. var world = mesh.getWorldMatrix();
  22452. var ray = rayFunction(world);
  22453. var result = mesh.intersects(ray, false);
  22454. if (!result || !result.hit)
  22455. continue;
  22456. pickingInfos.push(result);
  22457. }
  22458. return pickingInfos;
  22459. };
  22460. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22461. var pickingInfo = null;
  22462. camera = camera || this.activeCamera;
  22463. if (this.spriteManagers.length > 0) {
  22464. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22465. var spriteManager = this.spriteManagers[spriteIndex];
  22466. if (!spriteManager.isPickable) {
  22467. continue;
  22468. }
  22469. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22470. if (!result || !result.hit)
  22471. continue;
  22472. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22473. continue;
  22474. pickingInfo = result;
  22475. if (fastCheck) {
  22476. break;
  22477. }
  22478. }
  22479. }
  22480. return pickingInfo || new BABYLON.PickingInfo();
  22481. };
  22482. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22483. /// <param name="x">X position on screen</param>
  22484. /// <param name="y">Y position on screen</param>
  22485. /// <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>
  22486. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  22487. /// <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>
  22488. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22489. var _this = this;
  22490. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  22491. };
  22492. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22493. /// <param name="x">X position on screen</param>
  22494. /// <param name="y">Y position on screen</param>
  22495. /// <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>
  22496. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  22497. /// <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>
  22498. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22499. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  22500. };
  22501. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22502. var _this = this;
  22503. return this._internalPick(function (world) {
  22504. if (!_this._pickWithRayInverseMatrix) {
  22505. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22506. }
  22507. world.invertToRef(_this._pickWithRayInverseMatrix);
  22508. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  22509. }, predicate, fastCheck);
  22510. };
  22511. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22512. /// <param name="x">X position on screen</param>
  22513. /// <param name="y">Y position on screen</param>
  22514. /// <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>
  22515. /// <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>
  22516. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22517. var _this = this;
  22518. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  22519. };
  22520. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22521. /// <param name="ray">Ray to use</param>
  22522. /// <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>
  22523. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22524. var _this = this;
  22525. return this._internalMultiPick(function (world) {
  22526. if (!_this._pickWithRayInverseMatrix) {
  22527. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22528. }
  22529. world.invertToRef(_this._pickWithRayInverseMatrix);
  22530. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  22531. }, predicate);
  22532. };
  22533. Scene.prototype.setPointerOverMesh = function (mesh) {
  22534. if (this._pointerOverMesh === mesh) {
  22535. return;
  22536. }
  22537. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22538. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22539. }
  22540. this._pointerOverMesh = mesh;
  22541. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22542. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22543. }
  22544. };
  22545. Scene.prototype.getPointerOverMesh = function () {
  22546. return this._pointerOverMesh;
  22547. };
  22548. Scene.prototype.setPointerOverSprite = function (sprite) {
  22549. if (this._pointerOverSprite === sprite) {
  22550. return;
  22551. }
  22552. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22553. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22554. }
  22555. this._pointerOverSprite = sprite;
  22556. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22557. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22558. }
  22559. };
  22560. Scene.prototype.getPointerOverSprite = function () {
  22561. return this._pointerOverSprite;
  22562. };
  22563. // Physics
  22564. Scene.prototype.getPhysicsEngine = function () {
  22565. return this._physicsEngine;
  22566. };
  22567. /**
  22568. * Enables physics to the current scene
  22569. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22570. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22571. * @return {boolean} was the physics engine initialized
  22572. */
  22573. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22574. if (this._physicsEngine) {
  22575. return true;
  22576. }
  22577. try {
  22578. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22579. return true;
  22580. }
  22581. catch (e) {
  22582. BABYLON.Tools.Error(e.message);
  22583. return false;
  22584. }
  22585. };
  22586. Scene.prototype.disablePhysicsEngine = function () {
  22587. if (!this._physicsEngine) {
  22588. return;
  22589. }
  22590. this._physicsEngine.dispose();
  22591. this._physicsEngine = undefined;
  22592. };
  22593. Scene.prototype.isPhysicsEnabled = function () {
  22594. return this._physicsEngine !== undefined;
  22595. };
  22596. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22597. var mesh = compound.parts[0].mesh;
  22598. mesh.physicsImpostor.dispose();
  22599. mesh.physicsImpostor = null;
  22600. };
  22601. // Misc.
  22602. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  22603. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  22604. // Light
  22605. if (this.lights.length === 0) {
  22606. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  22607. }
  22608. // Camera
  22609. if (!this.activeCamera) {
  22610. // Compute position
  22611. var worldExtends = this.getWorldExtends();
  22612. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  22613. var camera;
  22614. if (createArcRotateCamera) {
  22615. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  22616. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  22617. camera.setTarget(worldCenter);
  22618. }
  22619. else {
  22620. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  22621. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  22622. camera.setTarget(worldCenter);
  22623. }
  22624. this.activeCamera = camera;
  22625. }
  22626. };
  22627. // Tags
  22628. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  22629. if (tagsQuery === undefined) {
  22630. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  22631. return list;
  22632. }
  22633. var listByTags = [];
  22634. forEach = forEach || (function (item) { return; });
  22635. for (var i in list) {
  22636. var item = list[i];
  22637. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  22638. listByTags.push(item);
  22639. forEach(item);
  22640. }
  22641. }
  22642. return listByTags;
  22643. };
  22644. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  22645. return this._getByTags(this.meshes, tagsQuery, forEach);
  22646. };
  22647. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  22648. return this._getByTags(this.cameras, tagsQuery, forEach);
  22649. };
  22650. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  22651. return this._getByTags(this.lights, tagsQuery, forEach);
  22652. };
  22653. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  22654. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  22655. };
  22656. /**
  22657. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22658. * This allowed control for front to back rendering or reversly depending of the special needs.
  22659. *
  22660. * @param renderingGroupId The rendering group id corresponding to its index
  22661. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22662. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22663. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22664. */
  22665. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22666. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22667. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22668. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22669. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  22670. };
  22671. /**
  22672. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22673. *
  22674. * @param renderingGroupId The rendering group id corresponding to its index
  22675. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22676. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22677. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22678. */
  22679. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22680. if (depth === void 0) { depth = true; }
  22681. if (stencil === void 0) { stencil = true; }
  22682. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  22683. };
  22684. /**
  22685. * Will flag all materials as dirty to trigger new shader compilation
  22686. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  22687. */
  22688. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  22689. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  22690. var material = _a[_i];
  22691. if (predicate && !predicate(material)) {
  22692. continue;
  22693. }
  22694. material.markAsDirty(flag);
  22695. }
  22696. };
  22697. return Scene;
  22698. }());
  22699. // Statics
  22700. Scene._FOGMODE_NONE = 0;
  22701. Scene._FOGMODE_EXP = 1;
  22702. Scene._FOGMODE_EXP2 = 2;
  22703. Scene._FOGMODE_LINEAR = 3;
  22704. Scene.MinDeltaTime = 1.0;
  22705. Scene.MaxDeltaTime = 1000.0;
  22706. Scene.DragMovementThreshold = 10; // in pixels
  22707. Scene.LongPressDelay = 500; // in milliseconds
  22708. Scene.DoubleClickDelay = 300; // in milliseconds
  22709. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  22710. BABYLON.Scene = Scene;
  22711. })(BABYLON || (BABYLON = {}));
  22712. //# sourceMappingURL=babylon.scene.js.map
  22713. var BABYLON;
  22714. (function (BABYLON) {
  22715. var Buffer = (function () {
  22716. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  22717. if (engine instanceof BABYLON.Mesh) {
  22718. this._engine = engine.getScene().getEngine();
  22719. }
  22720. else {
  22721. this._engine = engine;
  22722. }
  22723. this._updatable = updatable;
  22724. this._data = data;
  22725. this._strideSize = stride;
  22726. if (!postponeInternalCreation) {
  22727. this.create();
  22728. }
  22729. this._instanced = instanced;
  22730. }
  22731. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  22732. // a lot of these parameters are ignored as they are overriden by the buffer
  22733. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  22734. };
  22735. // Properties
  22736. Buffer.prototype.isUpdatable = function () {
  22737. return this._updatable;
  22738. };
  22739. Buffer.prototype.getData = function () {
  22740. return this._data;
  22741. };
  22742. Buffer.prototype.getBuffer = function () {
  22743. return this._buffer;
  22744. };
  22745. Buffer.prototype.getStrideSize = function () {
  22746. return this._strideSize;
  22747. };
  22748. Buffer.prototype.getIsInstanced = function () {
  22749. return this._instanced;
  22750. };
  22751. // Methods
  22752. Buffer.prototype.create = function (data) {
  22753. if (!data && this._buffer) {
  22754. return; // nothing to do
  22755. }
  22756. data = data || this._data;
  22757. if (!this._buffer) {
  22758. if (this._updatable) {
  22759. this._buffer = this._engine.createDynamicVertexBuffer(data);
  22760. this._data = data;
  22761. }
  22762. else {
  22763. this._buffer = this._engine.createVertexBuffer(data);
  22764. }
  22765. }
  22766. else if (this._updatable) {
  22767. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  22768. this._data = data;
  22769. }
  22770. };
  22771. Buffer.prototype.update = function (data) {
  22772. this.create(data);
  22773. };
  22774. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  22775. if (!this._buffer) {
  22776. return;
  22777. }
  22778. if (this._updatable) {
  22779. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  22780. this._data = null;
  22781. }
  22782. };
  22783. Buffer.prototype.dispose = function () {
  22784. if (!this._buffer) {
  22785. return;
  22786. }
  22787. if (this._engine._releaseBuffer(this._buffer)) {
  22788. this._buffer = null;
  22789. }
  22790. };
  22791. return Buffer;
  22792. }());
  22793. BABYLON.Buffer = Buffer;
  22794. })(BABYLON || (BABYLON = {}));
  22795. //# sourceMappingURL=babylon.buffer.js.map
  22796. var BABYLON;
  22797. (function (BABYLON) {
  22798. var VertexBuffer = (function () {
  22799. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  22800. if (!stride) {
  22801. // Deduce stride from kind
  22802. switch (kind) {
  22803. case VertexBuffer.PositionKind:
  22804. stride = 3;
  22805. break;
  22806. case VertexBuffer.NormalKind:
  22807. stride = 3;
  22808. break;
  22809. case VertexBuffer.UVKind:
  22810. case VertexBuffer.UV2Kind:
  22811. case VertexBuffer.UV3Kind:
  22812. case VertexBuffer.UV4Kind:
  22813. case VertexBuffer.UV5Kind:
  22814. case VertexBuffer.UV6Kind:
  22815. stride = 2;
  22816. break;
  22817. case VertexBuffer.TangentKind:
  22818. case VertexBuffer.ColorKind:
  22819. stride = 4;
  22820. break;
  22821. case VertexBuffer.MatricesIndicesKind:
  22822. case VertexBuffer.MatricesIndicesExtraKind:
  22823. stride = 4;
  22824. break;
  22825. case VertexBuffer.MatricesWeightsKind:
  22826. case VertexBuffer.MatricesWeightsExtraKind:
  22827. stride = 4;
  22828. break;
  22829. }
  22830. }
  22831. if (data instanceof BABYLON.Buffer) {
  22832. if (!stride) {
  22833. stride = data.getStrideSize();
  22834. }
  22835. this._buffer = data;
  22836. this._ownsBuffer = false;
  22837. }
  22838. else {
  22839. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  22840. this._ownsBuffer = true;
  22841. }
  22842. this._stride = stride;
  22843. this._offset = offset ? offset : 0;
  22844. this._size = size ? size : stride;
  22845. this._kind = kind;
  22846. }
  22847. /**
  22848. * Returns the kind of the VertexBuffer (string).
  22849. */
  22850. VertexBuffer.prototype.getKind = function () {
  22851. return this._kind;
  22852. };
  22853. // Properties
  22854. /**
  22855. * Boolean : is the VertexBuffer updatable ?
  22856. */
  22857. VertexBuffer.prototype.isUpdatable = function () {
  22858. return this._buffer.isUpdatable();
  22859. };
  22860. /**
  22861. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  22862. */
  22863. VertexBuffer.prototype.getData = function () {
  22864. return this._buffer.getData();
  22865. };
  22866. /**
  22867. * Returns the WebGLBuffer associated to the VertexBuffer.
  22868. */
  22869. VertexBuffer.prototype.getBuffer = function () {
  22870. return this._buffer.getBuffer();
  22871. };
  22872. /**
  22873. * Returns the stride of the VertexBuffer (integer).
  22874. */
  22875. VertexBuffer.prototype.getStrideSize = function () {
  22876. return this._stride;
  22877. };
  22878. /**
  22879. * Returns the offset (integer).
  22880. */
  22881. VertexBuffer.prototype.getOffset = function () {
  22882. return this._offset;
  22883. };
  22884. /**
  22885. * Returns the VertexBuffer total size (integer).
  22886. */
  22887. VertexBuffer.prototype.getSize = function () {
  22888. return this._size;
  22889. };
  22890. /**
  22891. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  22892. */
  22893. VertexBuffer.prototype.getIsInstanced = function () {
  22894. return this._buffer.getIsInstanced();
  22895. };
  22896. // Methods
  22897. /**
  22898. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  22899. * Returns the created WebGLBuffer.
  22900. */
  22901. VertexBuffer.prototype.create = function (data) {
  22902. return this._buffer.create(data);
  22903. };
  22904. /**
  22905. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22906. * Returns the updated WebGLBuffer.
  22907. */
  22908. VertexBuffer.prototype.update = function (data) {
  22909. return this._buffer.update(data);
  22910. };
  22911. /**
  22912. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22913. * Returns the directly updated WebGLBuffer.
  22914. */
  22915. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  22916. return this._buffer.updateDirectly(data, offset);
  22917. };
  22918. /**
  22919. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  22920. */
  22921. VertexBuffer.prototype.dispose = function () {
  22922. if (this._ownsBuffer) {
  22923. this._buffer.dispose();
  22924. }
  22925. };
  22926. Object.defineProperty(VertexBuffer, "PositionKind", {
  22927. get: function () {
  22928. return VertexBuffer._PositionKind;
  22929. },
  22930. enumerable: true,
  22931. configurable: true
  22932. });
  22933. Object.defineProperty(VertexBuffer, "NormalKind", {
  22934. get: function () {
  22935. return VertexBuffer._NormalKind;
  22936. },
  22937. enumerable: true,
  22938. configurable: true
  22939. });
  22940. Object.defineProperty(VertexBuffer, "TangentKind", {
  22941. get: function () {
  22942. return VertexBuffer._TangentKind;
  22943. },
  22944. enumerable: true,
  22945. configurable: true
  22946. });
  22947. Object.defineProperty(VertexBuffer, "UVKind", {
  22948. get: function () {
  22949. return VertexBuffer._UVKind;
  22950. },
  22951. enumerable: true,
  22952. configurable: true
  22953. });
  22954. Object.defineProperty(VertexBuffer, "UV2Kind", {
  22955. get: function () {
  22956. return VertexBuffer._UV2Kind;
  22957. },
  22958. enumerable: true,
  22959. configurable: true
  22960. });
  22961. Object.defineProperty(VertexBuffer, "UV3Kind", {
  22962. get: function () {
  22963. return VertexBuffer._UV3Kind;
  22964. },
  22965. enumerable: true,
  22966. configurable: true
  22967. });
  22968. Object.defineProperty(VertexBuffer, "UV4Kind", {
  22969. get: function () {
  22970. return VertexBuffer._UV4Kind;
  22971. },
  22972. enumerable: true,
  22973. configurable: true
  22974. });
  22975. Object.defineProperty(VertexBuffer, "UV5Kind", {
  22976. get: function () {
  22977. return VertexBuffer._UV5Kind;
  22978. },
  22979. enumerable: true,
  22980. configurable: true
  22981. });
  22982. Object.defineProperty(VertexBuffer, "UV6Kind", {
  22983. get: function () {
  22984. return VertexBuffer._UV6Kind;
  22985. },
  22986. enumerable: true,
  22987. configurable: true
  22988. });
  22989. Object.defineProperty(VertexBuffer, "ColorKind", {
  22990. get: function () {
  22991. return VertexBuffer._ColorKind;
  22992. },
  22993. enumerable: true,
  22994. configurable: true
  22995. });
  22996. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  22997. get: function () {
  22998. return VertexBuffer._MatricesIndicesKind;
  22999. },
  23000. enumerable: true,
  23001. configurable: true
  23002. });
  23003. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23004. get: function () {
  23005. return VertexBuffer._MatricesWeightsKind;
  23006. },
  23007. enumerable: true,
  23008. configurable: true
  23009. });
  23010. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23011. get: function () {
  23012. return VertexBuffer._MatricesIndicesExtraKind;
  23013. },
  23014. enumerable: true,
  23015. configurable: true
  23016. });
  23017. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23018. get: function () {
  23019. return VertexBuffer._MatricesWeightsExtraKind;
  23020. },
  23021. enumerable: true,
  23022. configurable: true
  23023. });
  23024. return VertexBuffer;
  23025. }());
  23026. // Enums
  23027. VertexBuffer._PositionKind = "position";
  23028. VertexBuffer._NormalKind = "normal";
  23029. VertexBuffer._TangentKind = "tangent";
  23030. VertexBuffer._UVKind = "uv";
  23031. VertexBuffer._UV2Kind = "uv2";
  23032. VertexBuffer._UV3Kind = "uv3";
  23033. VertexBuffer._UV4Kind = "uv4";
  23034. VertexBuffer._UV5Kind = "uv5";
  23035. VertexBuffer._UV6Kind = "uv6";
  23036. VertexBuffer._ColorKind = "color";
  23037. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23038. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23039. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23040. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23041. BABYLON.VertexBuffer = VertexBuffer;
  23042. })(BABYLON || (BABYLON = {}));
  23043. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23044. var BABYLON;
  23045. (function (BABYLON) {
  23046. /**
  23047. * Creates an instance based on a source mesh.
  23048. */
  23049. var InstancedMesh = (function (_super) {
  23050. __extends(InstancedMesh, _super);
  23051. function InstancedMesh(name, source) {
  23052. var _this = _super.call(this, name, source.getScene()) || this;
  23053. source.instances.push(_this);
  23054. _this._sourceMesh = source;
  23055. _this.position.copyFrom(source.position);
  23056. _this.rotation.copyFrom(source.rotation);
  23057. _this.scaling.copyFrom(source.scaling);
  23058. if (source.rotationQuaternion) {
  23059. _this.rotationQuaternion = source.rotationQuaternion.clone();
  23060. }
  23061. _this.infiniteDistance = source.infiniteDistance;
  23062. _this.setPivotMatrix(source.getPivotMatrix());
  23063. _this.refreshBoundingInfo();
  23064. _this._syncSubMeshes();
  23065. return _this;
  23066. }
  23067. /**
  23068. * Returns the string "InstancedMesh".
  23069. */
  23070. InstancedMesh.prototype.getClassName = function () {
  23071. return "InstancedMesh";
  23072. };
  23073. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  23074. // Methods
  23075. get: function () {
  23076. return this._sourceMesh.receiveShadows;
  23077. },
  23078. enumerable: true,
  23079. configurable: true
  23080. });
  23081. Object.defineProperty(InstancedMesh.prototype, "material", {
  23082. get: function () {
  23083. return this._sourceMesh.material;
  23084. },
  23085. enumerable: true,
  23086. configurable: true
  23087. });
  23088. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  23089. get: function () {
  23090. return this._sourceMesh.visibility;
  23091. },
  23092. enumerable: true,
  23093. configurable: true
  23094. });
  23095. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  23096. get: function () {
  23097. return this._sourceMesh.skeleton;
  23098. },
  23099. enumerable: true,
  23100. configurable: true
  23101. });
  23102. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  23103. get: function () {
  23104. return this._sourceMesh.renderingGroupId;
  23105. },
  23106. enumerable: true,
  23107. configurable: true
  23108. });
  23109. /**
  23110. * Returns the total number of vertices (integer).
  23111. */
  23112. InstancedMesh.prototype.getTotalVertices = function () {
  23113. return this._sourceMesh.getTotalVertices();
  23114. };
  23115. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  23116. get: function () {
  23117. return this._sourceMesh;
  23118. },
  23119. enumerable: true,
  23120. configurable: true
  23121. });
  23122. /**
  23123. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  23124. */
  23125. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  23126. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  23127. };
  23128. /**
  23129. * Boolean : True if the mesh owns the requested kind of data.
  23130. */
  23131. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  23132. return this._sourceMesh.isVerticesDataPresent(kind);
  23133. };
  23134. /**
  23135. * Returns an array of indices (IndicesArray).
  23136. */
  23137. InstancedMesh.prototype.getIndices = function () {
  23138. return this._sourceMesh.getIndices();
  23139. };
  23140. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  23141. get: function () {
  23142. return this._sourceMesh._positions;
  23143. },
  23144. enumerable: true,
  23145. configurable: true
  23146. });
  23147. /**
  23148. * Sets a new updated BoundingInfo to the mesh.
  23149. * Returns the mesh.
  23150. */
  23151. InstancedMesh.prototype.refreshBoundingInfo = function () {
  23152. var meshBB = this._sourceMesh.getBoundingInfo();
  23153. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  23154. this._updateBoundingInfo();
  23155. return this;
  23156. };
  23157. InstancedMesh.prototype._preActivate = function () {
  23158. if (this._currentLOD) {
  23159. this._currentLOD._preActivate();
  23160. }
  23161. return this;
  23162. };
  23163. InstancedMesh.prototype._activate = function (renderId) {
  23164. if (this._currentLOD) {
  23165. this._currentLOD._registerInstanceForRenderId(this, renderId);
  23166. }
  23167. return this;
  23168. };
  23169. /**
  23170. * Returns the current associated LOD AbstractMesh.
  23171. */
  23172. InstancedMesh.prototype.getLOD = function (camera) {
  23173. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  23174. if (this._currentLOD === this.sourceMesh) {
  23175. return this;
  23176. }
  23177. return this._currentLOD;
  23178. };
  23179. InstancedMesh.prototype._syncSubMeshes = function () {
  23180. this.releaseSubMeshes();
  23181. if (this._sourceMesh.subMeshes) {
  23182. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  23183. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  23184. }
  23185. }
  23186. return this;
  23187. };
  23188. InstancedMesh.prototype._generatePointsArray = function () {
  23189. return this._sourceMesh._generatePointsArray();
  23190. };
  23191. /**
  23192. * Creates a new InstancedMesh from the current mesh.
  23193. * - name (string) : the cloned mesh name
  23194. * - newParent (optional Node) : the optional Node to parent the clone to.
  23195. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  23196. *
  23197. * Returns the clone.
  23198. */
  23199. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  23200. var result = this._sourceMesh.createInstance(name);
  23201. // Deep copy
  23202. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  23203. // Bounding info
  23204. this.refreshBoundingInfo();
  23205. // Parent
  23206. if (newParent) {
  23207. result.parent = newParent;
  23208. }
  23209. if (!doNotCloneChildren) {
  23210. // Children
  23211. for (var index = 0; index < this.getScene().meshes.length; index++) {
  23212. var mesh = this.getScene().meshes[index];
  23213. if (mesh.parent === this) {
  23214. mesh.clone(mesh.name, result);
  23215. }
  23216. }
  23217. }
  23218. result.computeWorldMatrix(true);
  23219. return result;
  23220. };
  23221. /**
  23222. * Disposes the InstancedMesh.
  23223. * Returns nothing.
  23224. */
  23225. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  23226. // Remove from mesh
  23227. var index = this._sourceMesh.instances.indexOf(this);
  23228. this._sourceMesh.instances.splice(index, 1);
  23229. _super.prototype.dispose.call(this, doNotRecurse);
  23230. };
  23231. return InstancedMesh;
  23232. }(BABYLON.AbstractMesh));
  23233. BABYLON.InstancedMesh = InstancedMesh;
  23234. })(BABYLON || (BABYLON = {}));
  23235. //# sourceMappingURL=babylon.instancedMesh.js.map
  23236. var BABYLON;
  23237. (function (BABYLON) {
  23238. var _InstancesBatch = (function () {
  23239. function _InstancesBatch() {
  23240. this.mustReturn = false;
  23241. this.visibleInstances = new Array();
  23242. this.renderSelf = new Array();
  23243. }
  23244. return _InstancesBatch;
  23245. }());
  23246. BABYLON._InstancesBatch = _InstancesBatch;
  23247. var Mesh = (function (_super) {
  23248. __extends(Mesh, _super);
  23249. /**
  23250. * @constructor
  23251. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  23252. * @param {Scene} scene The scene to add this mesh to.
  23253. * @param {Node} parent The parent of this mesh, if it has one
  23254. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  23255. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  23256. * When false, achieved by calling a clone(), also passing False.
  23257. * This will make creation of children, recursive.
  23258. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  23259. */
  23260. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  23261. if (parent === void 0) { parent = null; }
  23262. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23263. var _this = _super.call(this, name, scene) || this;
  23264. // Events
  23265. /**
  23266. * An event triggered before rendering the mesh
  23267. * @type {BABYLON.Observable}
  23268. */
  23269. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23270. /**
  23271. * An event triggered after rendering the mesh
  23272. * @type {BABYLON.Observable}
  23273. */
  23274. _this.onAfterRenderObservable = new BABYLON.Observable();
  23275. /**
  23276. * An event triggered before drawing the mesh
  23277. * @type {BABYLON.Observable}
  23278. */
  23279. _this.onBeforeDrawObservable = new BABYLON.Observable();
  23280. // Members
  23281. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23282. _this.instances = new Array();
  23283. _this._LODLevels = new Array();
  23284. _this._visibleInstances = {};
  23285. _this._renderIdForInstances = new Array();
  23286. _this._batchCache = new _InstancesBatch();
  23287. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  23288. _this._sideOrientation = Mesh._DEFAULTSIDE;
  23289. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  23290. // Will be used to save a source mesh reference, If any
  23291. _this._source = null;
  23292. if (source) {
  23293. // Source mesh
  23294. _this._source = source;
  23295. // Geometry
  23296. if (source._geometry) {
  23297. source._geometry.applyToMesh(_this);
  23298. }
  23299. // Deep copy
  23300. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  23301. // Parent
  23302. _this.parent = source.parent;
  23303. // Pivot
  23304. _this.setPivotMatrix(source.getPivotMatrix());
  23305. _this.id = name + "." + source.id;
  23306. // Material
  23307. _this.material = source.material;
  23308. var index;
  23309. if (!doNotCloneChildren) {
  23310. // Children
  23311. for (index = 0; index < scene.meshes.length; index++) {
  23312. var mesh = scene.meshes[index];
  23313. if (mesh.parent === source) {
  23314. // doNotCloneChildren is always going to be False
  23315. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  23316. }
  23317. }
  23318. }
  23319. // Physics clone
  23320. var physicsEngine = _this.getScene().getPhysicsEngine();
  23321. if (clonePhysicsImpostor && physicsEngine) {
  23322. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  23323. if (impostor) {
  23324. _this.physicsImpostor = impostor.clone(_this);
  23325. }
  23326. }
  23327. // Particles
  23328. for (index = 0; index < scene.particleSystems.length; index++) {
  23329. var system = scene.particleSystems[index];
  23330. if (system.emitter === source) {
  23331. system.clone(system.name, _this);
  23332. }
  23333. }
  23334. _this.computeWorldMatrix(true);
  23335. }
  23336. // Parent
  23337. if (parent !== null) {
  23338. _this.parent = parent;
  23339. }
  23340. return _this;
  23341. }
  23342. Object.defineProperty(Mesh, "FRONTSIDE", {
  23343. /**
  23344. * Mesh side orientation : usually the external or front surface
  23345. */
  23346. get: function () {
  23347. return Mesh._FRONTSIDE;
  23348. },
  23349. enumerable: true,
  23350. configurable: true
  23351. });
  23352. Object.defineProperty(Mesh, "BACKSIDE", {
  23353. /**
  23354. * Mesh side orientation : usually the internal or back surface
  23355. */
  23356. get: function () {
  23357. return Mesh._BACKSIDE;
  23358. },
  23359. enumerable: true,
  23360. configurable: true
  23361. });
  23362. Object.defineProperty(Mesh, "DOUBLESIDE", {
  23363. /**
  23364. * Mesh side orientation : both internal and external or front and back surfaces
  23365. */
  23366. get: function () {
  23367. return Mesh._DOUBLESIDE;
  23368. },
  23369. enumerable: true,
  23370. configurable: true
  23371. });
  23372. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  23373. /**
  23374. * Mesh side orientation : by default, `FRONTSIDE`
  23375. */
  23376. get: function () {
  23377. return Mesh._DEFAULTSIDE;
  23378. },
  23379. enumerable: true,
  23380. configurable: true
  23381. });
  23382. Object.defineProperty(Mesh, "NO_CAP", {
  23383. /**
  23384. * Mesh cap setting : no cap
  23385. */
  23386. get: function () {
  23387. return Mesh._NO_CAP;
  23388. },
  23389. enumerable: true,
  23390. configurable: true
  23391. });
  23392. Object.defineProperty(Mesh, "CAP_START", {
  23393. /**
  23394. * Mesh cap setting : one cap at the beginning of the mesh
  23395. */
  23396. get: function () {
  23397. return Mesh._CAP_START;
  23398. },
  23399. enumerable: true,
  23400. configurable: true
  23401. });
  23402. Object.defineProperty(Mesh, "CAP_END", {
  23403. /**
  23404. * Mesh cap setting : one cap at the end of the mesh
  23405. */
  23406. get: function () {
  23407. return Mesh._CAP_END;
  23408. },
  23409. enumerable: true,
  23410. configurable: true
  23411. });
  23412. Object.defineProperty(Mesh, "CAP_ALL", {
  23413. /**
  23414. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  23415. */
  23416. get: function () {
  23417. return Mesh._CAP_ALL;
  23418. },
  23419. enumerable: true,
  23420. configurable: true
  23421. });
  23422. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  23423. set: function (callback) {
  23424. if (this._onBeforeDrawObserver) {
  23425. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  23426. }
  23427. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  23428. },
  23429. enumerable: true,
  23430. configurable: true
  23431. });
  23432. Object.defineProperty(Mesh.prototype, "source", {
  23433. get: function () {
  23434. return this._source;
  23435. },
  23436. enumerable: true,
  23437. configurable: true
  23438. });
  23439. // Methods
  23440. /**
  23441. * Returns the string "Mesh".
  23442. */
  23443. Mesh.prototype.getClassName = function () {
  23444. return "Mesh";
  23445. };
  23446. /**
  23447. * Returns a string.
  23448. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23449. */
  23450. Mesh.prototype.toString = function (fullDetails) {
  23451. var ret = _super.prototype.toString.call(this, fullDetails);
  23452. ret += ", n vertices: " + this.getTotalVertices();
  23453. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23454. if (this.animations) {
  23455. for (var i = 0; i < this.animations.length; i++) {
  23456. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23457. }
  23458. }
  23459. if (fullDetails) {
  23460. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  23461. }
  23462. return ret;
  23463. };
  23464. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23465. /**
  23466. * True if the mesh has some Levels Of Details (LOD).
  23467. * Returns a boolean.
  23468. */
  23469. get: function () {
  23470. return this._LODLevels.length > 0;
  23471. },
  23472. enumerable: true,
  23473. configurable: true
  23474. });
  23475. Mesh.prototype._sortLODLevels = function () {
  23476. this._LODLevels.sort(function (a, b) {
  23477. if (a.distance < b.distance) {
  23478. return 1;
  23479. }
  23480. if (a.distance > b.distance) {
  23481. return -1;
  23482. }
  23483. return 0;
  23484. });
  23485. };
  23486. /**
  23487. * Add a mesh as LOD level triggered at the given distance.
  23488. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23489. * @param {number} distance The distance from the center of the object to show this level
  23490. * @param {Mesh} mesh The mesh to be added as LOD level
  23491. * @return {Mesh} This mesh (for chaining)
  23492. */
  23493. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23494. if (mesh && mesh._masterMesh) {
  23495. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23496. return this;
  23497. }
  23498. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23499. this._LODLevels.push(level);
  23500. if (mesh) {
  23501. mesh._masterMesh = this;
  23502. }
  23503. this._sortLODLevels();
  23504. return this;
  23505. };
  23506. /**
  23507. * Returns the LOD level mesh at the passed distance or null if not found.
  23508. * It is related to the method `addLODLevel(distance, mesh)`.
  23509. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23510. * Returns an object Mesh or `null`.
  23511. */
  23512. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23513. for (var index = 0; index < this._LODLevels.length; index++) {
  23514. var level = this._LODLevels[index];
  23515. if (level.distance === distance) {
  23516. return level.mesh;
  23517. }
  23518. }
  23519. return null;
  23520. };
  23521. /**
  23522. * Remove a mesh from the LOD array
  23523. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23524. * @param {Mesh} mesh The mesh to be removed.
  23525. * @return {Mesh} This mesh (for chaining)
  23526. */
  23527. Mesh.prototype.removeLODLevel = function (mesh) {
  23528. for (var index = 0; index < this._LODLevels.length; index++) {
  23529. if (this._LODLevels[index].mesh === mesh) {
  23530. this._LODLevels.splice(index, 1);
  23531. if (mesh) {
  23532. mesh._masterMesh = null;
  23533. }
  23534. }
  23535. }
  23536. this._sortLODLevels();
  23537. return this;
  23538. };
  23539. /**
  23540. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23541. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23542. */
  23543. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23544. if (!this._LODLevels || this._LODLevels.length === 0) {
  23545. return this;
  23546. }
  23547. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  23548. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23549. if (this.onLODLevelSelection) {
  23550. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23551. }
  23552. return this;
  23553. }
  23554. for (var index = 0; index < this._LODLevels.length; index++) {
  23555. var level = this._LODLevels[index];
  23556. if (level.distance < distanceToCamera) {
  23557. if (level.mesh) {
  23558. level.mesh._preActivate();
  23559. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23560. }
  23561. if (this.onLODLevelSelection) {
  23562. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23563. }
  23564. return level.mesh;
  23565. }
  23566. }
  23567. if (this.onLODLevelSelection) {
  23568. this.onLODLevelSelection(distanceToCamera, this, this);
  23569. }
  23570. return this;
  23571. };
  23572. Object.defineProperty(Mesh.prototype, "geometry", {
  23573. /**
  23574. * Returns the mesh internal Geometry object.
  23575. */
  23576. get: function () {
  23577. return this._geometry;
  23578. },
  23579. enumerable: true,
  23580. configurable: true
  23581. });
  23582. /**
  23583. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23584. */
  23585. Mesh.prototype.getTotalVertices = function () {
  23586. if (!this._geometry) {
  23587. return 0;
  23588. }
  23589. return this._geometry.getTotalVertices();
  23590. };
  23591. /**
  23592. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23593. * 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.
  23594. * Returns null if the mesh has no geometry or no vertex buffer.
  23595. * Possible `kind` values :
  23596. * - BABYLON.VertexBuffer.PositionKind
  23597. * - BABYLON.VertexBuffer.UVKind
  23598. * - BABYLON.VertexBuffer.UV2Kind
  23599. * - BABYLON.VertexBuffer.UV3Kind
  23600. * - BABYLON.VertexBuffer.UV4Kind
  23601. * - BABYLON.VertexBuffer.UV5Kind
  23602. * - BABYLON.VertexBuffer.UV6Kind
  23603. * - BABYLON.VertexBuffer.ColorKind
  23604. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23605. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23606. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23607. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23608. */
  23609. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  23610. if (!this._geometry) {
  23611. return null;
  23612. }
  23613. return this._geometry.getVerticesData(kind, copyWhenShared);
  23614. };
  23615. /**
  23616. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23617. * Returns `undefined` if the mesh has no geometry.
  23618. * Possible `kind` values :
  23619. * - BABYLON.VertexBuffer.PositionKind
  23620. * - BABYLON.VertexBuffer.UVKind
  23621. * - BABYLON.VertexBuffer.UV2Kind
  23622. * - BABYLON.VertexBuffer.UV3Kind
  23623. * - BABYLON.VertexBuffer.UV4Kind
  23624. * - BABYLON.VertexBuffer.UV5Kind
  23625. * - BABYLON.VertexBuffer.UV6Kind
  23626. * - BABYLON.VertexBuffer.ColorKind
  23627. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23628. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23629. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23630. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23631. */
  23632. Mesh.prototype.getVertexBuffer = function (kind) {
  23633. if (!this._geometry) {
  23634. return undefined;
  23635. }
  23636. return this._geometry.getVertexBuffer(kind);
  23637. };
  23638. /**
  23639. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23640. * Possible `kind` values :
  23641. * - BABYLON.VertexBuffer.PositionKind
  23642. * - BABYLON.VertexBuffer.UVKind
  23643. * - BABYLON.VertexBuffer.UV2Kind
  23644. * - BABYLON.VertexBuffer.UV3Kind
  23645. * - BABYLON.VertexBuffer.UV4Kind
  23646. * - BABYLON.VertexBuffer.UV5Kind
  23647. * - BABYLON.VertexBuffer.UV6Kind
  23648. * - BABYLON.VertexBuffer.ColorKind
  23649. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23650. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23651. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23652. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23653. */
  23654. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23655. if (!this._geometry) {
  23656. if (this._delayInfo) {
  23657. return this._delayInfo.indexOf(kind) !== -1;
  23658. }
  23659. return false;
  23660. }
  23661. return this._geometry.isVerticesDataPresent(kind);
  23662. };
  23663. /**
  23664. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23665. * Possible `kind` values :
  23666. * - BABYLON.VertexBuffer.PositionKind
  23667. * - BABYLON.VertexBuffer.UVKind
  23668. * - BABYLON.VertexBuffer.UV2Kind
  23669. * - BABYLON.VertexBuffer.UV3Kind
  23670. * - BABYLON.VertexBuffer.UV4Kind
  23671. * - BABYLON.VertexBuffer.UV5Kind
  23672. * - BABYLON.VertexBuffer.UV6Kind
  23673. * - BABYLON.VertexBuffer.ColorKind
  23674. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23675. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23676. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23677. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23678. */
  23679. Mesh.prototype.getVerticesDataKinds = function () {
  23680. if (!this._geometry) {
  23681. var result = [];
  23682. if (this._delayInfo) {
  23683. this._delayInfo.forEach(function (kind, index, array) {
  23684. result.push(kind);
  23685. });
  23686. }
  23687. return result;
  23688. }
  23689. return this._geometry.getVerticesDataKinds();
  23690. };
  23691. /**
  23692. * Returns a positive integer : the total number of indices in this mesh geometry.
  23693. * Returns zero if the mesh has no geometry.
  23694. */
  23695. Mesh.prototype.getTotalIndices = function () {
  23696. if (!this._geometry) {
  23697. return 0;
  23698. }
  23699. return this._geometry.getTotalIndices();
  23700. };
  23701. /**
  23702. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23703. * 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.
  23704. * Returns an empty array if the mesh has no geometry.
  23705. */
  23706. Mesh.prototype.getIndices = function (copyWhenShared) {
  23707. if (!this._geometry) {
  23708. return [];
  23709. }
  23710. return this._geometry.getIndices(copyWhenShared);
  23711. };
  23712. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23713. get: function () {
  23714. return this._masterMesh !== null && this._masterMesh !== undefined;
  23715. },
  23716. enumerable: true,
  23717. configurable: true
  23718. });
  23719. /**
  23720. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23721. */
  23722. Mesh.prototype.isReady = function () {
  23723. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23724. return false;
  23725. }
  23726. return _super.prototype.isReady.call(this);
  23727. };
  23728. /**
  23729. * Boolean : true if the mesh has been disposed.
  23730. */
  23731. Mesh.prototype.isDisposed = function () {
  23732. return this._isDisposed;
  23733. };
  23734. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  23735. get: function () {
  23736. return this._sideOrientation;
  23737. },
  23738. /**
  23739. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  23740. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  23741. */
  23742. set: function (sideO) {
  23743. this._sideOrientation = sideO;
  23744. },
  23745. enumerable: true,
  23746. configurable: true
  23747. });
  23748. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23749. /**
  23750. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23751. * This property is pertinent only for updatable parametric shapes.
  23752. */
  23753. get: function () {
  23754. return this._areNormalsFrozen;
  23755. },
  23756. enumerable: true,
  23757. configurable: true
  23758. });
  23759. /**
  23760. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23761. * It has no effect at all on other shapes.
  23762. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23763. * Returns the Mesh.
  23764. */
  23765. Mesh.prototype.freezeNormals = function () {
  23766. this._areNormalsFrozen = true;
  23767. return this;
  23768. };
  23769. /**
  23770. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23771. * It has no effect at all on other shapes.
  23772. * It reactivates the mesh normals computation if it was previously frozen.
  23773. * Returns the Mesh.
  23774. */
  23775. Mesh.prototype.unfreezeNormals = function () {
  23776. this._areNormalsFrozen = false;
  23777. return this;
  23778. };
  23779. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23780. /**
  23781. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23782. */
  23783. set: function (count) {
  23784. this._overridenInstanceCount = count;
  23785. },
  23786. enumerable: true,
  23787. configurable: true
  23788. });
  23789. // Methods
  23790. Mesh.prototype._preActivate = function () {
  23791. var sceneRenderId = this.getScene().getRenderId();
  23792. if (this._preActivateId === sceneRenderId) {
  23793. return this;
  23794. }
  23795. this._preActivateId = sceneRenderId;
  23796. this._visibleInstances = null;
  23797. return this;
  23798. };
  23799. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23800. if (this._visibleInstances) {
  23801. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23802. }
  23803. return this;
  23804. };
  23805. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23806. if (!this._visibleInstances) {
  23807. this._visibleInstances = {};
  23808. this._visibleInstances.defaultRenderId = renderId;
  23809. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23810. }
  23811. if (!this._visibleInstances[renderId]) {
  23812. this._visibleInstances[renderId] = new Array();
  23813. }
  23814. this._visibleInstances[renderId].push(instance);
  23815. return this;
  23816. };
  23817. /**
  23818. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23819. * This means the mesh underlying bounding box and sphere are recomputed.
  23820. * Returns the Mesh.
  23821. */
  23822. Mesh.prototype.refreshBoundingInfo = function () {
  23823. if (this._boundingInfo.isLocked) {
  23824. return;
  23825. }
  23826. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23827. if (data) {
  23828. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23829. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23830. }
  23831. if (this.subMeshes) {
  23832. for (var index = 0; index < this.subMeshes.length; index++) {
  23833. this.subMeshes[index].refreshBoundingInfo();
  23834. }
  23835. }
  23836. this._updateBoundingInfo();
  23837. return this;
  23838. };
  23839. Mesh.prototype._createGlobalSubMesh = function () {
  23840. var totalVertices = this.getTotalVertices();
  23841. if (!totalVertices || !this.getIndices()) {
  23842. return null;
  23843. }
  23844. this.releaseSubMeshes();
  23845. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23846. };
  23847. Mesh.prototype.subdivide = function (count) {
  23848. if (count < 1) {
  23849. return;
  23850. }
  23851. var totalIndices = this.getTotalIndices();
  23852. var subdivisionSize = (totalIndices / count) | 0;
  23853. var offset = 0;
  23854. // Ensure that subdivisionSize is a multiple of 3
  23855. while (subdivisionSize % 3 !== 0) {
  23856. subdivisionSize++;
  23857. }
  23858. this.releaseSubMeshes();
  23859. for (var index = 0; index < count; index++) {
  23860. if (offset >= totalIndices) {
  23861. break;
  23862. }
  23863. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23864. offset += subdivisionSize;
  23865. }
  23866. this.synchronizeInstances();
  23867. };
  23868. /**
  23869. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23870. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23871. * The `data` are either a numeric array either a Float32Array.
  23872. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23873. * 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).
  23874. * Note that a new underlying VertexBuffer object is created each call.
  23875. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23876. *
  23877. * Possible `kind` values :
  23878. * - BABYLON.VertexBuffer.PositionKind
  23879. * - BABYLON.VertexBuffer.UVKind
  23880. * - BABYLON.VertexBuffer.UV2Kind
  23881. * - BABYLON.VertexBuffer.UV3Kind
  23882. * - BABYLON.VertexBuffer.UV4Kind
  23883. * - BABYLON.VertexBuffer.UV5Kind
  23884. * - BABYLON.VertexBuffer.UV6Kind
  23885. * - BABYLON.VertexBuffer.ColorKind
  23886. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23887. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23888. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23889. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23890. *
  23891. * Returns the Mesh.
  23892. */
  23893. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23894. if (!this._geometry) {
  23895. var vertexData = new BABYLON.VertexData();
  23896. vertexData.set(data, kind);
  23897. var scene = this.getScene();
  23898. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23899. }
  23900. else {
  23901. this._geometry.setVerticesData(kind, data, updatable, stride);
  23902. }
  23903. return this;
  23904. };
  23905. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23906. if (updatable === void 0) { updatable = true; }
  23907. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  23908. return;
  23909. }
  23910. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23911. };
  23912. /**
  23913. * Sets the mesh VertexBuffer.
  23914. * Returns the Mesh.
  23915. */
  23916. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23917. if (!this._geometry) {
  23918. var scene = this.getScene();
  23919. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  23920. }
  23921. this._geometry.setVerticesBuffer(buffer);
  23922. return this;
  23923. };
  23924. /**
  23925. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23926. * If the mesh has no geometry, it is simply returned as it is.
  23927. * The `data` are either a numeric array either a Float32Array.
  23928. * No new underlying VertexBuffer object is created.
  23929. * 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.
  23930. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23931. *
  23932. * Possible `kind` values :
  23933. * - BABYLON.VertexBuffer.PositionKind
  23934. * - BABYLON.VertexBuffer.UVKind
  23935. * - BABYLON.VertexBuffer.UV2Kind
  23936. * - BABYLON.VertexBuffer.UV3Kind
  23937. * - BABYLON.VertexBuffer.UV4Kind
  23938. * - BABYLON.VertexBuffer.UV5Kind
  23939. * - BABYLON.VertexBuffer.UV6Kind
  23940. * - BABYLON.VertexBuffer.ColorKind
  23941. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23942. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23943. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23944. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23945. *
  23946. * Returns the Mesh.
  23947. */
  23948. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23949. if (!this._geometry) {
  23950. return;
  23951. }
  23952. if (!makeItUnique) {
  23953. this._geometry.updateVerticesData(kind, data, updateExtends);
  23954. }
  23955. else {
  23956. this.makeGeometryUnique();
  23957. this.updateVerticesData(kind, data, updateExtends, false);
  23958. }
  23959. return this;
  23960. };
  23961. /**
  23962. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23963. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23964. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23965. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23966. * Returns the Mesh.
  23967. */
  23968. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23969. if (computeNormals === void 0) { computeNormals = true; }
  23970. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23971. positionFunction(positions);
  23972. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23973. if (computeNormals) {
  23974. var indices = this.getIndices();
  23975. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23976. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23977. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23978. }
  23979. return this;
  23980. };
  23981. /**
  23982. * Creates a un-shared specific occurence of the geometry for the mesh.
  23983. * Returns the Mesh.
  23984. */
  23985. Mesh.prototype.makeGeometryUnique = function () {
  23986. if (!this._geometry) {
  23987. return;
  23988. }
  23989. var oldGeometry = this._geometry;
  23990. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23991. oldGeometry.releaseForMesh(this, true);
  23992. geometry.applyToMesh(this);
  23993. return this;
  23994. };
  23995. /**
  23996. * Sets the mesh indices.
  23997. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23998. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23999. * This method creates a new index buffer each call.
  24000. * Returns the Mesh.
  24001. */
  24002. Mesh.prototype.setIndices = function (indices, totalVertices) {
  24003. if (!this._geometry) {
  24004. var vertexData = new BABYLON.VertexData();
  24005. vertexData.indices = indices;
  24006. var scene = this.getScene();
  24007. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  24008. }
  24009. else {
  24010. this._geometry.setIndices(indices, totalVertices);
  24011. }
  24012. return this;
  24013. };
  24014. /**
  24015. * Invert the geometry to move from a right handed system to a left handed one.
  24016. * Returns the Mesh.
  24017. */
  24018. Mesh.prototype.toLeftHanded = function () {
  24019. if (!this._geometry) {
  24020. return;
  24021. }
  24022. this._geometry.toLeftHanded();
  24023. return this;
  24024. };
  24025. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  24026. var engine = this.getScene().getEngine();
  24027. // Wireframe
  24028. var indexToBind;
  24029. if (this._unIndexed) {
  24030. indexToBind = null;
  24031. }
  24032. else {
  24033. switch (fillMode) {
  24034. case BABYLON.Material.PointFillMode:
  24035. indexToBind = null;
  24036. break;
  24037. case BABYLON.Material.WireFrameFillMode:
  24038. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  24039. break;
  24040. default:
  24041. case BABYLON.Material.TriangleFillMode:
  24042. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  24043. break;
  24044. }
  24045. }
  24046. // VBOs
  24047. this._geometry._bind(effect, indexToBind);
  24048. return this;
  24049. };
  24050. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  24051. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24052. return this;
  24053. }
  24054. this.onBeforeDrawObservable.notifyObservers(this);
  24055. var engine = this.getScene().getEngine();
  24056. // Draw order
  24057. switch (fillMode) {
  24058. case BABYLON.Material.PointFillMode:
  24059. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  24060. break;
  24061. case BABYLON.Material.WireFrameFillMode:
  24062. if (this._unIndexed) {
  24063. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  24064. }
  24065. else {
  24066. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  24067. }
  24068. break;
  24069. default:
  24070. if (this._unIndexed) {
  24071. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  24072. }
  24073. else {
  24074. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  24075. }
  24076. }
  24077. return this;
  24078. };
  24079. /**
  24080. * Registers for this mesh a javascript function called just before the rendering process.
  24081. * This function is passed the current mesh.
  24082. * Return the Mesh.
  24083. */
  24084. Mesh.prototype.registerBeforeRender = function (func) {
  24085. this.onBeforeRenderObservable.add(func);
  24086. return this;
  24087. };
  24088. /**
  24089. * Disposes a previously registered javascript function called before the rendering.
  24090. * This function is passed the current mesh.
  24091. * Returns the Mesh.
  24092. */
  24093. Mesh.prototype.unregisterBeforeRender = function (func) {
  24094. this.onBeforeRenderObservable.removeCallback(func);
  24095. return this;
  24096. };
  24097. /**
  24098. * Registers for this mesh a javascript function called just after the rendering is complete.
  24099. * This function is passed the current mesh.
  24100. * Returns the Mesh.
  24101. */
  24102. Mesh.prototype.registerAfterRender = function (func) {
  24103. this.onAfterRenderObservable.add(func);
  24104. return this;
  24105. };
  24106. /**
  24107. * Disposes a previously registered javascript function called after the rendering.
  24108. * This function is passed the current mesh.
  24109. * Return the Mesh.
  24110. */
  24111. Mesh.prototype.unregisterAfterRender = function (func) {
  24112. this.onAfterRenderObservable.removeCallback(func);
  24113. return this;
  24114. };
  24115. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  24116. var scene = this.getScene();
  24117. this._batchCache.mustReturn = false;
  24118. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  24119. this._batchCache.visibleInstances[subMeshId] = null;
  24120. if (this._visibleInstances) {
  24121. var currentRenderId = scene.getRenderId();
  24122. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  24123. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  24124. var selfRenderId = this._renderId;
  24125. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  24126. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  24127. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  24128. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  24129. }
  24130. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  24131. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  24132. this._batchCache.mustReturn = true;
  24133. return this._batchCache;
  24134. }
  24135. if (currentRenderId !== selfRenderId) {
  24136. this._batchCache.renderSelf[subMeshId] = false;
  24137. }
  24138. }
  24139. this._renderIdForInstances[subMeshId] = currentRenderId;
  24140. }
  24141. return this._batchCache;
  24142. };
  24143. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  24144. var visibleInstances = batch.visibleInstances[subMesh._id];
  24145. var matricesCount = visibleInstances.length + 1;
  24146. var bufferSize = matricesCount * 16 * 4;
  24147. var currentInstancesBufferSize = this._instancesBufferSize;
  24148. var instancesBuffer = this._instancesBuffer;
  24149. while (this._instancesBufferSize < bufferSize) {
  24150. this._instancesBufferSize *= 2;
  24151. }
  24152. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  24153. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  24154. }
  24155. var offset = 0;
  24156. var instancesCount = 0;
  24157. var world = this.getWorldMatrix();
  24158. if (batch.renderSelf[subMesh._id]) {
  24159. world.copyToArray(this._instancesData, offset);
  24160. offset += 16;
  24161. instancesCount++;
  24162. }
  24163. if (visibleInstances) {
  24164. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  24165. var instance = visibleInstances[instanceIndex];
  24166. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  24167. offset += 16;
  24168. instancesCount++;
  24169. }
  24170. }
  24171. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  24172. if (instancesBuffer) {
  24173. instancesBuffer.dispose();
  24174. }
  24175. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  24176. this._instancesBuffer = instancesBuffer;
  24177. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  24178. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  24179. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  24180. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  24181. }
  24182. else {
  24183. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  24184. }
  24185. this.geometry._bind(effect);
  24186. this._draw(subMesh, fillMode, instancesCount);
  24187. engine.unbindInstanceAttributes();
  24188. return this;
  24189. };
  24190. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  24191. var scene = this.getScene();
  24192. var engine = scene.getEngine();
  24193. if (hardwareInstancedRendering) {
  24194. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  24195. }
  24196. else {
  24197. if (batch.renderSelf[subMesh._id]) {
  24198. // Draw
  24199. if (onBeforeDraw) {
  24200. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  24201. }
  24202. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  24203. }
  24204. if (batch.visibleInstances[subMesh._id]) {
  24205. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  24206. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  24207. // World
  24208. var world = instance.getWorldMatrix();
  24209. if (onBeforeDraw) {
  24210. onBeforeDraw(true, world, effectiveMaterial);
  24211. }
  24212. // Draw
  24213. this._draw(subMesh, fillMode);
  24214. }
  24215. }
  24216. }
  24217. return this;
  24218. };
  24219. /**
  24220. * Triggers the draw call for the mesh.
  24221. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  24222. * Returns the Mesh.
  24223. */
  24224. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  24225. var scene = this.getScene();
  24226. // Managing instances
  24227. var batch = this._getInstancesRenderList(subMesh._id);
  24228. if (batch.mustReturn) {
  24229. return this;
  24230. }
  24231. // Checking geometry state
  24232. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24233. return this;
  24234. }
  24235. var callbackIndex;
  24236. this.onBeforeRenderObservable.notifyObservers(this);
  24237. var engine = scene.getEngine();
  24238. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24239. // Material
  24240. var effectiveMaterial = subMesh.getMaterial();
  24241. if (!effectiveMaterial) {
  24242. return this;
  24243. }
  24244. if (effectiveMaterial.storeEffectOnSubMeshes) {
  24245. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  24246. return this;
  24247. }
  24248. }
  24249. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  24250. return this;
  24251. }
  24252. // Outline - step 1
  24253. var savedDepthWrite = engine.getDepthWrite();
  24254. if (this.renderOutline) {
  24255. engine.setDepthWrite(false);
  24256. scene.getOutlineRenderer().render(subMesh, batch);
  24257. engine.setDepthWrite(savedDepthWrite);
  24258. }
  24259. var effect;
  24260. if (effectiveMaterial.storeEffectOnSubMeshes) {
  24261. effect = subMesh.effect;
  24262. }
  24263. else {
  24264. effect = effectiveMaterial.getEffect();
  24265. }
  24266. effectiveMaterial._preBind(effect);
  24267. // Bind
  24268. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  24269. this._bind(subMesh, effect, fillMode);
  24270. var world = this.getWorldMatrix();
  24271. if (effectiveMaterial.storeEffectOnSubMeshes) {
  24272. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  24273. }
  24274. else {
  24275. effectiveMaterial.bind(world, this);
  24276. }
  24277. // Alpha mode
  24278. if (enableAlphaMode) {
  24279. engine.setAlphaMode(effectiveMaterial.alphaMode);
  24280. }
  24281. // Draw
  24282. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  24283. // Unbind
  24284. effectiveMaterial.unbind();
  24285. // Outline - step 2
  24286. if (this.renderOutline && savedDepthWrite) {
  24287. engine.setDepthWrite(true);
  24288. engine.setColorWrite(false);
  24289. scene.getOutlineRenderer().render(subMesh, batch);
  24290. engine.setColorWrite(true);
  24291. }
  24292. // Overlay
  24293. if (this.renderOverlay) {
  24294. var currentMode = engine.getAlphaMode();
  24295. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24296. scene.getOutlineRenderer().render(subMesh, batch, true);
  24297. engine.setAlphaMode(currentMode);
  24298. }
  24299. this.onAfterRenderObservable.notifyObservers(this);
  24300. return this;
  24301. };
  24302. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  24303. if (isInstance) {
  24304. effectiveMaterial.bindOnlyWorldMatrix(world);
  24305. }
  24306. return this;
  24307. };
  24308. /**
  24309. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  24310. */
  24311. Mesh.prototype.getEmittedParticleSystems = function () {
  24312. var results = new Array();
  24313. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24314. var particleSystem = this.getScene().particleSystems[index];
  24315. if (particleSystem.emitter === this) {
  24316. results.push(particleSystem);
  24317. }
  24318. }
  24319. return results;
  24320. };
  24321. /**
  24322. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  24323. */
  24324. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  24325. var results = new Array();
  24326. var descendants = this.getDescendants();
  24327. descendants.push(this);
  24328. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24329. var particleSystem = this.getScene().particleSystems[index];
  24330. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  24331. results.push(particleSystem);
  24332. }
  24333. }
  24334. return results;
  24335. };
  24336. Mesh.prototype._checkDelayState = function () {
  24337. var scene = this.getScene();
  24338. if (this._geometry) {
  24339. this._geometry.load(scene);
  24340. }
  24341. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24342. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24343. this._queueLoad(this, scene);
  24344. }
  24345. return this;
  24346. };
  24347. Mesh.prototype._queueLoad = function (mesh, scene) {
  24348. var _this = this;
  24349. scene._addPendingData(mesh);
  24350. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  24351. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24352. if (data instanceof ArrayBuffer) {
  24353. _this._delayLoadingFunction(data, _this);
  24354. }
  24355. else {
  24356. _this._delayLoadingFunction(JSON.parse(data), _this);
  24357. }
  24358. _this.instances.forEach(function (instance) {
  24359. instance._syncSubMeshes();
  24360. });
  24361. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24362. scene._removePendingData(_this);
  24363. }, function () { }, scene.database, getBinaryData);
  24364. return this;
  24365. };
  24366. /**
  24367. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  24368. */
  24369. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  24370. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24371. return false;
  24372. }
  24373. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  24374. return false;
  24375. }
  24376. this._checkDelayState();
  24377. return true;
  24378. };
  24379. /**
  24380. * Sets the mesh material by the material or multiMaterial `id` property.
  24381. * The material `id` is a string identifying the material or the multiMaterial.
  24382. * This method returns the Mesh.
  24383. */
  24384. Mesh.prototype.setMaterialByID = function (id) {
  24385. var materials = this.getScene().materials;
  24386. var index;
  24387. for (index = 0; index < materials.length; index++) {
  24388. if (materials[index].id === id) {
  24389. this.material = materials[index];
  24390. return this;
  24391. }
  24392. }
  24393. // Multi
  24394. var multiMaterials = this.getScene().multiMaterials;
  24395. for (index = 0; index < multiMaterials.length; index++) {
  24396. if (multiMaterials[index].id === id) {
  24397. this.material = multiMaterials[index];
  24398. return this;
  24399. }
  24400. }
  24401. return this;
  24402. };
  24403. /**
  24404. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  24405. */
  24406. Mesh.prototype.getAnimatables = function () {
  24407. var results = [];
  24408. if (this.material) {
  24409. results.push(this.material);
  24410. }
  24411. if (this.skeleton) {
  24412. results.push(this.skeleton);
  24413. }
  24414. return results;
  24415. };
  24416. /**
  24417. * Modifies the mesh geometry according to the passed transformation matrix.
  24418. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  24419. * The mesh normals are modified accordingly the same transformation.
  24420. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24421. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24422. * Returns the Mesh.
  24423. */
  24424. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  24425. // Position
  24426. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24427. return this;
  24428. }
  24429. var submeshes = this.subMeshes.splice(0);
  24430. this._resetPointsArrayCache();
  24431. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24432. var temp = [];
  24433. var index;
  24434. for (index = 0; index < data.length; index += 3) {
  24435. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  24436. }
  24437. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  24438. // Normals
  24439. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24440. return this;
  24441. }
  24442. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24443. temp = [];
  24444. for (index = 0; index < data.length; index += 3) {
  24445. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  24446. }
  24447. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  24448. // flip faces?
  24449. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  24450. this.flipFaces();
  24451. }
  24452. // Restore submeshes
  24453. this.releaseSubMeshes();
  24454. this.subMeshes = submeshes;
  24455. return this;
  24456. };
  24457. /**
  24458. * Modifies the mesh geometry according to its own current World Matrix.
  24459. * The mesh World Matrix is then reset.
  24460. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  24461. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24462. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24463. * Returns the Mesh.
  24464. */
  24465. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  24466. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  24467. this.scaling.copyFromFloats(1, 1, 1);
  24468. this.position.copyFromFloats(0, 0, 0);
  24469. this.rotation.copyFromFloats(0, 0, 0);
  24470. //only if quaternion is already set
  24471. if (this.rotationQuaternion) {
  24472. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  24473. }
  24474. this._worldMatrix = BABYLON.Matrix.Identity();
  24475. return this;
  24476. };
  24477. // Cache
  24478. Mesh.prototype._resetPointsArrayCache = function () {
  24479. this._positions = null;
  24480. return this;
  24481. };
  24482. Mesh.prototype._generatePointsArray = function () {
  24483. if (this._positions)
  24484. return true;
  24485. this._positions = [];
  24486. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24487. if (!data) {
  24488. return false;
  24489. }
  24490. for (var index = 0; index < data.length; index += 3) {
  24491. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  24492. }
  24493. return true;
  24494. };
  24495. /**
  24496. * Returns a new Mesh object generated from the current mesh properties.
  24497. * This method must not get confused with createInstance().
  24498. * The parameter `name` is a string, the name given to the new mesh.
  24499. * The optional parameter `newParent` can be any Node object (default `null`).
  24500. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  24501. * 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.
  24502. */
  24503. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  24504. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24505. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  24506. };
  24507. /**
  24508. * Disposes the mesh.
  24509. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  24510. */
  24511. Mesh.prototype.dispose = function (doNotRecurse) {
  24512. var _this = this;
  24513. if (this._geometry) {
  24514. this._geometry.releaseForMesh(this, true);
  24515. }
  24516. // Sources
  24517. var meshes = this.getScene().meshes;
  24518. meshes.forEach(function (mesh) {
  24519. if (mesh._source && mesh._source === _this) {
  24520. mesh._source = null;
  24521. }
  24522. });
  24523. this._source = null;
  24524. // Instances
  24525. if (this._instancesBuffer) {
  24526. this._instancesBuffer.dispose();
  24527. this._instancesBuffer = null;
  24528. }
  24529. while (this.instances.length) {
  24530. this.instances[0].dispose();
  24531. }
  24532. // Highlight layers.
  24533. var highlightLayers = this.getScene().highlightLayers;
  24534. for (var i = 0; i < highlightLayers.length; i++) {
  24535. var highlightLayer = highlightLayers[i];
  24536. if (highlightLayer) {
  24537. highlightLayer.removeMesh(this);
  24538. highlightLayer.removeExcludedMesh(this);
  24539. }
  24540. }
  24541. _super.prototype.dispose.call(this, doNotRecurse);
  24542. };
  24543. /**
  24544. * Modifies the mesh geometry according to a displacement map.
  24545. * 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.
  24546. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24547. * This method returns nothing.
  24548. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24549. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24550. * 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.
  24551. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24552. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24553. *
  24554. * Returns the Mesh.
  24555. */
  24556. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24557. var _this = this;
  24558. var scene = this.getScene();
  24559. var onload = function (img) {
  24560. // Getting height map data
  24561. var canvas = document.createElement("canvas");
  24562. var context = canvas.getContext("2d");
  24563. var heightMapWidth = img.width;
  24564. var heightMapHeight = img.height;
  24565. canvas.width = heightMapWidth;
  24566. canvas.height = heightMapHeight;
  24567. context.drawImage(img, 0, 0);
  24568. // Create VertexData from map data
  24569. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24570. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24571. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24572. //execute success callback, if set
  24573. if (onSuccess) {
  24574. onSuccess(_this);
  24575. }
  24576. };
  24577. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24578. return this;
  24579. };
  24580. /**
  24581. * Modifies the mesh geometry according to a displacementMap buffer.
  24582. * 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.
  24583. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24584. * This method returns nothing.
  24585. * 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.
  24586. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24587. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24588. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24589. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24590. *
  24591. * Returns the Mesh.
  24592. */
  24593. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24594. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24595. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24596. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24597. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24598. return this;
  24599. }
  24600. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24601. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24602. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24603. var position = BABYLON.Vector3.Zero();
  24604. var normal = BABYLON.Vector3.Zero();
  24605. var uv = BABYLON.Vector2.Zero();
  24606. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24607. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24608. for (var index = 0; index < positions.length; index += 3) {
  24609. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24610. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24611. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24612. // Compute height
  24613. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24614. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24615. var pos = (u + v * heightMapWidth) * 4;
  24616. var r = buffer[pos] / 255.0;
  24617. var g = buffer[pos + 1] / 255.0;
  24618. var b = buffer[pos + 2] / 255.0;
  24619. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24620. normal.normalize();
  24621. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24622. position = position.add(normal);
  24623. position.toArray(positions, index);
  24624. }
  24625. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24626. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24627. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24628. return this;
  24629. };
  24630. /**
  24631. * Modify the mesh to get a flat shading rendering.
  24632. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24633. * This method returns the Mesh.
  24634. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24635. */
  24636. Mesh.prototype.convertToFlatShadedMesh = function () {
  24637. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24638. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24639. var kinds = this.getVerticesDataKinds();
  24640. var vbs = [];
  24641. var data = [];
  24642. var newdata = [];
  24643. var updatableNormals = false;
  24644. var kindIndex;
  24645. var kind;
  24646. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24647. kind = kinds[kindIndex];
  24648. var vertexBuffer = this.getVertexBuffer(kind);
  24649. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24650. updatableNormals = vertexBuffer.isUpdatable();
  24651. kinds.splice(kindIndex, 1);
  24652. kindIndex--;
  24653. continue;
  24654. }
  24655. vbs[kind] = vertexBuffer;
  24656. data[kind] = vbs[kind].getData();
  24657. newdata[kind] = [];
  24658. }
  24659. // Save previous submeshes
  24660. var previousSubmeshes = this.subMeshes.slice(0);
  24661. var indices = this.getIndices();
  24662. var totalIndices = this.getTotalIndices();
  24663. // Generating unique vertices per face
  24664. var index;
  24665. for (index = 0; index < totalIndices; index++) {
  24666. var vertexIndex = indices[index];
  24667. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24668. kind = kinds[kindIndex];
  24669. var stride = vbs[kind].getStrideSize();
  24670. for (var offset = 0; offset < stride; offset++) {
  24671. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24672. }
  24673. }
  24674. }
  24675. // Updating faces & normal
  24676. var normals = [];
  24677. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24678. for (index = 0; index < totalIndices; index += 3) {
  24679. indices[index] = index;
  24680. indices[index + 1] = index + 1;
  24681. indices[index + 2] = index + 2;
  24682. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24683. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24684. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24685. var p1p2 = p1.subtract(p2);
  24686. var p3p2 = p3.subtract(p2);
  24687. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24688. // Store same normals for every vertex
  24689. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24690. normals.push(normal.x);
  24691. normals.push(normal.y);
  24692. normals.push(normal.z);
  24693. }
  24694. }
  24695. this.setIndices(indices);
  24696. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24697. // Updating vertex buffers
  24698. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24699. kind = kinds[kindIndex];
  24700. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24701. }
  24702. // Updating submeshes
  24703. this.releaseSubMeshes();
  24704. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24705. var previousOne = previousSubmeshes[submeshIndex];
  24706. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24707. }
  24708. this.synchronizeInstances();
  24709. return this;
  24710. };
  24711. /**
  24712. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24713. * In other words, more vertices, no more indices and a single bigger VBO.
  24714. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24715. * Returns the Mesh.
  24716. */
  24717. Mesh.prototype.convertToUnIndexedMesh = function () {
  24718. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24719. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24720. var kinds = this.getVerticesDataKinds();
  24721. var vbs = [];
  24722. var data = [];
  24723. var newdata = [];
  24724. var updatableNormals = false;
  24725. var kindIndex;
  24726. var kind;
  24727. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24728. kind = kinds[kindIndex];
  24729. var vertexBuffer = this.getVertexBuffer(kind);
  24730. vbs[kind] = vertexBuffer;
  24731. data[kind] = vbs[kind].getData();
  24732. newdata[kind] = [];
  24733. }
  24734. // Save previous submeshes
  24735. var previousSubmeshes = this.subMeshes.slice(0);
  24736. var indices = this.getIndices();
  24737. var totalIndices = this.getTotalIndices();
  24738. // Generating unique vertices per face
  24739. var index;
  24740. for (index = 0; index < totalIndices; index++) {
  24741. var vertexIndex = indices[index];
  24742. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24743. kind = kinds[kindIndex];
  24744. var stride = vbs[kind].getStrideSize();
  24745. for (var offset = 0; offset < stride; offset++) {
  24746. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24747. }
  24748. }
  24749. }
  24750. // Updating indices
  24751. for (index = 0; index < totalIndices; index += 3) {
  24752. indices[index] = index;
  24753. indices[index + 1] = index + 1;
  24754. indices[index + 2] = index + 2;
  24755. }
  24756. this.setIndices(indices);
  24757. // Updating vertex buffers
  24758. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24759. kind = kinds[kindIndex];
  24760. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24761. }
  24762. // Updating submeshes
  24763. this.releaseSubMeshes();
  24764. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24765. var previousOne = previousSubmeshes[submeshIndex];
  24766. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24767. }
  24768. this._unIndexed = true;
  24769. this.synchronizeInstances();
  24770. return this;
  24771. };
  24772. /**
  24773. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24774. * This method returns the Mesh.
  24775. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24776. */
  24777. Mesh.prototype.flipFaces = function (flipNormals) {
  24778. if (flipNormals === void 0) { flipNormals = false; }
  24779. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24780. var i;
  24781. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24782. for (i = 0; i < vertex_data.normals.length; i++) {
  24783. vertex_data.normals[i] *= -1;
  24784. }
  24785. }
  24786. var temp;
  24787. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24788. // reassign indices
  24789. temp = vertex_data.indices[i + 1];
  24790. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24791. vertex_data.indices[i + 2] = temp;
  24792. }
  24793. vertex_data.applyToMesh(this);
  24794. return this;
  24795. };
  24796. // Instances
  24797. /**
  24798. * Creates a new InstancedMesh object from the mesh model.
  24799. * An instance shares the same properties and the same material than its model.
  24800. * Only these properties of each instance can then be set individually :
  24801. * - position
  24802. * - rotation
  24803. * - rotationQuaternion
  24804. * - setPivotMatrix
  24805. * - scaling
  24806. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24807. * Warning : this method is not supported for Line mesh and LineSystem
  24808. */
  24809. Mesh.prototype.createInstance = function (name) {
  24810. return new BABYLON.InstancedMesh(name, this);
  24811. };
  24812. /**
  24813. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24814. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24815. * This method returns the Mesh.
  24816. */
  24817. Mesh.prototype.synchronizeInstances = function () {
  24818. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24819. var instance = this.instances[instanceIndex];
  24820. instance._syncSubMeshes();
  24821. }
  24822. return this;
  24823. };
  24824. /**
  24825. * Simplify the mesh according to the given array of settings.
  24826. * Function will return immediately and will simplify async. It returns the Mesh.
  24827. * @param settings a collection of simplification settings.
  24828. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24829. * @param type the type of simplification to run.
  24830. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24831. */
  24832. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24833. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24834. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24835. this.getScene().simplificationQueue.addTask({
  24836. settings: settings,
  24837. parallelProcessing: parallelProcessing,
  24838. mesh: this,
  24839. simplificationType: simplificationType,
  24840. successCallback: successCallback
  24841. });
  24842. return this;
  24843. };
  24844. /**
  24845. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24846. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24847. * This should be used together with the simplification to avoid disappearing triangles.
  24848. * Returns the Mesh.
  24849. * @param successCallback an optional success callback to be called after the optimization finished.
  24850. */
  24851. Mesh.prototype.optimizeIndices = function (successCallback) {
  24852. var _this = this;
  24853. var indices = this.getIndices();
  24854. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24855. var vectorPositions = [];
  24856. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24857. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24858. }
  24859. var dupes = [];
  24860. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24861. var realPos = vectorPositions.length - 1 - iteration;
  24862. var testedPosition = vectorPositions[realPos];
  24863. for (var j = 0; j < realPos; ++j) {
  24864. var againstPosition = vectorPositions[j];
  24865. if (testedPosition.equals(againstPosition)) {
  24866. dupes[realPos] = j;
  24867. break;
  24868. }
  24869. }
  24870. }, function () {
  24871. for (var i = 0; i < indices.length; ++i) {
  24872. indices[i] = dupes[indices[i]] || indices[i];
  24873. }
  24874. //indices are now reordered
  24875. var originalSubMeshes = _this.subMeshes.slice(0);
  24876. _this.setIndices(indices);
  24877. _this.subMeshes = originalSubMeshes;
  24878. if (successCallback) {
  24879. successCallback(_this);
  24880. }
  24881. });
  24882. return this;
  24883. };
  24884. Mesh.prototype.serialize = function (serializationObject) {
  24885. serializationObject.name = this.name;
  24886. serializationObject.id = this.id;
  24887. serializationObject.type = this.getClassName();
  24888. if (BABYLON.Tags.HasTags(this)) {
  24889. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24890. }
  24891. serializationObject.position = this.position.asArray();
  24892. if (this.rotationQuaternion) {
  24893. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24894. }
  24895. else if (this.rotation) {
  24896. serializationObject.rotation = this.rotation.asArray();
  24897. }
  24898. serializationObject.scaling = this.scaling.asArray();
  24899. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24900. serializationObject.isEnabled = this.isEnabled();
  24901. serializationObject.isVisible = this.isVisible;
  24902. serializationObject.infiniteDistance = this.infiniteDistance;
  24903. serializationObject.pickable = this.isPickable;
  24904. serializationObject.receiveShadows = this.receiveShadows;
  24905. serializationObject.billboardMode = this.billboardMode;
  24906. serializationObject.visibility = this.visibility;
  24907. serializationObject.checkCollisions = this.checkCollisions;
  24908. serializationObject.isBlocker = this.isBlocker;
  24909. // Parent
  24910. if (this.parent) {
  24911. serializationObject.parentId = this.parent.id;
  24912. }
  24913. // Geometry
  24914. var geometry = this._geometry;
  24915. if (geometry) {
  24916. var geometryId = geometry.id;
  24917. serializationObject.geometryId = geometryId;
  24918. // SubMeshes
  24919. serializationObject.subMeshes = [];
  24920. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24921. var subMesh = this.subMeshes[subIndex];
  24922. serializationObject.subMeshes.push({
  24923. materialIndex: subMesh.materialIndex,
  24924. verticesStart: subMesh.verticesStart,
  24925. verticesCount: subMesh.verticesCount,
  24926. indexStart: subMesh.indexStart,
  24927. indexCount: subMesh.indexCount
  24928. });
  24929. }
  24930. }
  24931. // Material
  24932. if (this.material) {
  24933. serializationObject.materialId = this.material.id;
  24934. }
  24935. else {
  24936. this.material = null;
  24937. }
  24938. // Skeleton
  24939. if (this.skeleton) {
  24940. serializationObject.skeletonId = this.skeleton.id;
  24941. }
  24942. // Physics
  24943. //TODO implement correct serialization for physics impostors.
  24944. if (this.getPhysicsImpostor()) {
  24945. var impostor = this.getPhysicsImpostor();
  24946. serializationObject.physicsMass = impostor.getParam("mass");
  24947. serializationObject.physicsFriction = impostor.getParam("friction");
  24948. serializationObject.physicsRestitution = impostor.getParam("mass");
  24949. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  24950. }
  24951. // Metadata
  24952. if (this.metadata) {
  24953. serializationObject.metadata = this.metadata;
  24954. }
  24955. // Instances
  24956. serializationObject.instances = [];
  24957. for (var index = 0; index < this.instances.length; index++) {
  24958. var instance = this.instances[index];
  24959. var serializationInstance = {
  24960. name: instance.name,
  24961. position: instance.position.asArray(),
  24962. scaling: instance.scaling.asArray()
  24963. };
  24964. if (instance.rotationQuaternion) {
  24965. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24966. }
  24967. else if (instance.rotation) {
  24968. serializationInstance.rotation = instance.rotation.asArray();
  24969. }
  24970. serializationObject.instances.push(serializationInstance);
  24971. // Animations
  24972. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24973. serializationInstance.ranges = instance.serializeAnimationRanges();
  24974. }
  24975. // Animations
  24976. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24977. serializationObject.ranges = this.serializeAnimationRanges();
  24978. // Layer mask
  24979. serializationObject.layerMask = this.layerMask;
  24980. // Alpha
  24981. serializationObject.alphaIndex = this.alphaIndex;
  24982. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24983. // Overlay
  24984. serializationObject.overlayAlpha = this.overlayAlpha;
  24985. serializationObject.overlayColor = this.overlayColor.asArray();
  24986. serializationObject.renderOverlay = this.renderOverlay;
  24987. // Fog
  24988. serializationObject.applyFog = this.applyFog;
  24989. // Action Manager
  24990. if (this.actionManager) {
  24991. serializationObject.actions = this.actionManager.serialize(this.name);
  24992. }
  24993. };
  24994. // Statics
  24995. /**
  24996. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24997. * The parameter `parsedMesh` is the mesh to be copied.
  24998. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24999. */
  25000. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  25001. var mesh;
  25002. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  25003. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  25004. }
  25005. else {
  25006. mesh = new Mesh(parsedMesh.name, scene);
  25007. }
  25008. mesh.id = parsedMesh.id;
  25009. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  25010. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  25011. if (parsedMesh.metadata !== undefined) {
  25012. mesh.metadata = parsedMesh.metadata;
  25013. }
  25014. if (parsedMesh.rotationQuaternion) {
  25015. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  25016. }
  25017. else if (parsedMesh.rotation) {
  25018. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  25019. }
  25020. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  25021. if (parsedMesh.localMatrix) {
  25022. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  25023. }
  25024. else if (parsedMesh.pivotMatrix) {
  25025. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  25026. }
  25027. mesh.setEnabled(parsedMesh.isEnabled);
  25028. mesh.isVisible = parsedMesh.isVisible;
  25029. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  25030. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  25031. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  25032. if (parsedMesh.applyFog !== undefined) {
  25033. mesh.applyFog = parsedMesh.applyFog;
  25034. }
  25035. if (parsedMesh.pickable !== undefined) {
  25036. mesh.isPickable = parsedMesh.pickable;
  25037. }
  25038. if (parsedMesh.alphaIndex !== undefined) {
  25039. mesh.alphaIndex = parsedMesh.alphaIndex;
  25040. }
  25041. mesh.receiveShadows = parsedMesh.receiveShadows;
  25042. mesh.billboardMode = parsedMesh.billboardMode;
  25043. if (parsedMesh.visibility !== undefined) {
  25044. mesh.visibility = parsedMesh.visibility;
  25045. }
  25046. mesh.checkCollisions = parsedMesh.checkCollisions;
  25047. if (parsedMesh.isBlocker !== undefined) {
  25048. mesh.isBlocker = parsedMesh.isBlocker;
  25049. }
  25050. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  25051. // freezeWorldMatrix
  25052. if (parsedMesh.freezeWorldMatrix) {
  25053. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  25054. }
  25055. // Parent
  25056. if (parsedMesh.parentId) {
  25057. mesh._waitingParentId = parsedMesh.parentId;
  25058. }
  25059. // Actions
  25060. if (parsedMesh.actions !== undefined) {
  25061. mesh._waitingActions = parsedMesh.actions;
  25062. }
  25063. // Overlay
  25064. if (parsedMesh.overlayAlpha !== undefined) {
  25065. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  25066. }
  25067. if (parsedMesh.overlayColor !== undefined) {
  25068. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  25069. }
  25070. if (parsedMesh.renderOverlay !== undefined) {
  25071. mesh.renderOverlay = parsedMesh.renderOverlay;
  25072. }
  25073. // Geometry
  25074. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  25075. if (parsedMesh.delayLoadingFile) {
  25076. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25077. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  25078. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  25079. if (parsedMesh._binaryInfo) {
  25080. mesh._binaryInfo = parsedMesh._binaryInfo;
  25081. }
  25082. mesh._delayInfo = [];
  25083. if (parsedMesh.hasUVs) {
  25084. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  25085. }
  25086. if (parsedMesh.hasUVs2) {
  25087. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  25088. }
  25089. if (parsedMesh.hasUVs3) {
  25090. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  25091. }
  25092. if (parsedMesh.hasUVs4) {
  25093. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  25094. }
  25095. if (parsedMesh.hasUVs5) {
  25096. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  25097. }
  25098. if (parsedMesh.hasUVs6) {
  25099. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  25100. }
  25101. if (parsedMesh.hasColors) {
  25102. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  25103. }
  25104. if (parsedMesh.hasMatricesIndices) {
  25105. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25106. }
  25107. if (parsedMesh.hasMatricesWeights) {
  25108. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25109. }
  25110. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  25111. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  25112. mesh._checkDelayState();
  25113. }
  25114. }
  25115. else {
  25116. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  25117. }
  25118. // Material
  25119. if (parsedMesh.materialId) {
  25120. mesh.setMaterialByID(parsedMesh.materialId);
  25121. }
  25122. else {
  25123. mesh.material = null;
  25124. }
  25125. // Skeleton
  25126. if (parsedMesh.skeletonId > -1) {
  25127. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  25128. if (parsedMesh.numBoneInfluencers) {
  25129. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  25130. }
  25131. }
  25132. // Animations
  25133. if (parsedMesh.animations) {
  25134. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25135. var parsedAnimation = parsedMesh.animations[animationIndex];
  25136. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25137. }
  25138. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  25139. }
  25140. if (parsedMesh.autoAnimate) {
  25141. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  25142. }
  25143. // Layer Mask
  25144. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  25145. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  25146. }
  25147. else {
  25148. mesh.layerMask = 0x0FFFFFFF;
  25149. }
  25150. // Physics
  25151. if (parsedMesh.physicsImpostor) {
  25152. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  25153. mass: parsedMesh.physicsMass,
  25154. friction: parsedMesh.physicsFriction,
  25155. restitution: parsedMesh.physicsRestitution
  25156. }, scene);
  25157. }
  25158. // Instances
  25159. if (parsedMesh.instances) {
  25160. for (var index = 0; index < parsedMesh.instances.length; index++) {
  25161. var parsedInstance = parsedMesh.instances[index];
  25162. var instance = mesh.createInstance(parsedInstance.name);
  25163. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  25164. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  25165. if (parsedInstance.parentId) {
  25166. instance._waitingParentId = parsedInstance.parentId;
  25167. }
  25168. if (parsedInstance.rotationQuaternion) {
  25169. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  25170. }
  25171. else if (parsedInstance.rotation) {
  25172. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  25173. }
  25174. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  25175. instance.checkCollisions = mesh.checkCollisions;
  25176. if (parsedMesh.animations) {
  25177. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25178. parsedAnimation = parsedMesh.animations[animationIndex];
  25179. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25180. }
  25181. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  25182. }
  25183. }
  25184. }
  25185. return mesh;
  25186. };
  25187. /**
  25188. * Creates a ribbon mesh.
  25189. * Please consider using the same method from the MeshBuilder class instead.
  25190. * 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.
  25191. *
  25192. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25193. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25194. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25195. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25196. * 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.
  25197. * 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.
  25198. * 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
  25199. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25200. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25201. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25202. */
  25203. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  25204. return BABYLON.MeshBuilder.CreateRibbon(name, {
  25205. pathArray: pathArray,
  25206. closeArray: closeArray,
  25207. closePath: closePath,
  25208. offset: offset,
  25209. updatable: updatable,
  25210. sideOrientation: sideOrientation,
  25211. instance: instance
  25212. }, scene);
  25213. };
  25214. /**
  25215. * Creates a plane polygonal mesh. By default, this is a disc.
  25216. * Please consider using the same method from the MeshBuilder class instead.
  25217. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25218. * 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.
  25219. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25220. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25221. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25222. */
  25223. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  25224. var options = {
  25225. radius: radius,
  25226. tessellation: tessellation,
  25227. sideOrientation: sideOrientation,
  25228. updatable: updatable
  25229. };
  25230. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  25231. };
  25232. /**
  25233. * Creates a box mesh.
  25234. * Please consider using the same method from the MeshBuilder class instead.
  25235. * The parameter `size` sets the size (float) of each box side (default 1).
  25236. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25237. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25238. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25239. */
  25240. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  25241. var options = {
  25242. size: size,
  25243. sideOrientation: sideOrientation,
  25244. updatable: updatable
  25245. };
  25246. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  25247. };
  25248. /**
  25249. * Creates a sphere mesh.
  25250. * Please consider using the same method from the MeshBuilder class instead.
  25251. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25252. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25253. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25254. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25255. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25256. */
  25257. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  25258. var options = {
  25259. segments: segments,
  25260. diameterX: diameter,
  25261. diameterY: diameter,
  25262. diameterZ: diameter,
  25263. sideOrientation: sideOrientation,
  25264. updatable: updatable
  25265. };
  25266. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  25267. };
  25268. /**
  25269. * Creates a cylinder or a cone mesh.
  25270. * Please consider using the same method from the MeshBuilder class instead.
  25271. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25272. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25273. * 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.
  25274. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25275. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25276. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25277. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25278. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25279. */
  25280. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  25281. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  25282. if (scene !== undefined) {
  25283. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  25284. updatable = scene;
  25285. }
  25286. scene = subdivisions;
  25287. subdivisions = 1;
  25288. }
  25289. var options = {
  25290. height: height,
  25291. diameterTop: diameterTop,
  25292. diameterBottom: diameterBottom,
  25293. tessellation: tessellation,
  25294. subdivisions: subdivisions,
  25295. sideOrientation: sideOrientation,
  25296. updatable: updatable
  25297. };
  25298. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  25299. };
  25300. // Torus (Code from SharpDX.org)
  25301. /**
  25302. * Creates a torus mesh.
  25303. * Please consider using the same method from the MeshBuilder class instead.
  25304. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25305. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25306. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25307. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25308. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25309. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25310. */
  25311. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  25312. var options = {
  25313. diameter: diameter,
  25314. thickness: thickness,
  25315. tessellation: tessellation,
  25316. sideOrientation: sideOrientation,
  25317. updatable: updatable
  25318. };
  25319. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  25320. };
  25321. /**
  25322. * Creates a torus knot mesh.
  25323. * Please consider using the same method from the MeshBuilder class instead.
  25324. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25325. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25326. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25327. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25328. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25329. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25330. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25331. */
  25332. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  25333. var options = {
  25334. radius: radius,
  25335. tube: tube,
  25336. radialSegments: radialSegments,
  25337. tubularSegments: tubularSegments,
  25338. p: p,
  25339. q: q,
  25340. sideOrientation: sideOrientation,
  25341. updatable: updatable
  25342. };
  25343. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  25344. };
  25345. /**
  25346. * Creates a line mesh.
  25347. * Please consider using the same method from the MeshBuilder class instead.
  25348. * 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.
  25349. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25350. * The parameter `points` is an array successive Vector3.
  25351. * 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
  25352. * When updating an instance, remember that only point positions can change, not the number of points.
  25353. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25354. */
  25355. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  25356. var options = {
  25357. points: points,
  25358. updatable: updatable,
  25359. instance: instance
  25360. };
  25361. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  25362. };
  25363. /**
  25364. * Creates a dashed line mesh.
  25365. * Please consider using the same method from the MeshBuilder class instead.
  25366. * 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.
  25367. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25368. * The parameter `points` is an array successive Vector3.
  25369. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25370. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25371. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25372. * 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
  25373. * When updating an instance, remember that only point positions can change, not the number of points.
  25374. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25375. */
  25376. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  25377. var options = {
  25378. points: points,
  25379. dashSize: dashSize,
  25380. gapSize: gapSize,
  25381. dashNb: dashNb,
  25382. updatable: updatable,
  25383. instance: instance
  25384. };
  25385. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  25386. };
  25387. /**
  25388. * Creates an extruded shape mesh.
  25389. * 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.
  25390. * Please consider using the same method from the MeshBuilder class instead.
  25391. *
  25392. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25393. * 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
  25394. * extruded along the Z axis.
  25395. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25396. * 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.
  25397. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25398. * 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
  25399. * 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
  25400. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25401. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25402. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25403. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25404. */
  25405. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  25406. var options = {
  25407. shape: shape,
  25408. path: path,
  25409. scale: scale,
  25410. rotation: rotation,
  25411. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25412. sideOrientation: sideOrientation,
  25413. instance: instance,
  25414. updatable: updatable
  25415. };
  25416. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  25417. };
  25418. /**
  25419. * Creates an custom extruded shape mesh.
  25420. * 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.
  25421. * Please consider using the same method from the MeshBuilder class instead.
  25422. *
  25423. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25424. * 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
  25425. * extruded along the Z axis.
  25426. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25427. * 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
  25428. * and the distance of this point from the begining of the path :
  25429. * ```javascript
  25430. * var rotationFunction = function(i, distance) {
  25431. * // do things
  25432. * return rotationValue; }
  25433. * ```
  25434. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25435. * 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
  25436. * and the distance of this point from the begining of the path :
  25437. * ```javascript
  25438. * var scaleFunction = function(i, distance) {
  25439. * // do things
  25440. * return scaleValue;}
  25441. * ```
  25442. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25443. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25444. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25445. * 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
  25446. * 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
  25447. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25448. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25449. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25450. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25451. */
  25452. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  25453. var options = {
  25454. shape: shape,
  25455. path: path,
  25456. scaleFunction: scaleFunction,
  25457. rotationFunction: rotationFunction,
  25458. ribbonCloseArray: ribbonCloseArray,
  25459. ribbonClosePath: ribbonClosePath,
  25460. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25461. sideOrientation: sideOrientation,
  25462. instance: instance,
  25463. updatable: updatable
  25464. };
  25465. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  25466. };
  25467. /**
  25468. * Creates lathe mesh.
  25469. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25470. * Please consider using the same method from the MeshBuilder class instead.
  25471. * 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
  25472. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25473. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25474. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25475. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25476. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25477. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25478. */
  25479. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  25480. var options = {
  25481. shape: shape,
  25482. radius: radius,
  25483. tessellation: tessellation,
  25484. sideOrientation: sideOrientation,
  25485. updatable: updatable
  25486. };
  25487. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  25488. };
  25489. /**
  25490. * Creates a plane mesh.
  25491. * Please consider using the same method from the MeshBuilder class instead.
  25492. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25493. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25494. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25496. */
  25497. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  25498. var options = {
  25499. size: size,
  25500. width: size,
  25501. height: size,
  25502. sideOrientation: sideOrientation,
  25503. updatable: updatable
  25504. };
  25505. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  25506. };
  25507. /**
  25508. * Creates a ground mesh.
  25509. * Please consider using the same method from the MeshBuilder class instead.
  25510. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25511. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25513. */
  25514. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25515. var options = {
  25516. width: width,
  25517. height: height,
  25518. subdivisions: subdivisions,
  25519. updatable: updatable
  25520. };
  25521. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25522. };
  25523. /**
  25524. * Creates a tiled ground mesh.
  25525. * Please consider using the same method from the MeshBuilder class instead.
  25526. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25527. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25528. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25529. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25530. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25531. * numbers of subdivisions on the ground width and height of each tile.
  25532. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25533. */
  25534. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25535. var options = {
  25536. xmin: xmin,
  25537. zmin: zmin,
  25538. xmax: xmax,
  25539. zmax: zmax,
  25540. subdivisions: subdivisions,
  25541. precision: precision,
  25542. updatable: updatable
  25543. };
  25544. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25545. };
  25546. /**
  25547. * Creates a ground mesh from a height map.
  25548. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25549. * Please consider using the same method from the MeshBuilder class instead.
  25550. * The parameter `url` sets the URL of the height map image resource.
  25551. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25552. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25553. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25554. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25555. * 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).
  25556. * This function is passed the newly built mesh :
  25557. * ```javascript
  25558. * function(mesh) { // do things
  25559. * return; }
  25560. * ```
  25561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25562. */
  25563. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25564. var options = {
  25565. width: width,
  25566. height: height,
  25567. subdivisions: subdivisions,
  25568. minHeight: minHeight,
  25569. maxHeight: maxHeight,
  25570. updatable: updatable,
  25571. onReady: onReady
  25572. };
  25573. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25574. };
  25575. /**
  25576. * Creates a tube mesh.
  25577. * 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.
  25578. * Please consider using the same method from the MeshBuilder class instead.
  25579. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25580. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25581. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25582. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25583. * 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.
  25584. * It must return a radius value (positive float) :
  25585. * ```javascript
  25586. * var radiusFunction = function(i, distance) {
  25587. * // do things
  25588. * return radius; }
  25589. * ```
  25590. * 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
  25591. * 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
  25592. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25593. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25594. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25595. */
  25596. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25597. var options = {
  25598. path: path,
  25599. radius: radius,
  25600. tessellation: tessellation,
  25601. radiusFunction: radiusFunction,
  25602. arc: 1,
  25603. cap: cap,
  25604. updatable: updatable,
  25605. sideOrientation: sideOrientation,
  25606. instance: instance
  25607. };
  25608. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25609. };
  25610. /**
  25611. * Creates a polyhedron mesh.
  25612. * Please consider using the same method from the MeshBuilder class instead.
  25613. * 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
  25614. * to choose the wanted type.
  25615. * The parameter `size` (positive float, default 1) sets the polygon size.
  25616. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25617. * 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`.
  25618. * 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
  25619. * 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)`).
  25620. * 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
  25621. * 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.
  25622. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25623. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25624. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25625. */
  25626. Mesh.CreatePolyhedron = function (name, options, scene) {
  25627. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25628. };
  25629. /**
  25630. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25631. * Please consider using the same method from the MeshBuilder class instead.
  25632. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25633. * 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`).
  25634. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25635. * 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.
  25636. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25637. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25638. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25639. */
  25640. Mesh.CreateIcoSphere = function (name, options, scene) {
  25641. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25642. };
  25643. /**
  25644. * Creates a decal mesh.
  25645. * Please consider using the same method from the MeshBuilder class instead.
  25646. * 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.
  25647. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25648. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25649. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25650. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25651. */
  25652. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25653. var options = {
  25654. position: position,
  25655. normal: normal,
  25656. size: size,
  25657. angle: angle
  25658. };
  25659. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25660. };
  25661. // Skeletons
  25662. /**
  25663. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25664. */
  25665. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25666. var source;
  25667. if (!this._sourcePositions) {
  25668. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25669. this._sourcePositions = new Float32Array(source);
  25670. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  25671. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25672. }
  25673. }
  25674. return this._sourcePositions;
  25675. };
  25676. /**
  25677. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25678. */
  25679. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25680. var source;
  25681. if (!this._sourceNormals) {
  25682. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25683. this._sourceNormals = new Float32Array(source);
  25684. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  25685. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25686. }
  25687. }
  25688. return this._sourceNormals;
  25689. };
  25690. /**
  25691. * Updates the vertex buffer by applying transformation from the bones.
  25692. * Returns the Mesh.
  25693. *
  25694. * @param {skeleton} skeleton to apply
  25695. */
  25696. Mesh.prototype.applySkeleton = function (skeleton) {
  25697. if (!this.geometry) {
  25698. return this;
  25699. }
  25700. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25701. return this;
  25702. }
  25703. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25704. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25705. return this;
  25706. }
  25707. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25708. return this;
  25709. }
  25710. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25711. return this;
  25712. }
  25713. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25714. return this;
  25715. }
  25716. if (!this._sourcePositions) {
  25717. var submeshes = this.subMeshes.slice();
  25718. this.setPositionsForCPUSkinning();
  25719. this.subMeshes = submeshes;
  25720. }
  25721. if (!this._sourceNormals) {
  25722. this.setNormalsForCPUSkinning();
  25723. }
  25724. // positionsData checks for not being Float32Array will only pass at most once
  25725. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25726. if (!(positionsData instanceof Float32Array)) {
  25727. positionsData = new Float32Array(positionsData);
  25728. }
  25729. // normalsData checks for not being Float32Array will only pass at most once
  25730. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25731. if (!(normalsData instanceof Float32Array)) {
  25732. normalsData = new Float32Array(normalsData);
  25733. }
  25734. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25735. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25736. var needExtras = this.numBoneInfluencers > 4;
  25737. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25738. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25739. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25740. var tempVector3 = BABYLON.Vector3.Zero();
  25741. var finalMatrix = new BABYLON.Matrix();
  25742. var tempMatrix = new BABYLON.Matrix();
  25743. var matWeightIdx = 0;
  25744. var inf;
  25745. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25746. var weight;
  25747. for (inf = 0; inf < 4; inf++) {
  25748. weight = matricesWeightsData[matWeightIdx + inf];
  25749. if (weight > 0) {
  25750. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25751. finalMatrix.addToSelf(tempMatrix);
  25752. }
  25753. else
  25754. break;
  25755. }
  25756. if (needExtras) {
  25757. for (inf = 0; inf < 4; inf++) {
  25758. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25759. if (weight > 0) {
  25760. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25761. finalMatrix.addToSelf(tempMatrix);
  25762. }
  25763. else
  25764. break;
  25765. }
  25766. }
  25767. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25768. tempVector3.toArray(positionsData, index);
  25769. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25770. tempVector3.toArray(normalsData, index);
  25771. finalMatrix.reset();
  25772. }
  25773. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25774. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25775. return this;
  25776. };
  25777. // Tools
  25778. /**
  25779. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25780. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25781. */
  25782. Mesh.MinMax = function (meshes) {
  25783. var minVector = null;
  25784. var maxVector = null;
  25785. meshes.forEach(function (mesh, index, array) {
  25786. var boundingBox = mesh.getBoundingInfo().boundingBox;
  25787. if (!minVector) {
  25788. minVector = boundingBox.minimumWorld;
  25789. maxVector = boundingBox.maximumWorld;
  25790. }
  25791. else {
  25792. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25793. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25794. }
  25795. });
  25796. return {
  25797. min: minVector,
  25798. max: maxVector
  25799. };
  25800. };
  25801. /**
  25802. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25803. */
  25804. Mesh.Center = function (meshesOrMinMaxVector) {
  25805. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25806. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25807. };
  25808. /**
  25809. * Merge the array of meshes into a single mesh for performance reasons.
  25810. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25811. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25812. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25813. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25814. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25815. */
  25816. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25817. if (disposeSource === void 0) { disposeSource = true; }
  25818. var index;
  25819. if (!allow32BitsIndices) {
  25820. var totalVertices = 0;
  25821. // Counting vertices
  25822. for (index = 0; index < meshes.length; index++) {
  25823. if (meshes[index]) {
  25824. totalVertices += meshes[index].getTotalVertices();
  25825. if (totalVertices > 65536) {
  25826. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25827. return null;
  25828. }
  25829. }
  25830. }
  25831. }
  25832. // Merge
  25833. var vertexData;
  25834. var otherVertexData;
  25835. var indiceArray = new Array();
  25836. var source;
  25837. for (index = 0; index < meshes.length; index++) {
  25838. if (meshes[index]) {
  25839. meshes[index].computeWorldMatrix(true);
  25840. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25841. otherVertexData.transform(meshes[index].getWorldMatrix());
  25842. if (vertexData) {
  25843. vertexData.merge(otherVertexData);
  25844. }
  25845. else {
  25846. vertexData = otherVertexData;
  25847. source = meshes[index];
  25848. }
  25849. if (subdivideWithSubMeshes) {
  25850. indiceArray.push(meshes[index].getTotalIndices());
  25851. }
  25852. }
  25853. }
  25854. if (!meshSubclass) {
  25855. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25856. }
  25857. vertexData.applyToMesh(meshSubclass);
  25858. // Setting properties
  25859. meshSubclass.material = source.material;
  25860. meshSubclass.checkCollisions = source.checkCollisions;
  25861. // Cleaning
  25862. if (disposeSource) {
  25863. for (index = 0; index < meshes.length; index++) {
  25864. if (meshes[index]) {
  25865. meshes[index].dispose();
  25866. }
  25867. }
  25868. }
  25869. // Subdivide
  25870. if (subdivideWithSubMeshes) {
  25871. //-- Suppresions du submesh global
  25872. meshSubclass.releaseSubMeshes();
  25873. index = 0;
  25874. var offset = 0;
  25875. //-- aplique la subdivision en fonction du tableau d'indices
  25876. while (index < indiceArray.length) {
  25877. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25878. offset += indiceArray[index];
  25879. index++;
  25880. }
  25881. }
  25882. return meshSubclass;
  25883. };
  25884. return Mesh;
  25885. }(BABYLON.AbstractMesh));
  25886. // Consts
  25887. Mesh._FRONTSIDE = 0;
  25888. Mesh._BACKSIDE = 1;
  25889. Mesh._DOUBLESIDE = 2;
  25890. Mesh._DEFAULTSIDE = 0;
  25891. Mesh._NO_CAP = 0;
  25892. Mesh._CAP_START = 1;
  25893. Mesh._CAP_END = 2;
  25894. Mesh._CAP_ALL = 3;
  25895. BABYLON.Mesh = Mesh;
  25896. })(BABYLON || (BABYLON = {}));
  25897. //# sourceMappingURL=babylon.mesh.js.map
  25898. var BABYLON;
  25899. (function (BABYLON) {
  25900. var SubMesh = (function () {
  25901. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25902. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25903. this.materialIndex = materialIndex;
  25904. this.verticesStart = verticesStart;
  25905. this.verticesCount = verticesCount;
  25906. this.indexStart = indexStart;
  25907. this.indexCount = indexCount;
  25908. this._renderId = 0;
  25909. this._mesh = mesh;
  25910. this._renderingMesh = renderingMesh || mesh;
  25911. mesh.subMeshes.push(this);
  25912. this._trianglePlanes = [];
  25913. this._id = mesh.subMeshes.length - 1;
  25914. if (createBoundingBox) {
  25915. this.refreshBoundingInfo();
  25916. mesh.computeWorldMatrix(true);
  25917. }
  25918. }
  25919. Object.defineProperty(SubMesh.prototype, "effect", {
  25920. get: function () {
  25921. return this._materialEffect;
  25922. },
  25923. set: function (effect) {
  25924. this._materialEffect = effect;
  25925. },
  25926. enumerable: true,
  25927. configurable: true
  25928. });
  25929. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25930. get: function () {
  25931. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25932. },
  25933. enumerable: true,
  25934. configurable: true
  25935. });
  25936. /**
  25937. * Returns the submesh BoudingInfo object.
  25938. */
  25939. SubMesh.prototype.getBoundingInfo = function () {
  25940. if (this.IsGlobal) {
  25941. return this._mesh.getBoundingInfo();
  25942. }
  25943. return this._boundingInfo;
  25944. };
  25945. /**
  25946. * Sets the submesh BoundingInfo.
  25947. * Return the SubMesh.
  25948. */
  25949. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25950. this._boundingInfo = boundingInfo;
  25951. return this;
  25952. };
  25953. /**
  25954. * Returns the mesh of the current submesh.
  25955. */
  25956. SubMesh.prototype.getMesh = function () {
  25957. return this._mesh;
  25958. };
  25959. /**
  25960. * Returns the rendering mesh of the submesh.
  25961. */
  25962. SubMesh.prototype.getRenderingMesh = function () {
  25963. return this._renderingMesh;
  25964. };
  25965. /**
  25966. * Returns the submesh material.
  25967. */
  25968. SubMesh.prototype.getMaterial = function () {
  25969. var rootMaterial = this._renderingMesh.material;
  25970. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  25971. var multiMaterial = rootMaterial;
  25972. return multiMaterial.getSubMaterial(this.materialIndex);
  25973. }
  25974. if (!rootMaterial) {
  25975. return this._mesh.getScene().defaultMaterial;
  25976. }
  25977. return rootMaterial;
  25978. };
  25979. // Methods
  25980. /**
  25981. * Sets a new updated BoundingInfo object to the submesh.
  25982. * Returns the SubMesh.
  25983. */
  25984. SubMesh.prototype.refreshBoundingInfo = function () {
  25985. this._lastColliderWorldVertices = null;
  25986. if (this.IsGlobal) {
  25987. return;
  25988. }
  25989. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25990. if (!data) {
  25991. this._boundingInfo = this._mesh._boundingInfo;
  25992. return;
  25993. }
  25994. var indices = this._renderingMesh.getIndices();
  25995. var extend;
  25996. //is this the only submesh?
  25997. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25998. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25999. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  26000. }
  26001. else {
  26002. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  26003. }
  26004. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26005. return this;
  26006. };
  26007. SubMesh.prototype._checkCollision = function (collider) {
  26008. return this.getBoundingInfo()._checkCollision(collider);
  26009. };
  26010. /**
  26011. * Updates the submesh BoundingInfo.
  26012. * Returns the Submesh.
  26013. */
  26014. SubMesh.prototype.updateBoundingInfo = function (world) {
  26015. if (!this.getBoundingInfo()) {
  26016. this.refreshBoundingInfo();
  26017. }
  26018. this.getBoundingInfo().update(world);
  26019. return this;
  26020. };
  26021. /**
  26022. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  26023. * Boolean returned.
  26024. */
  26025. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  26026. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  26027. };
  26028. /**
  26029. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  26030. * Boolean returned.
  26031. */
  26032. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  26033. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  26034. };
  26035. /**
  26036. * Renders the submesh.
  26037. * Returns it.
  26038. */
  26039. SubMesh.prototype.render = function (enableAlphaMode) {
  26040. this._renderingMesh.render(this, enableAlphaMode);
  26041. return this;
  26042. };
  26043. /**
  26044. * Returns a new Index Buffer.
  26045. * Type returned : WebGLBuffer.
  26046. */
  26047. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  26048. if (!this._linesIndexBuffer) {
  26049. var linesIndices = [];
  26050. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26051. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  26052. }
  26053. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  26054. this.linesIndexCount = linesIndices.length;
  26055. }
  26056. return this._linesIndexBuffer;
  26057. };
  26058. /**
  26059. * True is the passed Ray intersects the submesh bounding box.
  26060. * Boolean returned.
  26061. */
  26062. SubMesh.prototype.canIntersects = function (ray) {
  26063. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  26064. };
  26065. /**
  26066. * Returns an object IntersectionInfo.
  26067. */
  26068. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  26069. var intersectInfo = null;
  26070. // LineMesh first as it's also a Mesh...
  26071. if (this._mesh instanceof BABYLON.LinesMesh) {
  26072. var lineMesh = this._mesh;
  26073. // Line test
  26074. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  26075. var p0 = positions[indices[index]];
  26076. var p1 = positions[indices[index + 1]];
  26077. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  26078. if (length < 0) {
  26079. continue;
  26080. }
  26081. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  26082. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  26083. if (fastCheck) {
  26084. break;
  26085. }
  26086. }
  26087. }
  26088. }
  26089. else {
  26090. // Triangles test
  26091. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26092. var p0 = positions[indices[index]];
  26093. var p1 = positions[indices[index + 1]];
  26094. var p2 = positions[indices[index + 2]];
  26095. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  26096. if (currentIntersectInfo) {
  26097. if (currentIntersectInfo.distance < 0) {
  26098. continue;
  26099. }
  26100. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  26101. intersectInfo = currentIntersectInfo;
  26102. intersectInfo.faceId = index / 3;
  26103. if (fastCheck) {
  26104. break;
  26105. }
  26106. }
  26107. }
  26108. }
  26109. }
  26110. return intersectInfo;
  26111. };
  26112. // Clone
  26113. /**
  26114. * Creates a new Submesh from the passed Mesh.
  26115. */
  26116. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  26117. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  26118. if (!this.IsGlobal) {
  26119. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  26120. }
  26121. return result;
  26122. };
  26123. // Dispose
  26124. /**
  26125. * Disposes the Submesh.
  26126. * Returns nothing.
  26127. */
  26128. SubMesh.prototype.dispose = function () {
  26129. if (this._linesIndexBuffer) {
  26130. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  26131. this._linesIndexBuffer = null;
  26132. }
  26133. // Remove from mesh
  26134. var index = this._mesh.subMeshes.indexOf(this);
  26135. this._mesh.subMeshes.splice(index, 1);
  26136. };
  26137. // Statics
  26138. /**
  26139. * Creates a new Submesh from the passed parameters :
  26140. * - materialIndex (integer) : the index of the main mesh material.
  26141. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  26142. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  26143. * - mesh (Mesh) : the main mesh to create the submesh from.
  26144. * - renderingMesh (optional Mesh) : rendering mesh.
  26145. */
  26146. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  26147. var minVertexIndex = Number.MAX_VALUE;
  26148. var maxVertexIndex = -Number.MAX_VALUE;
  26149. renderingMesh = renderingMesh || mesh;
  26150. var indices = renderingMesh.getIndices();
  26151. for (var index = startIndex; index < startIndex + indexCount; index++) {
  26152. var vertexIndex = indices[index];
  26153. if (vertexIndex < minVertexIndex)
  26154. minVertexIndex = vertexIndex;
  26155. if (vertexIndex > maxVertexIndex)
  26156. maxVertexIndex = vertexIndex;
  26157. }
  26158. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  26159. };
  26160. return SubMesh;
  26161. }());
  26162. BABYLON.SubMesh = SubMesh;
  26163. })(BABYLON || (BABYLON = {}));
  26164. //# sourceMappingURL=babylon.subMesh.js.map
  26165. var BABYLON;
  26166. (function (BABYLON) {
  26167. var MeshBuilder = (function () {
  26168. function MeshBuilder() {
  26169. }
  26170. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  26171. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  26172. return BABYLON.Mesh.DOUBLESIDE;
  26173. }
  26174. if (orientation === undefined || orientation === null) {
  26175. return BABYLON.Mesh.FRONTSIDE;
  26176. }
  26177. return orientation;
  26178. };
  26179. /**
  26180. * Creates a box mesh.
  26181. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  26182. * The parameter `size` sets the size (float) of each box side (default 1).
  26183. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  26184. * 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).
  26185. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  26186. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26187. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26188. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26189. */
  26190. MeshBuilder.CreateBox = function (name, options, scene) {
  26191. var box = new BABYLON.Mesh(name, scene);
  26192. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26193. box.sideOrientation = options.sideOrientation;
  26194. var vertexData = BABYLON.VertexData.CreateBox(options);
  26195. vertexData.applyToMesh(box, options.updatable);
  26196. return box;
  26197. };
  26198. /**
  26199. * Creates a sphere mesh.
  26200. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  26201. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  26202. * 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`).
  26203. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  26204. * 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
  26205. * 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).
  26206. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26207. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26208. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26209. */
  26210. MeshBuilder.CreateSphere = function (name, options, scene) {
  26211. var sphere = new BABYLON.Mesh(name, scene);
  26212. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26213. sphere.sideOrientation = options.sideOrientation;
  26214. var vertexData = BABYLON.VertexData.CreateSphere(options);
  26215. vertexData.applyToMesh(sphere, options.updatable);
  26216. return sphere;
  26217. };
  26218. /**
  26219. * Creates a plane polygonal mesh. By default, this is a disc.
  26220. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  26221. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  26222. * 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.
  26223. * 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
  26224. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26225. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26226. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26227. */
  26228. MeshBuilder.CreateDisc = function (name, options, scene) {
  26229. var disc = new BABYLON.Mesh(name, scene);
  26230. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26231. disc.sideOrientation = options.sideOrientation;
  26232. var vertexData = BABYLON.VertexData.CreateDisc(options);
  26233. vertexData.applyToMesh(disc, options.updatable);
  26234. return disc;
  26235. };
  26236. /**
  26237. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  26238. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  26239. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  26240. * 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`).
  26241. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  26242. * 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.
  26243. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26244. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26245. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26246. */
  26247. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  26248. var sphere = new BABYLON.Mesh(name, scene);
  26249. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26250. sphere.sideOrientation = options.sideOrientation;
  26251. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  26252. vertexData.applyToMesh(sphere, options.updatable);
  26253. return sphere;
  26254. };
  26255. ;
  26256. /**
  26257. * Creates a ribbon mesh.
  26258. * 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.
  26259. *
  26260. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  26261. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  26262. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  26263. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  26264. * 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.
  26265. * 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.
  26266. * 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
  26267. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26268. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26269. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26270. * 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.
  26271. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  26272. * 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
  26273. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  26274. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  26275. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26276. */
  26277. MeshBuilder.CreateRibbon = function (name, options, scene) {
  26278. var pathArray = options.pathArray;
  26279. var closeArray = options.closeArray;
  26280. var closePath = options.closePath;
  26281. var offset = options.offset;
  26282. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26283. var instance = options.instance;
  26284. var updatable = options.updatable;
  26285. if (instance) {
  26286. // positionFunction : ribbon case
  26287. // only pathArray and sideOrientation parameters are taken into account for positions update
  26288. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  26289. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  26290. var positionFunction = function (positions) {
  26291. var minlg = pathArray[0].length;
  26292. var i = 0;
  26293. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  26294. for (var si = 1; si <= ns; si++) {
  26295. for (var p = 0; p < pathArray.length; p++) {
  26296. var path = pathArray[p];
  26297. var l = path.length;
  26298. minlg = (minlg < l) ? minlg : l;
  26299. var j = 0;
  26300. while (j < minlg) {
  26301. positions[i] = path[j].x;
  26302. positions[i + 1] = path[j].y;
  26303. positions[i + 2] = path[j].z;
  26304. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  26305. BABYLON.Tmp.Vector3[0].x = path[j].x;
  26306. }
  26307. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  26308. BABYLON.Tmp.Vector3[1].x = path[j].x;
  26309. }
  26310. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  26311. BABYLON.Tmp.Vector3[0].y = path[j].y;
  26312. }
  26313. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  26314. BABYLON.Tmp.Vector3[1].y = path[j].y;
  26315. }
  26316. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  26317. BABYLON.Tmp.Vector3[0].z = path[j].z;
  26318. }
  26319. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  26320. BABYLON.Tmp.Vector3[1].z = path[j].z;
  26321. }
  26322. j++;
  26323. i += 3;
  26324. }
  26325. if (instance._closePath) {
  26326. positions[i] = path[0].x;
  26327. positions[i + 1] = path[0].y;
  26328. positions[i + 2] = path[0].z;
  26329. i += 3;
  26330. }
  26331. }
  26332. }
  26333. };
  26334. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26335. positionFunction(positions);
  26336. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  26337. instance._boundingInfo.update(instance._worldMatrix);
  26338. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  26339. if (options.colors) {
  26340. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26341. for (var c = 0; c < options.colors.length; c++) {
  26342. colors[c * 4] = options.colors[c].r;
  26343. colors[c * 4 + 1] = options.colors[c].g;
  26344. colors[c * 4 + 2] = options.colors[c].b;
  26345. colors[c * 4 + 3] = options.colors[c].a;
  26346. }
  26347. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  26348. }
  26349. if (options.uvs) {
  26350. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26351. for (var i = 0; i < options.uvs.length; i++) {
  26352. uvs[i * 2] = options.uvs[i].x;
  26353. uvs[i * 2 + 1] = options.uvs[i].y;
  26354. }
  26355. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  26356. }
  26357. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  26358. var indices = instance.getIndices();
  26359. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26360. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  26361. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  26362. if (instance._closePath) {
  26363. var indexFirst = 0;
  26364. var indexLast = 0;
  26365. for (var p = 0; p < pathArray.length; p++) {
  26366. indexFirst = instance._idx[p] * 3;
  26367. if (p + 1 < pathArray.length) {
  26368. indexLast = (instance._idx[p + 1] - 1) * 3;
  26369. }
  26370. else {
  26371. indexLast = normals.length - 3;
  26372. }
  26373. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26374. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26375. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26376. normals[indexLast] = normals[indexFirst];
  26377. normals[indexLast + 1] = normals[indexFirst + 1];
  26378. normals[indexLast + 2] = normals[indexFirst + 2];
  26379. }
  26380. }
  26381. if (!(instance.areNormalsFrozen)) {
  26382. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  26383. }
  26384. }
  26385. return instance;
  26386. }
  26387. else {
  26388. var ribbon = new BABYLON.Mesh(name, scene);
  26389. ribbon.sideOrientation = sideOrientation;
  26390. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  26391. if (closePath) {
  26392. ribbon._idx = vertexData._idx;
  26393. }
  26394. ribbon._closePath = closePath;
  26395. ribbon._closeArray = closeArray;
  26396. vertexData.applyToMesh(ribbon, updatable);
  26397. return ribbon;
  26398. }
  26399. };
  26400. /**
  26401. * Creates a cylinder or a cone mesh.
  26402. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  26403. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  26404. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  26405. * 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.
  26406. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  26407. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  26408. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  26409. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  26410. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  26411. * 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).
  26412. * 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
  26413. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  26414. * 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
  26415. * 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.
  26416. * If `enclose` is false, a ring surface is one element.
  26417. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  26418. * 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
  26419. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26420. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26421. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26422. */
  26423. MeshBuilder.CreateCylinder = function (name, options, scene) {
  26424. var cylinder = new BABYLON.Mesh(name, scene);
  26425. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26426. cylinder.sideOrientation = options.sideOrientation;
  26427. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  26428. vertexData.applyToMesh(cylinder, options.updatable);
  26429. return cylinder;
  26430. };
  26431. /**
  26432. * Creates a torus mesh.
  26433. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  26434. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  26435. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  26436. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  26437. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26438. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26439. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26440. */
  26441. MeshBuilder.CreateTorus = function (name, options, scene) {
  26442. var torus = new BABYLON.Mesh(name, scene);
  26443. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26444. torus.sideOrientation = options.sideOrientation;
  26445. var vertexData = BABYLON.VertexData.CreateTorus(options);
  26446. vertexData.applyToMesh(torus, options.updatable);
  26447. return torus;
  26448. };
  26449. /**
  26450. * Creates a torus knot mesh.
  26451. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  26452. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  26453. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  26454. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  26455. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  26456. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26457. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26458. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26459. */
  26460. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  26461. var torusKnot = new BABYLON.Mesh(name, scene);
  26462. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26463. torusKnot.sideOrientation = options.sideOrientation;
  26464. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  26465. vertexData.applyToMesh(torusKnot, options.updatable);
  26466. return torusKnot;
  26467. };
  26468. /**
  26469. * Creates a line system mesh.
  26470. * A line system is a pool of many lines gathered in a single mesh.
  26471. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  26472. * 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.
  26473. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  26474. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  26475. * 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
  26476. * 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
  26477. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  26478. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26479. */
  26480. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  26481. var instance = options.instance;
  26482. var lines = options.lines;
  26483. if (instance) {
  26484. var positionFunction = function (positions) {
  26485. var i = 0;
  26486. for (var l = 0; l < lines.length; l++) {
  26487. var points = lines[l];
  26488. for (var p = 0; p < points.length; p++) {
  26489. positions[i] = points[p].x;
  26490. positions[i + 1] = points[p].y;
  26491. positions[i + 2] = points[p].z;
  26492. i += 3;
  26493. }
  26494. }
  26495. };
  26496. instance.updateMeshPositions(positionFunction, false);
  26497. return instance;
  26498. }
  26499. // line system creation
  26500. var lineSystem = new BABYLON.LinesMesh(name, scene);
  26501. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  26502. vertexData.applyToMesh(lineSystem, options.updatable);
  26503. return lineSystem;
  26504. };
  26505. /**
  26506. * Creates a line mesh.
  26507. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  26508. * 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.
  26509. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26510. * The parameter `points` is an array successive Vector3.
  26511. * 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
  26512. * When updating an instance, remember that only point positions can change, not the number of points.
  26513. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26514. */
  26515. MeshBuilder.CreateLines = function (name, options, scene) {
  26516. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  26517. return lines;
  26518. };
  26519. /**
  26520. * Creates a dashed line mesh.
  26521. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  26522. * 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.
  26523. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26524. * The parameter `points` is an array successive Vector3.
  26525. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  26526. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  26527. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  26528. * 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
  26529. * When updating an instance, remember that only point positions can change, not the number of points.
  26530. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26531. */
  26532. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  26533. var points = options.points;
  26534. var instance = options.instance;
  26535. var gapSize = options.gapSize;
  26536. var dashNb = options.dashNb;
  26537. var dashSize = options.dashSize;
  26538. if (instance) {
  26539. var positionFunction = function (positions) {
  26540. var curvect = BABYLON.Vector3.Zero();
  26541. var nbSeg = positions.length / 6;
  26542. var lg = 0;
  26543. var nb = 0;
  26544. var shft = 0;
  26545. var dashshft = 0;
  26546. var curshft = 0;
  26547. var p = 0;
  26548. var i = 0;
  26549. var j = 0;
  26550. for (i = 0; i < points.length - 1; i++) {
  26551. points[i + 1].subtractToRef(points[i], curvect);
  26552. lg += curvect.length();
  26553. }
  26554. shft = lg / nbSeg;
  26555. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  26556. for (i = 0; i < points.length - 1; i++) {
  26557. points[i + 1].subtractToRef(points[i], curvect);
  26558. nb = Math.floor(curvect.length() / shft);
  26559. curvect.normalize();
  26560. j = 0;
  26561. while (j < nb && p < positions.length) {
  26562. curshft = shft * j;
  26563. positions[p] = points[i].x + curshft * curvect.x;
  26564. positions[p + 1] = points[i].y + curshft * curvect.y;
  26565. positions[p + 2] = points[i].z + curshft * curvect.z;
  26566. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  26567. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  26568. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  26569. p += 6;
  26570. j++;
  26571. }
  26572. }
  26573. while (p < positions.length) {
  26574. positions[p] = points[i].x;
  26575. positions[p + 1] = points[i].y;
  26576. positions[p + 2] = points[i].z;
  26577. p += 3;
  26578. }
  26579. };
  26580. instance.updateMeshPositions(positionFunction, false);
  26581. return instance;
  26582. }
  26583. // dashed lines creation
  26584. var dashedLines = new BABYLON.LinesMesh(name, scene);
  26585. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  26586. vertexData.applyToMesh(dashedLines, options.updatable);
  26587. dashedLines.dashSize = dashSize;
  26588. dashedLines.gapSize = gapSize;
  26589. return dashedLines;
  26590. };
  26591. /**
  26592. * Creates an extruded shape mesh.
  26593. * 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.
  26594. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  26595. *
  26596. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26597. * 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
  26598. * extruded along the Z axis.
  26599. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26600. * 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.
  26601. * The parameter `scale` (float, default 1) is the value to scale the shape.
  26602. * 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
  26603. * 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
  26604. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26605. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26606. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26607. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26608. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26609. */
  26610. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  26611. var path = options.path;
  26612. var shape = options.shape;
  26613. var scale = options.scale || 1;
  26614. var rotation = options.rotation || 0;
  26615. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  26616. var updatable = options.updatable;
  26617. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26618. var instance = options.instance;
  26619. var invertUV = options.invertUV || false;
  26620. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  26621. };
  26622. /**
  26623. * Creates an custom extruded shape mesh.
  26624. * 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.
  26625. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  26626. *
  26627. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26628. * 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
  26629. * extruded along the Z axis.
  26630. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26631. * 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
  26632. * and the distance of this point from the begining of the path :
  26633. * ```javascript
  26634. * var rotationFunction = function(i, distance) {
  26635. * // do things
  26636. * return rotationValue; }
  26637. * ```
  26638. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  26639. * 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
  26640. * and the distance of this point from the begining of the path :
  26641. * ```javascript
  26642. * var scaleFunction = function(i, distance) {
  26643. * // do things
  26644. * return scaleValue;}
  26645. * ```
  26646. * It must returns a float value that will be the scale value applied to the shape on each path point.
  26647. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  26648. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  26649. * 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
  26650. * 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
  26651. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26652. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26653. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26654. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26655. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26656. */
  26657. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  26658. var path = options.path;
  26659. var shape = options.shape;
  26660. var scaleFunction = options.scaleFunction || (function () { return 1; });
  26661. var rotationFunction = options.rotationFunction || (function () { return 0; });
  26662. var ribbonCloseArray = options.ribbonCloseArray || false;
  26663. var ribbonClosePath = options.ribbonClosePath || false;
  26664. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  26665. var updatable = options.updatable;
  26666. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26667. var instance = options.instance;
  26668. var invertUV = options.invertUV || false;
  26669. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  26670. };
  26671. /**
  26672. * Creates lathe mesh.
  26673. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  26674. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  26675. *
  26676. * 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
  26677. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  26678. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  26679. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  26680. * 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.
  26681. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  26682. * 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
  26683. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26684. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26685. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26686. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26687. */
  26688. MeshBuilder.CreateLathe = function (name, options, scene) {
  26689. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  26690. var closed = (options.closed === undefined) ? true : options.closed;
  26691. var shape = options.shape;
  26692. var radius = options.radius || 1;
  26693. var tessellation = options.tessellation || 64;
  26694. var updatable = options.updatable;
  26695. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26696. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  26697. var pi2 = Math.PI * 2;
  26698. var paths = new Array();
  26699. var invertUV = options.invertUV || false;
  26700. var i = 0;
  26701. var p = 0;
  26702. var step = pi2 / tessellation * arc;
  26703. var rotated;
  26704. var path = new Array();
  26705. ;
  26706. for (i = 0; i <= tessellation; i++) {
  26707. var path = [];
  26708. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  26709. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  26710. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  26711. }
  26712. for (p = 0; p < shape.length; p++) {
  26713. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  26714. path.push(rotated);
  26715. }
  26716. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  26717. 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));
  26718. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  26719. }
  26720. paths.push(path);
  26721. }
  26722. // lathe ribbon
  26723. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  26724. return lathe;
  26725. };
  26726. /**
  26727. * Creates a plane mesh.
  26728. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  26729. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  26730. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  26731. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  26732. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26733. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26734. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26735. */
  26736. MeshBuilder.CreatePlane = function (name, options, scene) {
  26737. var plane = new BABYLON.Mesh(name, scene);
  26738. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26739. plane.sideOrientation = options.sideOrientation;
  26740. var vertexData = BABYLON.VertexData.CreatePlane(options);
  26741. vertexData.applyToMesh(plane, options.updatable);
  26742. if (options.sourcePlane) {
  26743. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  26744. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  26745. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  26746. plane.rotate(vectorProduct, product);
  26747. }
  26748. return plane;
  26749. };
  26750. /**
  26751. * Creates a ground mesh.
  26752. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  26753. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  26754. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  26755. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26756. */
  26757. MeshBuilder.CreateGround = function (name, options, scene) {
  26758. var ground = new BABYLON.GroundMesh(name, scene);
  26759. ground._setReady(false);
  26760. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26761. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26762. ground._width = options.width || 1;
  26763. ground._height = options.height || 1;
  26764. ground._maxX = ground._width / 2;
  26765. ground._maxZ = ground._height / 2;
  26766. ground._minX = -ground._maxX;
  26767. ground._minZ = -ground._maxZ;
  26768. var vertexData = BABYLON.VertexData.CreateGround(options);
  26769. vertexData.applyToMesh(ground, options.updatable);
  26770. ground._setReady(true);
  26771. return ground;
  26772. };
  26773. /**
  26774. * Creates a tiled ground mesh.
  26775. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  26776. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  26777. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  26778. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  26779. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  26780. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  26781. * numbers of subdivisions on the ground width and height of each tile.
  26782. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26783. */
  26784. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  26785. var tiledGround = new BABYLON.Mesh(name, scene);
  26786. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  26787. vertexData.applyToMesh(tiledGround, options.updatable);
  26788. return tiledGround;
  26789. };
  26790. /**
  26791. * Creates a ground mesh from a height map.
  26792. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  26793. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  26794. * The parameter `url` sets the URL of the height map image resource.
  26795. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  26796. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  26797. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  26798. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  26799. * 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.
  26800. * 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).
  26801. * This function is passed the newly built mesh :
  26802. * ```javascript
  26803. * function(mesh) { // do things
  26804. * return; }
  26805. * ```
  26806. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26807. */
  26808. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  26809. var width = options.width || 10.0;
  26810. var height = options.height || 10.0;
  26811. var subdivisions = options.subdivisions || 1 | 0;
  26812. var minHeight = options.minHeight || 0.0;
  26813. var maxHeight = options.maxHeight || 10.0;
  26814. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26815. var updatable = options.updatable;
  26816. var onReady = options.onReady;
  26817. var ground = new BABYLON.GroundMesh(name, scene);
  26818. ground._subdivisionsX = subdivisions;
  26819. ground._subdivisionsY = subdivisions;
  26820. ground._width = width;
  26821. ground._height = height;
  26822. ground._maxX = ground._width / 2.0;
  26823. ground._maxZ = ground._height / 2.0;
  26824. ground._minX = -ground._maxX;
  26825. ground._minZ = -ground._maxZ;
  26826. ground._setReady(false);
  26827. var onload = function (img) {
  26828. // Getting height map data
  26829. var canvas = document.createElement("canvas");
  26830. var context = canvas.getContext("2d");
  26831. var bufferWidth = img.width;
  26832. var bufferHeight = img.height;
  26833. canvas.width = bufferWidth;
  26834. canvas.height = bufferHeight;
  26835. context.drawImage(img, 0, 0);
  26836. // Create VertexData from map data
  26837. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26838. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  26839. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  26840. width: width, height: height,
  26841. subdivisions: subdivisions,
  26842. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  26843. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  26844. });
  26845. vertexData.applyToMesh(ground, updatable);
  26846. ground._setReady(true);
  26847. //execute ready callback, if set
  26848. if (onReady) {
  26849. onReady(ground);
  26850. }
  26851. };
  26852. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26853. return ground;
  26854. };
  26855. /**
  26856. * Creates a tube mesh.
  26857. * 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.
  26858. *
  26859. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  26860. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  26861. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  26862. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  26863. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  26864. * 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.
  26865. * It must return a radius value (positive float) :
  26866. * ```javascript
  26867. * var radiusFunction = function(i, distance) {
  26868. * // do things
  26869. * return radius; }
  26870. * ```
  26871. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  26872. * 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
  26873. * 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
  26874. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26875. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26876. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26877. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26878. */
  26879. MeshBuilder.CreateTube = function (name, options, scene) {
  26880. var path = options.path;
  26881. var radius = options.radius || 1.0;
  26882. var tessellation = options.tessellation || 64 | 0;
  26883. var radiusFunction = options.radiusFunction;
  26884. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  26885. var invertUV = options.invertUV || false;
  26886. var updatable = options.updatable;
  26887. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26888. var instance = options.instance;
  26889. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  26890. // tube geometry
  26891. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  26892. var tangents = path3D.getTangents();
  26893. var normals = path3D.getNormals();
  26894. var distances = path3D.getDistances();
  26895. var pi2 = Math.PI * 2;
  26896. var step = pi2 / tessellation * arc;
  26897. var returnRadius = function () { return radius; };
  26898. var radiusFunctionFinal = radiusFunction || returnRadius;
  26899. var circlePath;
  26900. var rad;
  26901. var normal;
  26902. var rotated;
  26903. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  26904. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  26905. for (var i = 0; i < path.length; i++) {
  26906. rad = radiusFunctionFinal(i, distances[i]); // current radius
  26907. circlePath = Array(); // current circle array
  26908. normal = normals[i]; // current normal
  26909. for (var t = 0; t < tessellation; t++) {
  26910. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  26911. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  26912. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  26913. rotated.scaleInPlace(rad).addInPlace(path[i]);
  26914. circlePath[t] = rotated;
  26915. }
  26916. circlePaths[index] = circlePath;
  26917. index++;
  26918. }
  26919. // cap
  26920. var capPath = function (nbPoints, pathIndex) {
  26921. var pointCap = Array();
  26922. for (var i = 0; i < nbPoints; i++) {
  26923. pointCap.push(path[pathIndex]);
  26924. }
  26925. return pointCap;
  26926. };
  26927. switch (cap) {
  26928. case BABYLON.Mesh.NO_CAP:
  26929. break;
  26930. case BABYLON.Mesh.CAP_START:
  26931. circlePaths[0] = capPath(tessellation, 0);
  26932. circlePaths[1] = circlePaths[2].slice(0);
  26933. break;
  26934. case BABYLON.Mesh.CAP_END:
  26935. circlePaths[index] = circlePaths[index - 1].slice(0);
  26936. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  26937. break;
  26938. case BABYLON.Mesh.CAP_ALL:
  26939. circlePaths[0] = capPath(tessellation, 0);
  26940. circlePaths[1] = circlePaths[2].slice(0);
  26941. circlePaths[index] = circlePaths[index - 1].slice(0);
  26942. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  26943. break;
  26944. default:
  26945. break;
  26946. }
  26947. return circlePaths;
  26948. };
  26949. var path3D;
  26950. var pathArray;
  26951. if (instance) {
  26952. var arc = options.arc || instance.arc;
  26953. path3D = (instance.path3D).update(path);
  26954. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  26955. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  26956. instance.path3D = path3D;
  26957. instance.pathArray = pathArray;
  26958. instance.arc = arc;
  26959. return instance;
  26960. }
  26961. // tube creation
  26962. path3D = new BABYLON.Path3D(path);
  26963. var newPathArray = new Array();
  26964. cap = (cap < 0 || cap > 3) ? 0 : cap;
  26965. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  26966. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  26967. tube.pathArray = pathArray;
  26968. tube.path3D = path3D;
  26969. tube.tessellation = tessellation;
  26970. tube.cap = cap;
  26971. tube.arc = options.arc;
  26972. return tube;
  26973. };
  26974. /**
  26975. * Creates a polyhedron mesh.
  26976. *
  26977. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  26978. * 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
  26979. * to choose the wanted type.
  26980. * The parameter `size` (positive float, default 1) sets the polygon size.
  26981. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  26982. * 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`.
  26983. * 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
  26984. * 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)`).
  26985. * 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
  26986. * 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.
  26987. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26988. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26989. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26990. */
  26991. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  26992. var polyhedron = new BABYLON.Mesh(name, scene);
  26993. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26994. polyhedron.sideOrientation = options.sideOrientation;
  26995. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  26996. vertexData.applyToMesh(polyhedron, options.updatable);
  26997. return polyhedron;
  26998. };
  26999. /**
  27000. * Creates a decal mesh.
  27001. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  27002. * 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.
  27003. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27004. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27005. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27006. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27007. */
  27008. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  27009. var indices = sourceMesh.getIndices();
  27010. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27011. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27012. var position = options.position || BABYLON.Vector3.Zero();
  27013. var normal = options.normal || BABYLON.Vector3.Up();
  27014. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  27015. var angle = options.angle || 0;
  27016. // Getting correct rotation
  27017. if (!normal) {
  27018. var target = new BABYLON.Vector3(0, 0, 1);
  27019. var camera = sourceMesh.getScene().activeCamera;
  27020. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  27021. normal = camera.globalPosition.subtract(cameraWorldTarget);
  27022. }
  27023. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  27024. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  27025. var pitch = Math.atan2(normal.y, len);
  27026. // Matrix
  27027. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  27028. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  27029. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  27030. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  27031. var vertexData = new BABYLON.VertexData();
  27032. vertexData.indices = [];
  27033. vertexData.positions = [];
  27034. vertexData.normals = [];
  27035. vertexData.uvs = [];
  27036. var currentVertexDataIndex = 0;
  27037. var extractDecalVector3 = function (indexId) {
  27038. var vertexId = indices[indexId];
  27039. var result = new BABYLON.PositionNormalVertex();
  27040. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  27041. // Send vector to decal local world
  27042. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  27043. // Get normal
  27044. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  27045. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  27046. return result;
  27047. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  27048. var clip = function (vertices, axis) {
  27049. if (vertices.length === 0) {
  27050. return vertices;
  27051. }
  27052. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  27053. var clipVertices = function (v0, v1) {
  27054. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  27055. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  27056. };
  27057. var result = new Array();
  27058. for (var index = 0; index < vertices.length; index += 3) {
  27059. var v1Out;
  27060. var v2Out;
  27061. var v3Out;
  27062. var total = 0;
  27063. var nV1, nV2, nV3, nV4;
  27064. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  27065. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  27066. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  27067. v1Out = d1 > 0;
  27068. v2Out = d2 > 0;
  27069. v3Out = d3 > 0;
  27070. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  27071. switch (total) {
  27072. case 0:
  27073. result.push(vertices[index]);
  27074. result.push(vertices[index + 1]);
  27075. result.push(vertices[index + 2]);
  27076. break;
  27077. case 1:
  27078. if (v1Out) {
  27079. nV1 = vertices[index + 1];
  27080. nV2 = vertices[index + 2];
  27081. nV3 = clipVertices(vertices[index], nV1);
  27082. nV4 = clipVertices(vertices[index], nV2);
  27083. }
  27084. if (v2Out) {
  27085. nV1 = vertices[index];
  27086. nV2 = vertices[index + 2];
  27087. nV3 = clipVertices(vertices[index + 1], nV1);
  27088. nV4 = clipVertices(vertices[index + 1], nV2);
  27089. result.push(nV3);
  27090. result.push(nV2.clone());
  27091. result.push(nV1.clone());
  27092. result.push(nV2.clone());
  27093. result.push(nV3.clone());
  27094. result.push(nV4);
  27095. break;
  27096. }
  27097. if (v3Out) {
  27098. nV1 = vertices[index];
  27099. nV2 = vertices[index + 1];
  27100. nV3 = clipVertices(vertices[index + 2], nV1);
  27101. nV4 = clipVertices(vertices[index + 2], nV2);
  27102. }
  27103. result.push(nV1.clone());
  27104. result.push(nV2.clone());
  27105. result.push(nV3);
  27106. result.push(nV4);
  27107. result.push(nV3.clone());
  27108. result.push(nV2.clone());
  27109. break;
  27110. case 2:
  27111. if (!v1Out) {
  27112. nV1 = vertices[index].clone();
  27113. nV2 = clipVertices(nV1, vertices[index + 1]);
  27114. nV3 = clipVertices(nV1, vertices[index + 2]);
  27115. result.push(nV1);
  27116. result.push(nV2);
  27117. result.push(nV3);
  27118. }
  27119. if (!v2Out) {
  27120. nV1 = vertices[index + 1].clone();
  27121. nV2 = clipVertices(nV1, vertices[index + 2]);
  27122. nV3 = clipVertices(nV1, vertices[index]);
  27123. result.push(nV1);
  27124. result.push(nV2);
  27125. result.push(nV3);
  27126. }
  27127. if (!v3Out) {
  27128. nV1 = vertices[index + 2].clone();
  27129. nV2 = clipVertices(nV1, vertices[index]);
  27130. nV3 = clipVertices(nV1, vertices[index + 1]);
  27131. result.push(nV1);
  27132. result.push(nV2);
  27133. result.push(nV3);
  27134. }
  27135. break;
  27136. case 3:
  27137. break;
  27138. }
  27139. }
  27140. return result;
  27141. };
  27142. for (var index = 0; index < indices.length; index += 3) {
  27143. var faceVertices = new Array();
  27144. faceVertices.push(extractDecalVector3(index));
  27145. faceVertices.push(extractDecalVector3(index + 1));
  27146. faceVertices.push(extractDecalVector3(index + 2));
  27147. // Clip
  27148. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  27149. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  27150. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  27151. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  27152. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  27153. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  27154. if (faceVertices.length === 0) {
  27155. continue;
  27156. }
  27157. // Add UVs and get back to world
  27158. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  27159. var vertex = faceVertices[vIndex];
  27160. //TODO check for Int32Array | Uint32Array | Uint16Array
  27161. vertexData.indices.push(currentVertexDataIndex);
  27162. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  27163. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  27164. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  27165. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  27166. currentVertexDataIndex++;
  27167. }
  27168. }
  27169. // Return mesh
  27170. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  27171. vertexData.applyToMesh(decal);
  27172. decal.position = position.clone();
  27173. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  27174. return decal;
  27175. };
  27176. // Privates
  27177. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  27178. // extrusion geometry
  27179. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  27180. var tangents = path3D.getTangents();
  27181. var normals = path3D.getNormals();
  27182. var binormals = path3D.getBinormals();
  27183. var distances = path3D.getDistances();
  27184. var angle = 0;
  27185. var returnScale = function () { return scale; };
  27186. var returnRotation = function () { return rotation; };
  27187. var rotate = custom ? rotateFunction : returnRotation;
  27188. var scl = custom ? scaleFunction : returnScale;
  27189. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  27190. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  27191. for (var i = 0; i < curve.length; i++) {
  27192. var shapePath = new Array();
  27193. var angleStep = rotate(i, distances[i]);
  27194. var scaleRatio = scl(i, distances[i]);
  27195. for (var p = 0; p < shape.length; p++) {
  27196. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  27197. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  27198. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  27199. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  27200. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  27201. shapePath[p] = rotated;
  27202. }
  27203. shapePaths[index] = shapePath;
  27204. angle += angleStep;
  27205. index++;
  27206. }
  27207. // cap
  27208. var capPath = function (shapePath) {
  27209. var pointCap = Array();
  27210. var barycenter = BABYLON.Vector3.Zero();
  27211. var i;
  27212. for (i = 0; i < shapePath.length; i++) {
  27213. barycenter.addInPlace(shapePath[i]);
  27214. }
  27215. barycenter.scaleInPlace(1.0 / shapePath.length);
  27216. for (i = 0; i < shapePath.length; i++) {
  27217. pointCap.push(barycenter);
  27218. }
  27219. return pointCap;
  27220. };
  27221. switch (cap) {
  27222. case BABYLON.Mesh.NO_CAP:
  27223. break;
  27224. case BABYLON.Mesh.CAP_START:
  27225. shapePaths[0] = capPath(shapePaths[2]);
  27226. shapePaths[1] = shapePaths[2];
  27227. break;
  27228. case BABYLON.Mesh.CAP_END:
  27229. shapePaths[index] = shapePaths[index - 1];
  27230. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  27231. break;
  27232. case BABYLON.Mesh.CAP_ALL:
  27233. shapePaths[0] = capPath(shapePaths[2]);
  27234. shapePaths[1] = shapePaths[2];
  27235. shapePaths[index] = shapePaths[index - 1];
  27236. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  27237. break;
  27238. default:
  27239. break;
  27240. }
  27241. return shapePaths;
  27242. };
  27243. var path3D;
  27244. var pathArray;
  27245. if (instance) {
  27246. path3D = (instance.path3D).update(curve);
  27247. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  27248. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  27249. return instance;
  27250. }
  27251. // extruded shape creation
  27252. path3D = new BABYLON.Path3D(curve);
  27253. var newShapePaths = new Array();
  27254. cap = (cap < 0 || cap > 3) ? 0 : cap;
  27255. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  27256. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  27257. extrudedGeneric.pathArray = pathArray;
  27258. extrudedGeneric.path3D = path3D;
  27259. extrudedGeneric.cap = cap;
  27260. return extrudedGeneric;
  27261. };
  27262. return MeshBuilder;
  27263. }());
  27264. BABYLON.MeshBuilder = MeshBuilder;
  27265. })(BABYLON || (BABYLON = {}));
  27266. //# sourceMappingURL=babylon.meshBuilder.js.map
  27267. var BABYLON;
  27268. (function (BABYLON) {
  27269. var BaseTexture = (function () {
  27270. function BaseTexture(scene) {
  27271. this._hasAlpha = false;
  27272. this.getAlphaFromRGB = false;
  27273. this.level = 1;
  27274. this.coordinatesIndex = 0;
  27275. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  27276. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27277. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27278. this.anisotropicFilteringLevel = 4;
  27279. this.isCube = false;
  27280. this.isRenderTarget = false;
  27281. this.animations = new Array();
  27282. /**
  27283. * An event triggered when the texture is disposed.
  27284. * @type {BABYLON.Observable}
  27285. */
  27286. this.onDisposeObservable = new BABYLON.Observable();
  27287. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27288. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27289. this._scene.textures.push(this);
  27290. this._uid = null;
  27291. }
  27292. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  27293. get: function () {
  27294. return this._hasAlpha;
  27295. },
  27296. set: function (value) {
  27297. if (this._hasAlpha === value) {
  27298. return;
  27299. }
  27300. this._hasAlpha = value;
  27301. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27302. },
  27303. enumerable: true,
  27304. configurable: true
  27305. });
  27306. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  27307. get: function () {
  27308. return this._coordinatesMode;
  27309. },
  27310. set: function (value) {
  27311. if (this._coordinatesMode === value) {
  27312. return;
  27313. }
  27314. this._coordinatesMode = value;
  27315. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27316. },
  27317. enumerable: true,
  27318. configurable: true
  27319. });
  27320. Object.defineProperty(BaseTexture.prototype, "uid", {
  27321. get: function () {
  27322. if (!this._uid) {
  27323. this._uid = BABYLON.Tools.RandomId();
  27324. }
  27325. return this._uid;
  27326. },
  27327. enumerable: true,
  27328. configurable: true
  27329. });
  27330. BaseTexture.prototype.toString = function () {
  27331. return this.name;
  27332. };
  27333. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  27334. set: function (callback) {
  27335. if (this._onDisposeObserver) {
  27336. this.onDisposeObservable.remove(this._onDisposeObserver);
  27337. }
  27338. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27339. },
  27340. enumerable: true,
  27341. configurable: true
  27342. });
  27343. BaseTexture.prototype.getScene = function () {
  27344. return this._scene;
  27345. };
  27346. BaseTexture.prototype.getTextureMatrix = function () {
  27347. return null;
  27348. };
  27349. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  27350. return null;
  27351. };
  27352. BaseTexture.prototype.getInternalTexture = function () {
  27353. return this._texture;
  27354. };
  27355. BaseTexture.prototype.isReady = function () {
  27356. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27357. return true;
  27358. }
  27359. if (this._texture) {
  27360. return this._texture.isReady;
  27361. }
  27362. return false;
  27363. };
  27364. BaseTexture.prototype.getSize = function () {
  27365. if (this._texture._width) {
  27366. return new BABYLON.Size(this._texture._width, this._texture._height);
  27367. }
  27368. if (this._texture._size) {
  27369. return new BABYLON.Size(this._texture._size, this._texture._size);
  27370. }
  27371. return BABYLON.Size.Zero();
  27372. };
  27373. BaseTexture.prototype.getBaseSize = function () {
  27374. if (!this.isReady() || !this._texture)
  27375. return BABYLON.Size.Zero();
  27376. if (this._texture._size) {
  27377. return new BABYLON.Size(this._texture._size, this._texture._size);
  27378. }
  27379. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  27380. };
  27381. BaseTexture.prototype.scale = function (ratio) {
  27382. };
  27383. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27384. get: function () {
  27385. return false;
  27386. },
  27387. enumerable: true,
  27388. configurable: true
  27389. });
  27390. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  27391. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27392. for (var index = 0; index < texturesCache.length; index++) {
  27393. var texturesCacheEntry = texturesCache[index];
  27394. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  27395. texturesCache.splice(index, 1);
  27396. return;
  27397. }
  27398. }
  27399. };
  27400. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27401. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27402. for (var index = 0; index < texturesCache.length; index++) {
  27403. var texturesCacheEntry = texturesCache[index];
  27404. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  27405. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27406. texturesCacheEntry.references++;
  27407. return texturesCacheEntry;
  27408. }
  27409. }
  27410. }
  27411. return null;
  27412. };
  27413. BaseTexture.prototype.delayLoad = function () {
  27414. };
  27415. BaseTexture.prototype.clone = function () {
  27416. return null;
  27417. };
  27418. BaseTexture.prototype.releaseInternalTexture = function () {
  27419. if (this._texture) {
  27420. this._scene.getEngine().releaseInternalTexture(this._texture);
  27421. delete this._texture;
  27422. }
  27423. };
  27424. BaseTexture.prototype.dispose = function () {
  27425. // Animations
  27426. this.getScene().stopAnimation(this);
  27427. // Remove from scene
  27428. this._scene._removePendingData(this);
  27429. var index = this._scene.textures.indexOf(this);
  27430. if (index >= 0) {
  27431. this._scene.textures.splice(index, 1);
  27432. }
  27433. if (this._texture === undefined) {
  27434. return;
  27435. }
  27436. // Release
  27437. this.releaseInternalTexture();
  27438. // Callback
  27439. this.onDisposeObservable.notifyObservers(this);
  27440. this.onDisposeObservable.clear();
  27441. };
  27442. BaseTexture.prototype.serialize = function () {
  27443. if (!this.name) {
  27444. return null;
  27445. }
  27446. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27447. // Animations
  27448. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27449. return serializationObject;
  27450. };
  27451. return BaseTexture;
  27452. }());
  27453. __decorate([
  27454. BABYLON.serialize()
  27455. ], BaseTexture.prototype, "name", void 0);
  27456. __decorate([
  27457. BABYLON.serialize("hasAlpha")
  27458. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27459. __decorate([
  27460. BABYLON.serialize()
  27461. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27462. __decorate([
  27463. BABYLON.serialize()
  27464. ], BaseTexture.prototype, "level", void 0);
  27465. __decorate([
  27466. BABYLON.serialize()
  27467. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27468. __decorate([
  27469. BABYLON.serialize("coordinatesMode")
  27470. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27471. __decorate([
  27472. BABYLON.serialize()
  27473. ], BaseTexture.prototype, "wrapU", void 0);
  27474. __decorate([
  27475. BABYLON.serialize()
  27476. ], BaseTexture.prototype, "wrapV", void 0);
  27477. __decorate([
  27478. BABYLON.serialize()
  27479. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27480. __decorate([
  27481. BABYLON.serialize()
  27482. ], BaseTexture.prototype, "isCube", void 0);
  27483. __decorate([
  27484. BABYLON.serialize()
  27485. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27486. BABYLON.BaseTexture = BaseTexture;
  27487. })(BABYLON || (BABYLON = {}));
  27488. //# sourceMappingURL=babylon.baseTexture.js.map
  27489. var BABYLON;
  27490. (function (BABYLON) {
  27491. var Texture = (function (_super) {
  27492. __extends(Texture, _super);
  27493. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27494. if (noMipmap === void 0) { noMipmap = false; }
  27495. if (invertY === void 0) { invertY = true; }
  27496. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27497. if (onLoad === void 0) { onLoad = null; }
  27498. if (onError === void 0) { onError = null; }
  27499. if (buffer === void 0) { buffer = null; }
  27500. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27501. var _this = _super.call(this, scene) || this;
  27502. _this.uOffset = 0;
  27503. _this.vOffset = 0;
  27504. _this.uScale = 1.0;
  27505. _this.vScale = 1.0;
  27506. _this.uAng = 0;
  27507. _this.vAng = 0;
  27508. _this.wAng = 0;
  27509. _this.name = url;
  27510. _this.url = url;
  27511. _this._noMipmap = noMipmap;
  27512. _this._invertY = invertY;
  27513. _this._samplingMode = samplingMode;
  27514. _this._buffer = buffer;
  27515. _this._deleteBuffer = deleteBuffer;
  27516. _this._format = format;
  27517. if (!url) {
  27518. return _this;
  27519. }
  27520. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  27521. var load = function () {
  27522. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  27523. _this.onLoadObservable.notifyObservers(true);
  27524. }
  27525. if (onLoad) {
  27526. onLoad();
  27527. }
  27528. };
  27529. if (!_this._texture) {
  27530. if (!scene.useDelayedTextureLoading) {
  27531. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  27532. if (deleteBuffer) {
  27533. delete _this._buffer;
  27534. }
  27535. }
  27536. else {
  27537. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27538. _this._delayedOnLoad = load;
  27539. _this._delayedOnError = onError;
  27540. }
  27541. }
  27542. else {
  27543. if (_this._texture.isReady) {
  27544. BABYLON.Tools.SetImmediate(function () { return load(); });
  27545. }
  27546. else {
  27547. _this._texture.onLoadedCallbacks.push(load);
  27548. }
  27549. }
  27550. return _this;
  27551. }
  27552. Object.defineProperty(Texture.prototype, "noMipmap", {
  27553. get: function () {
  27554. return this._noMipmap;
  27555. },
  27556. enumerable: true,
  27557. configurable: true
  27558. });
  27559. Texture.prototype.delayLoad = function () {
  27560. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27561. return;
  27562. }
  27563. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27564. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27565. if (!this._texture) {
  27566. 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);
  27567. if (this._deleteBuffer) {
  27568. delete this._buffer;
  27569. }
  27570. }
  27571. };
  27572. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27573. if (!this._texture) {
  27574. return;
  27575. }
  27576. this._samplingMode = samplingMode;
  27577. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27578. };
  27579. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27580. x *= this.uScale;
  27581. y *= this.vScale;
  27582. x -= 0.5 * this.uScale;
  27583. y -= 0.5 * this.vScale;
  27584. z -= 0.5;
  27585. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27586. t.x += 0.5 * this.uScale + this.uOffset;
  27587. t.y += 0.5 * this.vScale + this.vOffset;
  27588. t.z += 0.5;
  27589. };
  27590. Texture.prototype.getTextureMatrix = function () {
  27591. if (this.uOffset === this._cachedUOffset &&
  27592. this.vOffset === this._cachedVOffset &&
  27593. this.uScale === this._cachedUScale &&
  27594. this.vScale === this._cachedVScale &&
  27595. this.uAng === this._cachedUAng &&
  27596. this.vAng === this._cachedVAng &&
  27597. this.wAng === this._cachedWAng) {
  27598. return this._cachedTextureMatrix;
  27599. }
  27600. this._cachedUOffset = this.uOffset;
  27601. this._cachedVOffset = this.vOffset;
  27602. this._cachedUScale = this.uScale;
  27603. this._cachedVScale = this.vScale;
  27604. this._cachedUAng = this.uAng;
  27605. this._cachedVAng = this.vAng;
  27606. this._cachedWAng = this.wAng;
  27607. if (!this._cachedTextureMatrix) {
  27608. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27609. this._rowGenerationMatrix = new BABYLON.Matrix();
  27610. this._t0 = BABYLON.Vector3.Zero();
  27611. this._t1 = BABYLON.Vector3.Zero();
  27612. this._t2 = BABYLON.Vector3.Zero();
  27613. }
  27614. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27615. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27616. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27617. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27618. this._t1.subtractInPlace(this._t0);
  27619. this._t2.subtractInPlace(this._t0);
  27620. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27621. this._cachedTextureMatrix.m[0] = this._t1.x;
  27622. this._cachedTextureMatrix.m[1] = this._t1.y;
  27623. this._cachedTextureMatrix.m[2] = this._t1.z;
  27624. this._cachedTextureMatrix.m[4] = this._t2.x;
  27625. this._cachedTextureMatrix.m[5] = this._t2.y;
  27626. this._cachedTextureMatrix.m[6] = this._t2.z;
  27627. this._cachedTextureMatrix.m[8] = this._t0.x;
  27628. this._cachedTextureMatrix.m[9] = this._t0.y;
  27629. this._cachedTextureMatrix.m[10] = this._t0.z;
  27630. return this._cachedTextureMatrix;
  27631. };
  27632. Texture.prototype.getReflectionTextureMatrix = function () {
  27633. if (this.uOffset === this._cachedUOffset &&
  27634. this.vOffset === this._cachedVOffset &&
  27635. this.uScale === this._cachedUScale &&
  27636. this.vScale === this._cachedVScale &&
  27637. this.coordinatesMode === this._cachedCoordinatesMode) {
  27638. return this._cachedTextureMatrix;
  27639. }
  27640. if (!this._cachedTextureMatrix) {
  27641. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27642. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27643. }
  27644. this._cachedCoordinatesMode = this.coordinatesMode;
  27645. switch (this.coordinatesMode) {
  27646. case Texture.PLANAR_MODE:
  27647. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27648. this._cachedTextureMatrix[0] = this.uScale;
  27649. this._cachedTextureMatrix[5] = this.vScale;
  27650. this._cachedTextureMatrix[12] = this.uOffset;
  27651. this._cachedTextureMatrix[13] = this.vOffset;
  27652. break;
  27653. case Texture.PROJECTION_MODE:
  27654. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27655. this._projectionModeMatrix.m[0] = 0.5;
  27656. this._projectionModeMatrix.m[5] = -0.5;
  27657. this._projectionModeMatrix.m[10] = 0.0;
  27658. this._projectionModeMatrix.m[12] = 0.5;
  27659. this._projectionModeMatrix.m[13] = 0.5;
  27660. this._projectionModeMatrix.m[14] = 1.0;
  27661. this._projectionModeMatrix.m[15] = 1.0;
  27662. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27663. break;
  27664. default:
  27665. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27666. break;
  27667. }
  27668. return this._cachedTextureMatrix;
  27669. };
  27670. Texture.prototype.clone = function () {
  27671. var _this = this;
  27672. return BABYLON.SerializationHelper.Clone(function () {
  27673. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27674. }, this);
  27675. };
  27676. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27677. get: function () {
  27678. if (!this._onLoadObservarble) {
  27679. this._onLoadObservarble = new BABYLON.Observable();
  27680. }
  27681. return this._onLoadObservarble;
  27682. },
  27683. enumerable: true,
  27684. configurable: true
  27685. });
  27686. // Statics
  27687. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27688. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27689. if (onLoad === void 0) { onLoad = null; }
  27690. if (onError === void 0) { onError = null; }
  27691. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27692. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27693. };
  27694. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27695. if (parsedTexture.customType) {
  27696. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27697. return customTexture.Parse(parsedTexture, scene, rootUrl);
  27698. }
  27699. if (parsedTexture.isCube) {
  27700. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27701. }
  27702. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27703. return null;
  27704. }
  27705. var texture = BABYLON.SerializationHelper.Parse(function () {
  27706. if (parsedTexture.mirrorPlane) {
  27707. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  27708. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27709. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27710. return mirrorTexture;
  27711. }
  27712. else if (parsedTexture.isRenderTarget) {
  27713. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  27714. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27715. return renderTargetTexture;
  27716. }
  27717. else {
  27718. var texture;
  27719. if (parsedTexture.base64String) {
  27720. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  27721. }
  27722. else {
  27723. texture = new Texture(rootUrl + parsedTexture.name, scene);
  27724. }
  27725. return texture;
  27726. }
  27727. }, parsedTexture, scene);
  27728. // Animations
  27729. if (parsedTexture.animations) {
  27730. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27731. var parsedAnimation = parsedTexture.animations[animationIndex];
  27732. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27733. }
  27734. }
  27735. return texture;
  27736. };
  27737. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27738. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27739. if (noMipmap === void 0) { noMipmap = false; }
  27740. if (invertY === void 0) { invertY = true; }
  27741. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27742. if (onLoad === void 0) { onLoad = null; }
  27743. if (onError === void 0) { onError = null; }
  27744. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27745. if (name.substr(0, 5) !== "data:") {
  27746. name = "data:" + name;
  27747. }
  27748. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27749. };
  27750. return Texture;
  27751. }(BABYLON.BaseTexture));
  27752. // Constants
  27753. Texture.NEAREST_SAMPLINGMODE = 1;
  27754. Texture.BILINEAR_SAMPLINGMODE = 2;
  27755. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27756. Texture.EXPLICIT_MODE = 0;
  27757. Texture.SPHERICAL_MODE = 1;
  27758. Texture.PLANAR_MODE = 2;
  27759. Texture.CUBIC_MODE = 3;
  27760. Texture.PROJECTION_MODE = 4;
  27761. Texture.SKYBOX_MODE = 5;
  27762. Texture.INVCUBIC_MODE = 6;
  27763. Texture.EQUIRECTANGULAR_MODE = 7;
  27764. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27765. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27766. Texture.CLAMP_ADDRESSMODE = 0;
  27767. Texture.WRAP_ADDRESSMODE = 1;
  27768. Texture.MIRROR_ADDRESSMODE = 2;
  27769. __decorate([
  27770. BABYLON.serialize()
  27771. ], Texture.prototype, "url", void 0);
  27772. __decorate([
  27773. BABYLON.serialize()
  27774. ], Texture.prototype, "uOffset", void 0);
  27775. __decorate([
  27776. BABYLON.serialize()
  27777. ], Texture.prototype, "vOffset", void 0);
  27778. __decorate([
  27779. BABYLON.serialize()
  27780. ], Texture.prototype, "uScale", void 0);
  27781. __decorate([
  27782. BABYLON.serialize()
  27783. ], Texture.prototype, "vScale", void 0);
  27784. __decorate([
  27785. BABYLON.serialize()
  27786. ], Texture.prototype, "uAng", void 0);
  27787. __decorate([
  27788. BABYLON.serialize()
  27789. ], Texture.prototype, "vAng", void 0);
  27790. __decorate([
  27791. BABYLON.serialize()
  27792. ], Texture.prototype, "wAng", void 0);
  27793. BABYLON.Texture = Texture;
  27794. })(BABYLON || (BABYLON = {}));
  27795. //# sourceMappingURL=babylon.texture.js.map
  27796. var BABYLON;
  27797. (function (BABYLON) {
  27798. var CubeTexture = (function (_super) {
  27799. __extends(CubeTexture, _super);
  27800. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  27801. if (onLoad === void 0) { onLoad = null; }
  27802. if (onError === void 0) { onError = null; }
  27803. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27804. var _this = _super.call(this, scene) || this;
  27805. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  27806. _this.name = rootUrl;
  27807. _this.url = rootUrl;
  27808. _this._noMipmap = noMipmap;
  27809. _this.hasAlpha = false;
  27810. _this._format = format;
  27811. if (!rootUrl && !files) {
  27812. return _this;
  27813. }
  27814. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  27815. if (!files) {
  27816. if (!extensions) {
  27817. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  27818. }
  27819. files = [];
  27820. for (var index = 0; index < extensions.length; index++) {
  27821. files.push(rootUrl + extensions[index]);
  27822. }
  27823. _this._extensions = extensions;
  27824. }
  27825. _this._files = files;
  27826. if (!_this._texture) {
  27827. if (!scene.useDelayedTextureLoading) {
  27828. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  27829. }
  27830. else {
  27831. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27832. }
  27833. }
  27834. else if (onLoad) {
  27835. if (_this._texture.isReady) {
  27836. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  27837. }
  27838. else {
  27839. _this._texture.onLoadedCallbacks.push(onLoad);
  27840. }
  27841. }
  27842. _this.isCube = true;
  27843. _this._textureMatrix = BABYLON.Matrix.Identity();
  27844. return _this;
  27845. }
  27846. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  27847. return new CubeTexture("", scene, null, noMipmap, files);
  27848. };
  27849. // Methods
  27850. CubeTexture.prototype.delayLoad = function () {
  27851. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27852. return;
  27853. }
  27854. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27855. this._texture = this._getFromCache(this.url, this._noMipmap);
  27856. if (!this._texture) {
  27857. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  27858. }
  27859. };
  27860. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  27861. return this._textureMatrix;
  27862. };
  27863. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  27864. var texture = BABYLON.SerializationHelper.Parse(function () {
  27865. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  27866. }, parsedTexture, scene);
  27867. // Animations
  27868. if (parsedTexture.animations) {
  27869. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27870. var parsedAnimation = parsedTexture.animations[animationIndex];
  27871. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27872. }
  27873. }
  27874. return texture;
  27875. };
  27876. CubeTexture.prototype.clone = function () {
  27877. var _this = this;
  27878. return BABYLON.SerializationHelper.Clone(function () {
  27879. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  27880. }, this);
  27881. };
  27882. return CubeTexture;
  27883. }(BABYLON.BaseTexture));
  27884. BABYLON.CubeTexture = CubeTexture;
  27885. })(BABYLON || (BABYLON = {}));
  27886. //# sourceMappingURL=babylon.cubeTexture.js.map
  27887. var BABYLON;
  27888. (function (BABYLON) {
  27889. var RenderTargetTexture = (function (_super) {
  27890. __extends(RenderTargetTexture, _super);
  27891. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  27892. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  27893. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  27894. if (isCube === void 0) { isCube = false; }
  27895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27896. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  27897. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  27898. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  27899. _this.isCube = isCube;
  27900. /**
  27901. * Use this list to define the list of mesh you want to render.
  27902. */
  27903. _this.renderList = new Array();
  27904. _this.renderParticles = true;
  27905. _this.renderSprites = false;
  27906. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  27907. // Events
  27908. /**
  27909. * An event triggered when the texture is unbind.
  27910. * @type {BABYLON.Observable}
  27911. */
  27912. _this.onAfterUnbindObservable = new BABYLON.Observable();
  27913. /**
  27914. * An event triggered before rendering the texture
  27915. * @type {BABYLON.Observable}
  27916. */
  27917. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27918. /**
  27919. * An event triggered after rendering the texture
  27920. * @type {BABYLON.Observable}
  27921. */
  27922. _this.onAfterRenderObservable = new BABYLON.Observable();
  27923. /**
  27924. * An event triggered after the texture clear
  27925. * @type {BABYLON.Observable}
  27926. */
  27927. _this.onClearObservable = new BABYLON.Observable();
  27928. _this._currentRefreshId = -1;
  27929. _this._refreshRate = 1;
  27930. _this._samples = 1;
  27931. _this.name = name;
  27932. _this.isRenderTarget = true;
  27933. _this._size = size;
  27934. _this._generateMipMaps = generateMipMaps;
  27935. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  27936. _this._renderTargetOptions = {
  27937. generateMipMaps: generateMipMaps,
  27938. type: type,
  27939. samplingMode: samplingMode,
  27940. generateDepthBuffer: generateDepthBuffer,
  27941. generateStencilBuffer: generateStencilBuffer
  27942. };
  27943. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  27944. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27945. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27946. }
  27947. if (isCube) {
  27948. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  27949. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  27950. _this._textureMatrix = BABYLON.Matrix.Identity();
  27951. }
  27952. else {
  27953. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  27954. }
  27955. // Rendering groups
  27956. _this._renderingManager = new BABYLON.RenderingManager(scene);
  27957. return _this;
  27958. }
  27959. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  27960. get: function () {
  27961. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  27962. },
  27963. enumerable: true,
  27964. configurable: true
  27965. });
  27966. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  27967. get: function () {
  27968. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  27969. },
  27970. enumerable: true,
  27971. configurable: true
  27972. });
  27973. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  27974. get: function () {
  27975. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  27976. },
  27977. enumerable: true,
  27978. configurable: true
  27979. });
  27980. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  27981. set: function (callback) {
  27982. if (this._onAfterUnbindObserver) {
  27983. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  27984. }
  27985. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  27986. },
  27987. enumerable: true,
  27988. configurable: true
  27989. });
  27990. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  27991. set: function (callback) {
  27992. if (this._onBeforeRenderObserver) {
  27993. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27994. }
  27995. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27996. },
  27997. enumerable: true,
  27998. configurable: true
  27999. });
  28000. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  28001. set: function (callback) {
  28002. if (this._onAfterRenderObserver) {
  28003. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28004. }
  28005. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28006. },
  28007. enumerable: true,
  28008. configurable: true
  28009. });
  28010. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  28011. set: function (callback) {
  28012. if (this._onClearObserver) {
  28013. this.onClearObservable.remove(this._onClearObserver);
  28014. }
  28015. this._onClearObserver = this.onClearObservable.add(callback);
  28016. },
  28017. enumerable: true,
  28018. configurable: true
  28019. });
  28020. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  28021. get: function () {
  28022. return this._samples;
  28023. },
  28024. set: function (value) {
  28025. if (this._samples === value) {
  28026. return;
  28027. }
  28028. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  28029. },
  28030. enumerable: true,
  28031. configurable: true
  28032. });
  28033. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  28034. this._currentRefreshId = -1;
  28035. };
  28036. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  28037. get: function () {
  28038. return this._refreshRate;
  28039. },
  28040. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  28041. set: function (value) {
  28042. this._refreshRate = value;
  28043. this.resetRefreshCounter();
  28044. },
  28045. enumerable: true,
  28046. configurable: true
  28047. });
  28048. RenderTargetTexture.prototype._shouldRender = function () {
  28049. if (this._currentRefreshId === -1) {
  28050. this._currentRefreshId = 1;
  28051. return true;
  28052. }
  28053. if (this.refreshRate === this._currentRefreshId) {
  28054. this._currentRefreshId = 1;
  28055. return true;
  28056. }
  28057. this._currentRefreshId++;
  28058. return false;
  28059. };
  28060. RenderTargetTexture.prototype.isReady = function () {
  28061. if (!this.getScene().renderTargetsEnabled) {
  28062. return false;
  28063. }
  28064. return _super.prototype.isReady.call(this);
  28065. };
  28066. RenderTargetTexture.prototype.getRenderSize = function () {
  28067. return this._size;
  28068. };
  28069. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  28070. get: function () {
  28071. return true;
  28072. },
  28073. enumerable: true,
  28074. configurable: true
  28075. });
  28076. RenderTargetTexture.prototype.scale = function (ratio) {
  28077. var newSize = this._size * ratio;
  28078. this.resize(newSize);
  28079. };
  28080. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  28081. if (this.isCube) {
  28082. return this._textureMatrix;
  28083. }
  28084. return _super.prototype.getReflectionTextureMatrix.call(this);
  28085. };
  28086. RenderTargetTexture.prototype.resize = function (size) {
  28087. this.releaseInternalTexture();
  28088. if (this.isCube) {
  28089. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  28090. }
  28091. else {
  28092. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  28093. }
  28094. };
  28095. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  28096. var scene = this.getScene();
  28097. var engine = scene.getEngine();
  28098. if (this.useCameraPostProcesses !== undefined) {
  28099. useCameraPostProcess = this.useCameraPostProcesses;
  28100. }
  28101. if (this._waitingRenderList) {
  28102. this.renderList = [];
  28103. for (var index = 0; index < this._waitingRenderList.length; index++) {
  28104. var id = this._waitingRenderList[index];
  28105. this.renderList.push(scene.getMeshByID(id));
  28106. }
  28107. delete this._waitingRenderList;
  28108. }
  28109. // Is predicate defined?
  28110. if (this.renderListPredicate) {
  28111. this.renderList.splice(0); // Clear previous renderList
  28112. var sceneMeshes = this.getScene().meshes;
  28113. for (var index = 0; index < sceneMeshes.length; index++) {
  28114. var mesh = sceneMeshes[index];
  28115. if (this.renderListPredicate(mesh)) {
  28116. this.renderList.push(mesh);
  28117. }
  28118. }
  28119. }
  28120. if (this.renderList && this.renderList.length === 0) {
  28121. return;
  28122. }
  28123. // Set custom projection.
  28124. // Needs to be before binding to prevent changing the aspect ratio.
  28125. if (this.activeCamera) {
  28126. engine.setViewport(this.activeCamera.viewport);
  28127. if (this.activeCamera !== scene.activeCamera) {
  28128. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  28129. }
  28130. }
  28131. else {
  28132. engine.setViewport(scene.activeCamera.viewport);
  28133. }
  28134. // Prepare renderingManager
  28135. this._renderingManager.reset();
  28136. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  28137. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  28138. var sceneRenderId = scene.getRenderId();
  28139. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  28140. var mesh = currentRenderList[meshIndex];
  28141. if (mesh) {
  28142. if (!mesh.isReady()) {
  28143. // Reset _currentRefreshId
  28144. this.resetRefreshCounter();
  28145. continue;
  28146. }
  28147. mesh._preActivateForIntermediateRendering(sceneRenderId);
  28148. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  28149. mesh._activate(sceneRenderId);
  28150. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28151. var subMesh = mesh.subMeshes[subIndex];
  28152. scene._activeIndices.addCount(subMesh.indexCount, false);
  28153. this._renderingManager.dispatch(subMesh);
  28154. }
  28155. }
  28156. }
  28157. }
  28158. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  28159. var particleSystem = scene.particleSystems[particleIndex];
  28160. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  28161. continue;
  28162. }
  28163. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  28164. this._renderingManager.dispatchParticles(particleSystem);
  28165. }
  28166. }
  28167. if (this.isCube) {
  28168. for (var face = 0; face < 6; face++) {
  28169. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  28170. scene.incrementRenderId();
  28171. scene.resetCachedMaterial();
  28172. }
  28173. }
  28174. else {
  28175. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  28176. }
  28177. this.onAfterUnbindObservable.notifyObservers(this);
  28178. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  28179. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  28180. }
  28181. engine.setViewport(scene.activeCamera.viewport);
  28182. scene.resetCachedMaterial();
  28183. };
  28184. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  28185. var _this = this;
  28186. var scene = this.getScene();
  28187. var engine = scene.getEngine();
  28188. // Bind
  28189. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  28190. if (this.isCube) {
  28191. engine.bindFramebuffer(this._texture, faceIndex);
  28192. }
  28193. else {
  28194. engine.bindFramebuffer(this._texture);
  28195. }
  28196. }
  28197. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  28198. // Clear
  28199. if (this.onClearObservable.hasObservers()) {
  28200. this.onClearObservable.notifyObservers(engine);
  28201. }
  28202. else {
  28203. engine.clear(scene.clearColor, true, true, true);
  28204. }
  28205. if (!this._doNotChangeAspectRatio) {
  28206. scene.updateTransformMatrix(true);
  28207. }
  28208. // Render
  28209. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  28210. if (useCameraPostProcess) {
  28211. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  28212. }
  28213. if (!this._doNotChangeAspectRatio) {
  28214. scene.updateTransformMatrix(true);
  28215. }
  28216. // Dump ?
  28217. if (dumpForDebug) {
  28218. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  28219. }
  28220. // Unbind
  28221. if (!this.isCube || faceIndex === 5) {
  28222. if (this.isCube) {
  28223. if (faceIndex === 5) {
  28224. engine.generateMipMapsForCubemap(this._texture);
  28225. }
  28226. }
  28227. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  28228. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  28229. });
  28230. }
  28231. else {
  28232. this.onAfterRenderObservable.notifyObservers(faceIndex);
  28233. }
  28234. };
  28235. /**
  28236. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28237. * This allowed control for front to back rendering or reversly depending of the special needs.
  28238. *
  28239. * @param renderingGroupId The rendering group id corresponding to its index
  28240. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28241. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28242. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28243. */
  28244. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28245. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28246. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28247. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28248. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28249. };
  28250. /**
  28251. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28252. *
  28253. * @param renderingGroupId The rendering group id corresponding to its index
  28254. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28255. */
  28256. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  28257. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  28258. };
  28259. RenderTargetTexture.prototype.clone = function () {
  28260. var textureSize = this.getSize();
  28261. 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);
  28262. // Base texture
  28263. newTexture.hasAlpha = this.hasAlpha;
  28264. newTexture.level = this.level;
  28265. // RenderTarget Texture
  28266. newTexture.coordinatesMode = this.coordinatesMode;
  28267. newTexture.renderList = this.renderList.slice(0);
  28268. return newTexture;
  28269. };
  28270. RenderTargetTexture.prototype.serialize = function () {
  28271. if (!this.name) {
  28272. return null;
  28273. }
  28274. var serializationObject = _super.prototype.serialize.call(this);
  28275. serializationObject.renderTargetSize = this.getRenderSize();
  28276. serializationObject.renderList = [];
  28277. for (var index = 0; index < this.renderList.length; index++) {
  28278. serializationObject.renderList.push(this.renderList[index].id);
  28279. }
  28280. return serializationObject;
  28281. };
  28282. return RenderTargetTexture;
  28283. }(BABYLON.Texture));
  28284. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  28285. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  28286. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  28287. BABYLON.RenderTargetTexture = RenderTargetTexture;
  28288. })(BABYLON || (BABYLON = {}));
  28289. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  28290. var BABYLON;
  28291. (function (BABYLON) {
  28292. var ProceduralTexture = (function (_super) {
  28293. __extends(ProceduralTexture, _super);
  28294. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  28295. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28296. if (isCube === void 0) { isCube = false; }
  28297. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  28298. _this.isCube = isCube;
  28299. _this.isEnabled = true;
  28300. _this._currentRefreshId = -1;
  28301. _this._refreshRate = 1;
  28302. _this._vertexBuffers = {};
  28303. _this._uniforms = new Array();
  28304. _this._samplers = new Array();
  28305. _this._textures = new Array();
  28306. _this._floats = new Array();
  28307. _this._floatsArrays = {};
  28308. _this._colors3 = new Array();
  28309. _this._colors4 = new Array();
  28310. _this._vectors2 = new Array();
  28311. _this._vectors3 = new Array();
  28312. _this._matrices = new Array();
  28313. _this._fallbackTextureUsed = false;
  28314. scene._proceduralTextures.push(_this);
  28315. _this.name = name;
  28316. _this.isRenderTarget = true;
  28317. _this._size = size;
  28318. _this._generateMipMaps = generateMipMaps;
  28319. _this.setFragment(fragment);
  28320. _this._fallbackTexture = fallbackTexture;
  28321. var engine = scene.getEngine();
  28322. if (isCube) {
  28323. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  28324. _this.setFloat("face", 0);
  28325. }
  28326. else {
  28327. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  28328. }
  28329. // VBO
  28330. var vertices = [];
  28331. vertices.push(1, 1);
  28332. vertices.push(-1, 1);
  28333. vertices.push(-1, -1);
  28334. vertices.push(1, -1);
  28335. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28336. // Indices
  28337. var indices = [];
  28338. indices.push(0);
  28339. indices.push(1);
  28340. indices.push(2);
  28341. indices.push(0);
  28342. indices.push(2);
  28343. indices.push(3);
  28344. _this._indexBuffer = engine.createIndexBuffer(indices);
  28345. return _this;
  28346. }
  28347. ProceduralTexture.prototype.reset = function () {
  28348. if (this._effect === undefined) {
  28349. return;
  28350. }
  28351. var engine = this.getScene().getEngine();
  28352. engine._releaseEffect(this._effect);
  28353. };
  28354. ProceduralTexture.prototype.isReady = function () {
  28355. var _this = this;
  28356. var engine = this.getScene().getEngine();
  28357. var shaders;
  28358. if (!this._fragment) {
  28359. return false;
  28360. }
  28361. if (this._fallbackTextureUsed) {
  28362. return true;
  28363. }
  28364. if (this._fragment.fragmentElement !== undefined) {
  28365. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  28366. }
  28367. else {
  28368. shaders = { vertex: "procedural", fragment: this._fragment };
  28369. }
  28370. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  28371. _this.releaseInternalTexture();
  28372. if (_this._fallbackTexture) {
  28373. _this._texture = _this._fallbackTexture._texture;
  28374. _this._texture.references++;
  28375. }
  28376. _this._fallbackTextureUsed = true;
  28377. });
  28378. return this._effect.isReady();
  28379. };
  28380. ProceduralTexture.prototype.resetRefreshCounter = function () {
  28381. this._currentRefreshId = -1;
  28382. };
  28383. ProceduralTexture.prototype.setFragment = function (fragment) {
  28384. this._fragment = fragment;
  28385. };
  28386. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  28387. get: function () {
  28388. return this._refreshRate;
  28389. },
  28390. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  28391. set: function (value) {
  28392. this._refreshRate = value;
  28393. this.resetRefreshCounter();
  28394. },
  28395. enumerable: true,
  28396. configurable: true
  28397. });
  28398. ProceduralTexture.prototype._shouldRender = function () {
  28399. if (!this.isEnabled || !this.isReady() || !this._texture) {
  28400. return false;
  28401. }
  28402. if (this._fallbackTextureUsed) {
  28403. return false;
  28404. }
  28405. if (this._currentRefreshId === -1) {
  28406. this._currentRefreshId = 1;
  28407. return true;
  28408. }
  28409. if (this.refreshRate === this._currentRefreshId) {
  28410. this._currentRefreshId = 1;
  28411. return true;
  28412. }
  28413. this._currentRefreshId++;
  28414. return false;
  28415. };
  28416. ProceduralTexture.prototype.getRenderSize = function () {
  28417. return this._size;
  28418. };
  28419. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  28420. if (this._fallbackTextureUsed) {
  28421. return;
  28422. }
  28423. this.releaseInternalTexture();
  28424. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  28425. };
  28426. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  28427. if (this._uniforms.indexOf(uniformName) === -1) {
  28428. this._uniforms.push(uniformName);
  28429. }
  28430. };
  28431. ProceduralTexture.prototype.setTexture = function (name, texture) {
  28432. if (this._samplers.indexOf(name) === -1) {
  28433. this._samplers.push(name);
  28434. }
  28435. this._textures[name] = texture;
  28436. return this;
  28437. };
  28438. ProceduralTexture.prototype.setFloat = function (name, value) {
  28439. this._checkUniform(name);
  28440. this._floats[name] = value;
  28441. return this;
  28442. };
  28443. ProceduralTexture.prototype.setFloats = function (name, value) {
  28444. this._checkUniform(name);
  28445. this._floatsArrays[name] = value;
  28446. return this;
  28447. };
  28448. ProceduralTexture.prototype.setColor3 = function (name, value) {
  28449. this._checkUniform(name);
  28450. this._colors3[name] = value;
  28451. return this;
  28452. };
  28453. ProceduralTexture.prototype.setColor4 = function (name, value) {
  28454. this._checkUniform(name);
  28455. this._colors4[name] = value;
  28456. return this;
  28457. };
  28458. ProceduralTexture.prototype.setVector2 = function (name, value) {
  28459. this._checkUniform(name);
  28460. this._vectors2[name] = value;
  28461. return this;
  28462. };
  28463. ProceduralTexture.prototype.setVector3 = function (name, value) {
  28464. this._checkUniform(name);
  28465. this._vectors3[name] = value;
  28466. return this;
  28467. };
  28468. ProceduralTexture.prototype.setMatrix = function (name, value) {
  28469. this._checkUniform(name);
  28470. this._matrices[name] = value;
  28471. return this;
  28472. };
  28473. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  28474. var scene = this.getScene();
  28475. var engine = scene.getEngine();
  28476. // Render
  28477. engine.enableEffect(this._effect);
  28478. engine.setState(false);
  28479. // Texture
  28480. for (var name in this._textures) {
  28481. this._effect.setTexture(name, this._textures[name]);
  28482. }
  28483. // Float
  28484. for (name in this._floats) {
  28485. this._effect.setFloat(name, this._floats[name]);
  28486. }
  28487. // Floats
  28488. for (name in this._floatsArrays) {
  28489. this._effect.setArray(name, this._floatsArrays[name]);
  28490. }
  28491. // Color3
  28492. for (name in this._colors3) {
  28493. this._effect.setColor3(name, this._colors3[name]);
  28494. }
  28495. // Color4
  28496. for (name in this._colors4) {
  28497. var color = this._colors4[name];
  28498. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28499. }
  28500. // Vector2
  28501. for (name in this._vectors2) {
  28502. this._effect.setVector2(name, this._vectors2[name]);
  28503. }
  28504. // Vector3
  28505. for (name in this._vectors3) {
  28506. this._effect.setVector3(name, this._vectors3[name]);
  28507. }
  28508. // Matrix
  28509. for (name in this._matrices) {
  28510. this._effect.setMatrix(name, this._matrices[name]);
  28511. }
  28512. if (this.isCube) {
  28513. for (var face = 0; face < 6; face++) {
  28514. engine.bindFramebuffer(this._texture, face);
  28515. // VBOs
  28516. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  28517. this._effect.setFloat("face", face);
  28518. // Clear
  28519. engine.clear(scene.clearColor, true, true, true);
  28520. // Draw order
  28521. engine.draw(true, 0, 6);
  28522. // Mipmaps
  28523. if (face === 5) {
  28524. engine.generateMipMapsForCubemap(this._texture);
  28525. }
  28526. }
  28527. }
  28528. else {
  28529. engine.bindFramebuffer(this._texture);
  28530. // VBOs
  28531. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  28532. // Clear
  28533. engine.clear(scene.clearColor, true, true, true);
  28534. // Draw order
  28535. engine.draw(true, 0, 6);
  28536. }
  28537. // Unbind
  28538. engine.unBindFramebuffer(this._texture, this.isCube);
  28539. if (this.onGenerated) {
  28540. this.onGenerated();
  28541. }
  28542. };
  28543. ProceduralTexture.prototype.clone = function () {
  28544. var textureSize = this.getSize();
  28545. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  28546. // Base texture
  28547. newTexture.hasAlpha = this.hasAlpha;
  28548. newTexture.level = this.level;
  28549. // RenderTarget Texture
  28550. newTexture.coordinatesMode = this.coordinatesMode;
  28551. return newTexture;
  28552. };
  28553. ProceduralTexture.prototype.dispose = function () {
  28554. var index = this.getScene()._proceduralTextures.indexOf(this);
  28555. if (index >= 0) {
  28556. this.getScene()._proceduralTextures.splice(index, 1);
  28557. }
  28558. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28559. if (vertexBuffer) {
  28560. vertexBuffer.dispose();
  28561. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28562. }
  28563. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  28564. this._indexBuffer = null;
  28565. }
  28566. _super.prototype.dispose.call(this);
  28567. };
  28568. return ProceduralTexture;
  28569. }(BABYLON.Texture));
  28570. BABYLON.ProceduralTexture = ProceduralTexture;
  28571. })(BABYLON || (BABYLON = {}));
  28572. //# sourceMappingURL=babylon.proceduralTexture.js.map
  28573. /// <reference path="babylon.renderTargetTexture.ts" />
  28574. var BABYLON;
  28575. (function (BABYLON) {
  28576. var MirrorTexture = (function (_super) {
  28577. __extends(MirrorTexture, _super);
  28578. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  28579. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28580. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28581. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  28582. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  28583. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  28584. _this._transformMatrix = BABYLON.Matrix.Zero();
  28585. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  28586. _this.onBeforeRenderObservable.add(function () {
  28587. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  28588. _this._savedViewMatrix = scene.getViewMatrix();
  28589. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  28590. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  28591. scene.clipPlane = _this.mirrorPlane;
  28592. scene.getEngine().cullBackFaces = false;
  28593. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  28594. });
  28595. _this.onAfterRenderObservable.add(function () {
  28596. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  28597. scene.getEngine().cullBackFaces = true;
  28598. scene._mirroredCameraPosition = null;
  28599. delete scene.clipPlane;
  28600. });
  28601. return _this;
  28602. }
  28603. MirrorTexture.prototype.clone = function () {
  28604. var textureSize = this.getSize();
  28605. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  28606. // Base texture
  28607. newTexture.hasAlpha = this.hasAlpha;
  28608. newTexture.level = this.level;
  28609. // Mirror Texture
  28610. newTexture.mirrorPlane = this.mirrorPlane.clone();
  28611. newTexture.renderList = this.renderList.slice(0);
  28612. return newTexture;
  28613. };
  28614. MirrorTexture.prototype.serialize = function () {
  28615. if (!this.name) {
  28616. return null;
  28617. }
  28618. var serializationObject = _super.prototype.serialize.call(this);
  28619. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  28620. return serializationObject;
  28621. };
  28622. return MirrorTexture;
  28623. }(BABYLON.RenderTargetTexture));
  28624. BABYLON.MirrorTexture = MirrorTexture;
  28625. })(BABYLON || (BABYLON = {}));
  28626. //# sourceMappingURL=babylon.mirrorTexture.js.map
  28627. /// <reference path="babylon.renderTargetTexture.ts" />
  28628. var BABYLON;
  28629. (function (BABYLON) {
  28630. /**
  28631. * Creates a refraction texture used by refraction channel of the standard material.
  28632. * @param name the texture name
  28633. * @param size size of the underlying texture
  28634. * @param scene root scene
  28635. */
  28636. var RefractionTexture = (function (_super) {
  28637. __extends(RefractionTexture, _super);
  28638. function RefractionTexture(name, size, scene, generateMipMaps) {
  28639. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  28640. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  28641. _this.depth = 2.0;
  28642. _this.onBeforeRenderObservable.add(function () {
  28643. scene.clipPlane = _this.refractionPlane;
  28644. });
  28645. _this.onAfterRenderObservable.add(function () {
  28646. delete scene.clipPlane;
  28647. });
  28648. return _this;
  28649. }
  28650. RefractionTexture.prototype.clone = function () {
  28651. var textureSize = this.getSize();
  28652. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  28653. // Base texture
  28654. newTexture.hasAlpha = this.hasAlpha;
  28655. newTexture.level = this.level;
  28656. // Refraction Texture
  28657. newTexture.refractionPlane = this.refractionPlane.clone();
  28658. newTexture.renderList = this.renderList.slice(0);
  28659. newTexture.depth = this.depth;
  28660. return newTexture;
  28661. };
  28662. RefractionTexture.prototype.serialize = function () {
  28663. if (!this.name) {
  28664. return null;
  28665. }
  28666. var serializationObject = _super.prototype.serialize.call(this);
  28667. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  28668. serializationObject.depth = this.depth;
  28669. return serializationObject;
  28670. };
  28671. return RefractionTexture;
  28672. }(BABYLON.RenderTargetTexture));
  28673. BABYLON.RefractionTexture = RefractionTexture;
  28674. })(BABYLON || (BABYLON = {}));
  28675. //# sourceMappingURL=babylon.refractionTexture.js.map
  28676. /// <reference path="babylon.texture.ts" />
  28677. var BABYLON;
  28678. (function (BABYLON) {
  28679. var DynamicTexture = (function (_super) {
  28680. __extends(DynamicTexture, _super);
  28681. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  28682. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28683. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  28684. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  28685. _this.name = name;
  28686. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28687. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28688. _this._generateMipMaps = generateMipMaps;
  28689. if (options.getContext) {
  28690. _this._canvas = options;
  28691. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  28692. }
  28693. else {
  28694. _this._canvas = document.createElement("canvas");
  28695. if (options.width) {
  28696. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  28697. }
  28698. else {
  28699. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  28700. }
  28701. }
  28702. var textureSize = _this.getSize();
  28703. _this._canvas.width = textureSize.width;
  28704. _this._canvas.height = textureSize.height;
  28705. _this._context = _this._canvas.getContext("2d");
  28706. return _this;
  28707. }
  28708. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  28709. get: function () {
  28710. return true;
  28711. },
  28712. enumerable: true,
  28713. configurable: true
  28714. });
  28715. DynamicTexture.prototype.scale = function (ratio) {
  28716. var textureSize = this.getSize();
  28717. textureSize.width *= ratio;
  28718. textureSize.height *= ratio;
  28719. this._canvas.width = textureSize.width;
  28720. this._canvas.height = textureSize.height;
  28721. this.releaseInternalTexture();
  28722. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  28723. };
  28724. DynamicTexture.prototype.getContext = function () {
  28725. return this._context;
  28726. };
  28727. DynamicTexture.prototype.clear = function () {
  28728. var size = this.getSize();
  28729. this._context.fillRect(0, 0, size.width, size.height);
  28730. };
  28731. DynamicTexture.prototype.update = function (invertY) {
  28732. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  28733. };
  28734. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  28735. if (update === void 0) { update = true; }
  28736. var size = this.getSize();
  28737. if (clearColor) {
  28738. this._context.fillStyle = clearColor;
  28739. this._context.fillRect(0, 0, size.width, size.height);
  28740. }
  28741. this._context.font = font;
  28742. if (x === null || x === undefined) {
  28743. var textSize = this._context.measureText(text);
  28744. x = (size.width - textSize.width) / 2;
  28745. }
  28746. if (y === null || y === undefined) {
  28747. var fontSize = parseInt((font.replace(/\D/g, '')));
  28748. ;
  28749. y = (size.height / 2) + (fontSize / 3.65);
  28750. }
  28751. this._context.fillStyle = color;
  28752. this._context.fillText(text, x, y);
  28753. if (update) {
  28754. this.update(invertY);
  28755. }
  28756. };
  28757. DynamicTexture.prototype.clone = function () {
  28758. var textureSize = this.getSize();
  28759. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  28760. // Base texture
  28761. newTexture.hasAlpha = this.hasAlpha;
  28762. newTexture.level = this.level;
  28763. // Dynamic Texture
  28764. newTexture.wrapU = this.wrapU;
  28765. newTexture.wrapV = this.wrapV;
  28766. return newTexture;
  28767. };
  28768. return DynamicTexture;
  28769. }(BABYLON.Texture));
  28770. BABYLON.DynamicTexture = DynamicTexture;
  28771. })(BABYLON || (BABYLON = {}));
  28772. //# sourceMappingURL=babylon.dynamicTexture.js.map
  28773. var BABYLON;
  28774. (function (BABYLON) {
  28775. var VideoTexture = (function (_super) {
  28776. __extends(VideoTexture, _super);
  28777. /**
  28778. * Creates a video texture.
  28779. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  28780. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  28781. * @param {BABYLON.Scene} scene is obviously the current scene.
  28782. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  28783. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  28784. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  28785. */
  28786. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  28787. if (generateMipMaps === void 0) { generateMipMaps = false; }
  28788. if (invertY === void 0) { invertY = false; }
  28789. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28790. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  28791. _this._autoLaunch = true;
  28792. var urls;
  28793. _this.name = name;
  28794. if (urlsOrVideo instanceof HTMLVideoElement) {
  28795. _this.video = urlsOrVideo;
  28796. }
  28797. else {
  28798. urls = urlsOrVideo;
  28799. _this.video = document.createElement("video");
  28800. _this.video.autoplay = false;
  28801. _this.video.loop = true;
  28802. }
  28803. _this._generateMipMaps = generateMipMaps;
  28804. _this._samplingMode = samplingMode;
  28805. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  28806. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28807. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28808. }
  28809. else {
  28810. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28811. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28812. _this._generateMipMaps = false;
  28813. }
  28814. if (urls) {
  28815. _this.video.addEventListener("canplaythrough", function () {
  28816. _this._createTexture();
  28817. });
  28818. urls.forEach(function (url) {
  28819. var source = document.createElement("source");
  28820. source.src = url;
  28821. _this.video.appendChild(source);
  28822. });
  28823. }
  28824. else {
  28825. _this._createTexture();
  28826. }
  28827. _this._lastUpdate = BABYLON.Tools.Now;
  28828. return _this;
  28829. }
  28830. VideoTexture.prototype._createTexture = function () {
  28831. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  28832. this._texture.isReady = true;
  28833. };
  28834. VideoTexture.prototype.update = function () {
  28835. if (this._autoLaunch) {
  28836. this._autoLaunch = false;
  28837. this.video.play();
  28838. }
  28839. var now = BABYLON.Tools.Now;
  28840. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  28841. return false;
  28842. }
  28843. this._lastUpdate = now;
  28844. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  28845. return true;
  28846. };
  28847. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  28848. var video = document.createElement("video");
  28849. var constraintsDeviceId;
  28850. if (constraints && constraints.deviceId) {
  28851. constraintsDeviceId = {
  28852. exact: constraints.deviceId
  28853. };
  28854. }
  28855. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  28856. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  28857. if (navigator.getUserMedia) {
  28858. navigator.getUserMedia({
  28859. video: {
  28860. deviceId: constraintsDeviceId,
  28861. width: {
  28862. min: (constraints && constraints.minWidth) || 256,
  28863. max: (constraints && constraints.maxWidth) || 640
  28864. },
  28865. height: {
  28866. min: (constraints && constraints.minHeight) || 256,
  28867. max: (constraints && constraints.maxHeight) || 480
  28868. }
  28869. }
  28870. }, function (stream) {
  28871. if (video.mozSrcObject !== undefined) {
  28872. video.mozSrcObject = stream;
  28873. }
  28874. else {
  28875. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  28876. }
  28877. video.play();
  28878. if (onReady) {
  28879. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  28880. }
  28881. }, function (e) {
  28882. BABYLON.Tools.Error(e.name);
  28883. });
  28884. }
  28885. };
  28886. return VideoTexture;
  28887. }(BABYLON.Texture));
  28888. BABYLON.VideoTexture = VideoTexture;
  28889. })(BABYLON || (BABYLON = {}));
  28890. //# sourceMappingURL=babylon.videoTexture.js.map
  28891. /// <reference path="babylon.proceduralTexture.ts" />
  28892. var BABYLON;
  28893. (function (BABYLON) {
  28894. var CustomProceduralTexture = (function (_super) {
  28895. __extends(CustomProceduralTexture, _super);
  28896. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  28897. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  28898. _this._animate = true;
  28899. _this._time = 0;
  28900. _this._texturePath = texturePath;
  28901. //Try to load json
  28902. _this.loadJson(texturePath);
  28903. _this.refreshRate = 1;
  28904. return _this;
  28905. }
  28906. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  28907. var _this = this;
  28908. var that = this;
  28909. function noConfigFile() {
  28910. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  28911. try {
  28912. that.setFragment(that._texturePath);
  28913. }
  28914. catch (ex) {
  28915. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  28916. }
  28917. }
  28918. var configFileUrl = jsonUrl + "/config.json";
  28919. var xhr = new XMLHttpRequest();
  28920. xhr.open("GET", configFileUrl, true);
  28921. xhr.addEventListener("load", function () {
  28922. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  28923. try {
  28924. _this._config = JSON.parse(xhr.response);
  28925. _this.updateShaderUniforms();
  28926. _this.updateTextures();
  28927. _this.setFragment(_this._texturePath + "/custom");
  28928. _this._animate = _this._config.animate;
  28929. _this.refreshRate = _this._config.refreshrate;
  28930. }
  28931. catch (ex) {
  28932. noConfigFile();
  28933. }
  28934. }
  28935. else {
  28936. noConfigFile();
  28937. }
  28938. }, false);
  28939. xhr.addEventListener("error", function () {
  28940. noConfigFile();
  28941. }, false);
  28942. try {
  28943. xhr.send();
  28944. }
  28945. catch (ex) {
  28946. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  28947. }
  28948. };
  28949. CustomProceduralTexture.prototype.isReady = function () {
  28950. if (!_super.prototype.isReady.call(this)) {
  28951. return false;
  28952. }
  28953. for (var name in this._textures) {
  28954. var texture = this._textures[name];
  28955. if (!texture.isReady()) {
  28956. return false;
  28957. }
  28958. }
  28959. return true;
  28960. };
  28961. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  28962. if (this._animate) {
  28963. this._time += this.getScene().getAnimationRatio() * 0.03;
  28964. this.updateShaderUniforms();
  28965. }
  28966. _super.prototype.render.call(this, useCameraPostProcess);
  28967. };
  28968. CustomProceduralTexture.prototype.updateTextures = function () {
  28969. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  28970. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  28971. }
  28972. };
  28973. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  28974. if (this._config) {
  28975. for (var j = 0; j < this._config.uniforms.length; j++) {
  28976. var uniform = this._config.uniforms[j];
  28977. switch (uniform.type) {
  28978. case "float":
  28979. this.setFloat(uniform.name, uniform.value);
  28980. break;
  28981. case "color3":
  28982. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  28983. break;
  28984. case "color4":
  28985. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  28986. break;
  28987. case "vector2":
  28988. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  28989. break;
  28990. case "vector3":
  28991. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  28992. break;
  28993. }
  28994. }
  28995. }
  28996. this.setFloat("time", this._time);
  28997. };
  28998. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  28999. get: function () {
  29000. return this._animate;
  29001. },
  29002. set: function (value) {
  29003. this._animate = value;
  29004. },
  29005. enumerable: true,
  29006. configurable: true
  29007. });
  29008. return CustomProceduralTexture;
  29009. }(BABYLON.ProceduralTexture));
  29010. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  29011. })(BABYLON || (BABYLON = {}));
  29012. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  29013. var BABYLON;
  29014. (function (BABYLON) {
  29015. var EffectFallbacks = (function () {
  29016. function EffectFallbacks() {
  29017. this._defines = {};
  29018. this._currentRank = 32;
  29019. this._maxRank = -1;
  29020. }
  29021. EffectFallbacks.prototype.addFallback = function (rank, define) {
  29022. if (!this._defines[rank]) {
  29023. if (rank < this._currentRank) {
  29024. this._currentRank = rank;
  29025. }
  29026. if (rank > this._maxRank) {
  29027. this._maxRank = rank;
  29028. }
  29029. this._defines[rank] = new Array();
  29030. }
  29031. this._defines[rank].push(define);
  29032. };
  29033. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  29034. this._meshRank = rank;
  29035. this._mesh = mesh;
  29036. if (rank < this._currentRank) {
  29037. this._currentRank = rank;
  29038. }
  29039. if (rank > this._maxRank) {
  29040. this._maxRank = rank;
  29041. }
  29042. };
  29043. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  29044. get: function () {
  29045. return this._currentRank <= this._maxRank;
  29046. },
  29047. enumerable: true,
  29048. configurable: true
  29049. });
  29050. EffectFallbacks.prototype.reduce = function (currentDefines) {
  29051. // First we try to switch to CPU skinning
  29052. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  29053. this._mesh.computeBonesUsingShaders = false;
  29054. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  29055. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  29056. var scene = this._mesh.getScene();
  29057. for (var index = 0; index < scene.meshes.length; index++) {
  29058. var otherMesh = scene.meshes[index];
  29059. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  29060. otherMesh.computeBonesUsingShaders = false;
  29061. }
  29062. }
  29063. }
  29064. else {
  29065. var currentFallbacks = this._defines[this._currentRank];
  29066. if (currentFallbacks) {
  29067. for (var index = 0; index < currentFallbacks.length; index++) {
  29068. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  29069. }
  29070. }
  29071. this._currentRank++;
  29072. }
  29073. return currentDefines;
  29074. };
  29075. return EffectFallbacks;
  29076. }());
  29077. BABYLON.EffectFallbacks = EffectFallbacks;
  29078. var Effect = (function () {
  29079. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  29080. var _this = this;
  29081. this.uniqueId = 0;
  29082. this._isReady = false;
  29083. this._compilationError = "";
  29084. this._valueCache = {};
  29085. this._engine = engine;
  29086. this.name = baseName;
  29087. this.defines = defines;
  29088. this._uniformsNames = uniformsNames.concat(samplers);
  29089. this._samplers = samplers;
  29090. this._attributesNames = attributesNames;
  29091. this.onError = onError;
  29092. this.onCompiled = onCompiled;
  29093. this._indexParameters = indexParameters;
  29094. this.uniqueId = Effect._uniqueIdSeed++;
  29095. var vertexSource;
  29096. var fragmentSource;
  29097. if (baseName.vertexElement) {
  29098. vertexSource = document.getElementById(baseName.vertexElement);
  29099. if (!vertexSource) {
  29100. vertexSource = baseName.vertexElement;
  29101. }
  29102. }
  29103. else {
  29104. vertexSource = baseName.vertex || baseName;
  29105. }
  29106. if (baseName.fragmentElement) {
  29107. fragmentSource = document.getElementById(baseName.fragmentElement);
  29108. if (!fragmentSource) {
  29109. fragmentSource = baseName.fragmentElement;
  29110. }
  29111. }
  29112. else {
  29113. fragmentSource = baseName.fragment || baseName;
  29114. }
  29115. this._loadVertexShader(vertexSource, function (vertexCode) {
  29116. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  29117. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  29118. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  29119. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  29120. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  29121. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  29122. });
  29123. });
  29124. });
  29125. });
  29126. });
  29127. });
  29128. }
  29129. Object.defineProperty(Effect.prototype, "key", {
  29130. get: function () {
  29131. return this._key;
  29132. },
  29133. enumerable: true,
  29134. configurable: true
  29135. });
  29136. // Properties
  29137. Effect.prototype.isReady = function () {
  29138. return this._isReady;
  29139. };
  29140. Effect.prototype.getProgram = function () {
  29141. return this._program;
  29142. };
  29143. Effect.prototype.getAttributesNames = function () {
  29144. return this._attributesNames;
  29145. };
  29146. Effect.prototype.getAttributeLocation = function (index) {
  29147. return this._attributes[index];
  29148. };
  29149. Effect.prototype.getAttributeLocationByName = function (name) {
  29150. var index = this._attributesNames.indexOf(name);
  29151. return this._attributes[index];
  29152. };
  29153. Effect.prototype.getAttributesCount = function () {
  29154. return this._attributes.length;
  29155. };
  29156. Effect.prototype.getUniformIndex = function (uniformName) {
  29157. return this._uniformsNames.indexOf(uniformName);
  29158. };
  29159. Effect.prototype.getUniform = function (uniformName) {
  29160. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  29161. };
  29162. Effect.prototype.getSamplers = function () {
  29163. return this._samplers;
  29164. };
  29165. Effect.prototype.getCompilationError = function () {
  29166. return this._compilationError;
  29167. };
  29168. Effect.prototype.getVertexShaderSource = function () {
  29169. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  29170. };
  29171. Effect.prototype.getFragmentShaderSource = function () {
  29172. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  29173. };
  29174. // Methods
  29175. Effect.prototype._loadVertexShader = function (vertex, callback) {
  29176. // DOM element ?
  29177. if (vertex instanceof HTMLElement) {
  29178. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  29179. callback(vertexCode);
  29180. return;
  29181. }
  29182. // Base64 encoded ?
  29183. if (vertex.substr(0, 7) === "base64:") {
  29184. var vertexBinary = window.atob(vertex.substr(7));
  29185. callback(vertexBinary);
  29186. return;
  29187. }
  29188. // Is in local store ?
  29189. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  29190. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  29191. return;
  29192. }
  29193. var vertexShaderUrl;
  29194. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  29195. vertexShaderUrl = vertex;
  29196. }
  29197. else {
  29198. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  29199. }
  29200. // Vertex shader
  29201. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  29202. };
  29203. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  29204. // DOM element ?
  29205. if (fragment instanceof HTMLElement) {
  29206. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  29207. callback(fragmentCode);
  29208. return;
  29209. }
  29210. // Base64 encoded ?
  29211. if (fragment.substr(0, 7) === "base64:") {
  29212. var fragmentBinary = window.atob(fragment.substr(7));
  29213. callback(fragmentBinary);
  29214. return;
  29215. }
  29216. // Is in local store ?
  29217. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  29218. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  29219. return;
  29220. }
  29221. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  29222. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  29223. return;
  29224. }
  29225. var fragmentShaderUrl;
  29226. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  29227. fragmentShaderUrl = fragment;
  29228. }
  29229. else {
  29230. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  29231. }
  29232. // Fragment shader
  29233. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  29234. };
  29235. Effect.prototype._dumpShadersName = function () {
  29236. if (this.name.vertexElement) {
  29237. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  29238. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  29239. }
  29240. else if (this.name.vertex) {
  29241. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  29242. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  29243. }
  29244. else {
  29245. BABYLON.Tools.Error("Vertex shader:" + this.name);
  29246. BABYLON.Tools.Error("Fragment shader:" + this.name);
  29247. }
  29248. };
  29249. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  29250. var preparedSourceCode = this._processPrecision(sourceCode);
  29251. if (this._engine.webGLVersion == 1) {
  29252. callback(preparedSourceCode);
  29253. return;
  29254. }
  29255. // Already converted
  29256. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  29257. callback(preparedSourceCode);
  29258. return;
  29259. }
  29260. // Remove extensions
  29261. // #extension GL_OES_standard_derivatives : enable
  29262. // #extension GL_EXT_shader_texture_lod : enable
  29263. // #extension GL_EXT_frag_depth : enable
  29264. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  29265. var result = preparedSourceCode.replace(regex, "");
  29266. // Migrate to GLSL v300
  29267. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  29268. result = result.replace(/attribute[ \t]/g, "in ");
  29269. result = result.replace(/[ \t]attribute/g, " in");
  29270. if (isFragment) {
  29271. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  29272. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  29273. result = result.replace(/texture2D\(/g, "texture(");
  29274. result = result.replace(/textureCube\(/g, "texture(");
  29275. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  29276. result = result.replace(/gl_FragColor/g, "glFragColor");
  29277. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  29278. }
  29279. callback(result);
  29280. };
  29281. Effect.prototype._processIncludes = function (sourceCode, callback) {
  29282. var _this = this;
  29283. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  29284. var match = regex.exec(sourceCode);
  29285. var returnValue = new String(sourceCode);
  29286. while (match != null) {
  29287. var includeFile = match[1];
  29288. if (Effect.IncludesShadersStore[includeFile]) {
  29289. // Substitution
  29290. var includeContent = Effect.IncludesShadersStore[includeFile];
  29291. if (match[2]) {
  29292. var splits = match[3].split(",");
  29293. for (var index = 0; index < splits.length; index += 2) {
  29294. var source = new RegExp(splits[index], "g");
  29295. var dest = splits[index + 1];
  29296. includeContent = includeContent.replace(source, dest);
  29297. }
  29298. }
  29299. if (match[4]) {
  29300. var indexString = match[5];
  29301. if (indexString.indexOf("..") !== -1) {
  29302. var indexSplits = indexString.split("..");
  29303. var minIndex = parseInt(indexSplits[0]);
  29304. var maxIndex = parseInt(indexSplits[1]);
  29305. var sourceIncludeContent = includeContent.slice(0);
  29306. includeContent = "";
  29307. if (isNaN(maxIndex)) {
  29308. maxIndex = this._indexParameters[indexSplits[1]];
  29309. }
  29310. for (var i = minIndex; i <= maxIndex; i++) {
  29311. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  29312. }
  29313. }
  29314. else {
  29315. includeContent = includeContent.replace(/\{X\}/g, indexString);
  29316. }
  29317. }
  29318. // Replace
  29319. returnValue = returnValue.replace(match[0], includeContent);
  29320. }
  29321. else {
  29322. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  29323. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  29324. Effect.IncludesShadersStore[includeFile] = fileContent;
  29325. _this._processIncludes(returnValue, callback);
  29326. });
  29327. return;
  29328. }
  29329. match = regex.exec(sourceCode);
  29330. }
  29331. callback(returnValue);
  29332. };
  29333. Effect.prototype._processPrecision = function (source) {
  29334. if (source.indexOf("precision highp float") === -1) {
  29335. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  29336. source = "precision mediump float;\n" + source;
  29337. }
  29338. else {
  29339. source = "precision highp float;\n" + source;
  29340. }
  29341. }
  29342. else {
  29343. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  29344. source = source.replace("precision highp float", "precision mediump float");
  29345. }
  29346. }
  29347. return source;
  29348. };
  29349. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  29350. try {
  29351. var engine = this._engine;
  29352. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  29353. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  29354. this._attributes = engine.getAttributes(this._program, attributesNames);
  29355. var index;
  29356. for (index = 0; index < this._samplers.length; index++) {
  29357. var sampler = this.getUniform(this._samplers[index]);
  29358. if (sampler == null) {
  29359. this._samplers.splice(index, 1);
  29360. index--;
  29361. }
  29362. }
  29363. engine.bindSamplers(this);
  29364. this._compilationError = "";
  29365. this._isReady = true;
  29366. if (this.onCompiled) {
  29367. this.onCompiled(this);
  29368. }
  29369. }
  29370. catch (e) {
  29371. this._compilationError = e.message;
  29372. // Let's go through fallbacks then
  29373. BABYLON.Tools.Error("Unable to compile effect: ");
  29374. BABYLON.Tools.Error("Defines: " + defines);
  29375. BABYLON.Tools.Error("Error: " + this._compilationError);
  29376. this._dumpShadersName();
  29377. if (fallbacks && fallbacks.isMoreFallbacks) {
  29378. BABYLON.Tools.Error("Trying next fallback.");
  29379. defines = fallbacks.reduce(defines);
  29380. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  29381. }
  29382. else {
  29383. if (this.onError) {
  29384. this.onError(this, this._compilationError);
  29385. }
  29386. }
  29387. }
  29388. };
  29389. Object.defineProperty(Effect.prototype, "isSupported", {
  29390. get: function () {
  29391. return this._compilationError === "";
  29392. },
  29393. enumerable: true,
  29394. configurable: true
  29395. });
  29396. Effect.prototype._bindTexture = function (channel, texture) {
  29397. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  29398. };
  29399. Effect.prototype.setTexture = function (channel, texture) {
  29400. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  29401. };
  29402. Effect.prototype.setTextureArray = function (channel, textures) {
  29403. if (this._samplers.indexOf(channel + "Ex") === -1) {
  29404. var initialPos = this._samplers.indexOf(channel);
  29405. for (var index = 1; index < textures.length; index++) {
  29406. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  29407. }
  29408. }
  29409. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  29410. };
  29411. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  29412. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  29413. };
  29414. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  29415. var changed = false;
  29416. var cache = this._valueCache[uniformName];
  29417. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  29418. changed = true;
  29419. cache = new BABYLON.Matrix();
  29420. }
  29421. var tm = cache.m;
  29422. var om = matrix.m;
  29423. for (var index = 0; index < 16; index++) {
  29424. if (tm[index] !== om[index]) {
  29425. tm[index] = om[index];
  29426. changed = true;
  29427. }
  29428. }
  29429. this._valueCache[uniformName] = cache;
  29430. return changed;
  29431. };
  29432. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  29433. var cache = this._valueCache[uniformName];
  29434. if (!cache) {
  29435. cache = [x, y];
  29436. this._valueCache[uniformName] = cache;
  29437. return true;
  29438. }
  29439. var changed = false;
  29440. if (cache[0] !== x) {
  29441. cache[0] = x;
  29442. changed = true;
  29443. }
  29444. if (cache[1] !== y) {
  29445. cache[1] = y;
  29446. changed = true;
  29447. }
  29448. return changed;
  29449. };
  29450. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  29451. var cache = this._valueCache[uniformName];
  29452. if (!cache) {
  29453. cache = [x, y, z];
  29454. this._valueCache[uniformName] = cache;
  29455. return true;
  29456. }
  29457. var changed = false;
  29458. if (cache[0] !== x) {
  29459. cache[0] = x;
  29460. changed = true;
  29461. }
  29462. if (cache[1] !== y) {
  29463. cache[1] = y;
  29464. changed = true;
  29465. }
  29466. if (cache[2] !== z) {
  29467. cache[2] = z;
  29468. changed = true;
  29469. }
  29470. return changed;
  29471. };
  29472. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  29473. var cache = this._valueCache[uniformName];
  29474. if (!cache) {
  29475. cache = [x, y, z, w];
  29476. this._valueCache[uniformName] = cache;
  29477. return true;
  29478. }
  29479. var changed = false;
  29480. if (cache[0] !== x) {
  29481. cache[0] = x;
  29482. changed = true;
  29483. }
  29484. if (cache[1] !== y) {
  29485. cache[1] = y;
  29486. changed = true;
  29487. }
  29488. if (cache[2] !== z) {
  29489. cache[2] = z;
  29490. changed = true;
  29491. }
  29492. if (cache[3] !== w) {
  29493. cache[3] = w;
  29494. changed = true;
  29495. }
  29496. return changed;
  29497. };
  29498. Effect.prototype.setIntArray = function (uniformName, array) {
  29499. this._valueCache[uniformName] = null;
  29500. this._engine.setIntArray(this.getUniform(uniformName), array);
  29501. return this;
  29502. };
  29503. Effect.prototype.setIntArray2 = function (uniformName, array) {
  29504. this._valueCache[uniformName] = null;
  29505. this._engine.setIntArray2(this.getUniform(uniformName), array);
  29506. return this;
  29507. };
  29508. Effect.prototype.setIntArray3 = function (uniformName, array) {
  29509. this._valueCache[uniformName] = null;
  29510. this._engine.setIntArray3(this.getUniform(uniformName), array);
  29511. return this;
  29512. };
  29513. Effect.prototype.setIntArray4 = function (uniformName, array) {
  29514. this._valueCache[uniformName] = null;
  29515. this._engine.setIntArray4(this.getUniform(uniformName), array);
  29516. return this;
  29517. };
  29518. Effect.prototype.setFloatArray = function (uniformName, array) {
  29519. this._valueCache[uniformName] = null;
  29520. this._engine.setFloatArray(this.getUniform(uniformName), array);
  29521. return this;
  29522. };
  29523. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  29524. this._valueCache[uniformName] = null;
  29525. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  29526. return this;
  29527. };
  29528. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  29529. this._valueCache[uniformName] = null;
  29530. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  29531. return this;
  29532. };
  29533. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  29534. this._valueCache[uniformName] = null;
  29535. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  29536. return this;
  29537. };
  29538. Effect.prototype.setArray = function (uniformName, array) {
  29539. this._valueCache[uniformName] = null;
  29540. this._engine.setArray(this.getUniform(uniformName), array);
  29541. return this;
  29542. };
  29543. Effect.prototype.setArray2 = function (uniformName, array) {
  29544. this._valueCache[uniformName] = null;
  29545. this._engine.setArray2(this.getUniform(uniformName), array);
  29546. return this;
  29547. };
  29548. Effect.prototype.setArray3 = function (uniformName, array) {
  29549. this._valueCache[uniformName] = null;
  29550. this._engine.setArray3(this.getUniform(uniformName), array);
  29551. return this;
  29552. };
  29553. Effect.prototype.setArray4 = function (uniformName, array) {
  29554. this._valueCache[uniformName] = null;
  29555. this._engine.setArray4(this.getUniform(uniformName), array);
  29556. return this;
  29557. };
  29558. Effect.prototype.setMatrices = function (uniformName, matrices) {
  29559. this._valueCache[uniformName] = null;
  29560. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  29561. return this;
  29562. };
  29563. Effect.prototype.setMatrix = function (uniformName, matrix) {
  29564. if (this._cacheMatrix(uniformName, matrix)) {
  29565. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  29566. }
  29567. return this;
  29568. };
  29569. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  29570. this._valueCache[uniformName] = null;
  29571. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  29572. return this;
  29573. };
  29574. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  29575. this._valueCache[uniformName] = null;
  29576. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  29577. return this;
  29578. };
  29579. Effect.prototype.setFloat = function (uniformName, value) {
  29580. var cache = this._valueCache[uniformName];
  29581. if (cache !== undefined && cache === value)
  29582. return this;
  29583. this._valueCache[uniformName] = value;
  29584. this._engine.setFloat(this.getUniform(uniformName), value);
  29585. return this;
  29586. };
  29587. Effect.prototype.setBool = function (uniformName, bool) {
  29588. var cache = this._valueCache[uniformName];
  29589. if (cache !== undefined && cache === bool)
  29590. return this;
  29591. this._valueCache[uniformName] = bool;
  29592. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  29593. return this;
  29594. };
  29595. Effect.prototype.setVector2 = function (uniformName, vector2) {
  29596. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  29597. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  29598. }
  29599. return this;
  29600. };
  29601. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  29602. if (this._cacheFloat2(uniformName, x, y)) {
  29603. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  29604. }
  29605. return this;
  29606. };
  29607. Effect.prototype.setVector3 = function (uniformName, vector3) {
  29608. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  29609. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  29610. }
  29611. return this;
  29612. };
  29613. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  29614. if (this._cacheFloat3(uniformName, x, y, z)) {
  29615. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  29616. }
  29617. return this;
  29618. };
  29619. Effect.prototype.setVector4 = function (uniformName, vector4) {
  29620. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  29621. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  29622. }
  29623. return this;
  29624. };
  29625. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  29626. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  29627. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  29628. }
  29629. return this;
  29630. };
  29631. Effect.prototype.setColor3 = function (uniformName, color3) {
  29632. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  29633. this._engine.setColor3(this.getUniform(uniformName), color3);
  29634. }
  29635. return this;
  29636. };
  29637. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  29638. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  29639. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  29640. }
  29641. return this;
  29642. };
  29643. Effect.prototype._recombineShader = function (node) {
  29644. if (node.define) {
  29645. if (node.condition) {
  29646. var defineIndex = this.defines.indexOf("#define " + node.define);
  29647. if (defineIndex === -1) {
  29648. return null;
  29649. }
  29650. var nextComma = this.defines.indexOf("\n", defineIndex);
  29651. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  29652. var condition = defineValue + node.condition;
  29653. if (!eval(condition)) {
  29654. return null;
  29655. }
  29656. }
  29657. else if (node.ndef) {
  29658. if (this.defines.indexOf("#define " + node.define) !== -1) {
  29659. return null;
  29660. }
  29661. }
  29662. else if (this.defines.indexOf("#define " + node.define) === -1) {
  29663. return null;
  29664. }
  29665. }
  29666. var result = "";
  29667. for (var index = 0; index < node.children.length; index++) {
  29668. var line = node.children[index];
  29669. if (line.children) {
  29670. var combined = this._recombineShader(line);
  29671. if (combined !== null) {
  29672. result += combined + "\r\n";
  29673. }
  29674. continue;
  29675. }
  29676. if (line.length > 0) {
  29677. result += line + "\r\n";
  29678. }
  29679. }
  29680. return result;
  29681. };
  29682. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  29683. var root = {
  29684. children: []
  29685. };
  29686. var currentNode = root;
  29687. var lines = shaderString.split("\n");
  29688. for (var index = 0; index < lines.length; index++) {
  29689. var line = lines[index].trim();
  29690. // #ifdef
  29691. var pos = line.indexOf("#ifdef ");
  29692. if (pos !== -1) {
  29693. var define = line.substr(pos + 7);
  29694. var newNode = {
  29695. condition: null,
  29696. ndef: false,
  29697. define: define,
  29698. children: [],
  29699. parent: currentNode
  29700. };
  29701. currentNode.children.push(newNode);
  29702. currentNode = newNode;
  29703. continue;
  29704. }
  29705. // #ifndef
  29706. var pos = line.indexOf("#ifndef ");
  29707. if (pos !== -1) {
  29708. var define = line.substr(pos + 8);
  29709. newNode = {
  29710. condition: null,
  29711. define: define,
  29712. ndef: true,
  29713. children: [],
  29714. parent: currentNode
  29715. };
  29716. currentNode.children.push(newNode);
  29717. currentNode = newNode;
  29718. continue;
  29719. }
  29720. // #if
  29721. var pos = line.indexOf("#if ");
  29722. if (pos !== -1) {
  29723. var define = line.substr(pos + 4).trim();
  29724. var conditionPos = define.indexOf(" ");
  29725. newNode = {
  29726. condition: define.substr(conditionPos + 1),
  29727. define: define.substr(0, conditionPos),
  29728. ndef: false,
  29729. children: [],
  29730. parent: currentNode
  29731. };
  29732. currentNode.children.push(newNode);
  29733. currentNode = newNode;
  29734. continue;
  29735. }
  29736. // #endif
  29737. pos = line.indexOf("#endif");
  29738. if (pos !== -1) {
  29739. currentNode = currentNode.parent;
  29740. continue;
  29741. }
  29742. currentNode.children.push(line);
  29743. }
  29744. // Recombine
  29745. return this._recombineShader(root);
  29746. };
  29747. return Effect;
  29748. }());
  29749. Effect._uniqueIdSeed = 0;
  29750. // Statics
  29751. Effect.ShadersStore = {};
  29752. Effect.IncludesShadersStore = {};
  29753. BABYLON.Effect = Effect;
  29754. })(BABYLON || (BABYLON = {}));
  29755. //# sourceMappingURL=babylon.effect.js.map
  29756. var BABYLON;
  29757. (function (BABYLON) {
  29758. var MaterialHelper = (function () {
  29759. function MaterialHelper() {
  29760. }
  29761. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useInstances) {
  29762. if (!defines._areAttributesDirty) {
  29763. return;
  29764. }
  29765. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  29766. if (defines._needUVs) {
  29767. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  29768. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  29769. }
  29770. else {
  29771. defines["UV1"] = false;
  29772. defines["UV2"] = false;
  29773. }
  29774. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  29775. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  29776. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29777. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  29778. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  29779. }
  29780. else {
  29781. defines["NUM_BONE_INFLUENCERS"] = 0;
  29782. defines["BonesPerMesh"] = 0;
  29783. }
  29784. };
  29785. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights, disableLighting) {
  29786. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29787. if (disableLighting === void 0) { disableLighting = false; }
  29788. if (!defines._areLightsDirty) {
  29789. return defines._needNormals;
  29790. }
  29791. var lightIndex = 0;
  29792. var needNormals = false;
  29793. var needRebuild = false;
  29794. var needShadows = false;
  29795. var lightmapMode = false;
  29796. if (scene.lightsEnabled && !disableLighting) {
  29797. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  29798. var light = _a[_i];
  29799. needNormals = true;
  29800. if (defines["LIGHT" + lightIndex] === undefined) {
  29801. needRebuild = true;
  29802. }
  29803. defines["LIGHT" + lightIndex] = true;
  29804. var type;
  29805. if (light instanceof BABYLON.SpotLight) {
  29806. type = "SPOTLIGHT" + lightIndex;
  29807. }
  29808. else if (light instanceof BABYLON.HemisphericLight) {
  29809. type = "HEMILIGHT" + lightIndex;
  29810. }
  29811. else if (light instanceof BABYLON.PointLight) {
  29812. type = "POINTLIGHT" + lightIndex;
  29813. }
  29814. else {
  29815. type = "DIRLIGHT" + lightIndex;
  29816. }
  29817. if (!needRebuild && defines[type] === undefined) {
  29818. needRebuild = true;
  29819. }
  29820. defines[type] = true;
  29821. // Specular
  29822. defines["SPECULARTERM"] = (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined);
  29823. // Shadows
  29824. var shadowEnabled = false;
  29825. if (scene.shadowsEnabled) {
  29826. var shadowGenerator = light.getShadowGenerator();
  29827. if (mesh && mesh.receiveShadows && shadowGenerator) {
  29828. if (!needRebuild && defines["SHADOW" + lightIndex] === undefined) {
  29829. needRebuild = true;
  29830. }
  29831. defines["SHADOW" + lightIndex] = true;
  29832. shadowEnabled = true;
  29833. if (shadowGenerator.usePoissonSampling) {
  29834. if (!needRebuild && defines["SHADOWPCF" + lightIndex] === undefined) {
  29835. needRebuild = true;
  29836. }
  29837. defines["SHADOWPCF" + lightIndex] = true;
  29838. }
  29839. else if (shadowGenerator.useExponentialShadowMap || shadowGenerator.useBlurExponentialShadowMap) {
  29840. if (!needRebuild && defines["SHADOWESM" + lightIndex] === undefined) {
  29841. needRebuild = true;
  29842. }
  29843. defines["SHADOWESM" + lightIndex] = true;
  29844. }
  29845. needShadows = true;
  29846. }
  29847. else {
  29848. defines["SHADOW" + lightIndex] = false;
  29849. }
  29850. }
  29851. defines["SHADOWS"] = shadowEnabled;
  29852. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  29853. lightmapMode = true;
  29854. if (!needRebuild && defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  29855. needRebuild = true;
  29856. }
  29857. if (!needRebuild && defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  29858. needRebuild = true;
  29859. }
  29860. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  29861. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  29862. }
  29863. else {
  29864. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  29865. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  29866. }
  29867. lightIndex++;
  29868. if (lightIndex === maxSimultaneousLights)
  29869. break;
  29870. }
  29871. }
  29872. // Resetting all other lights if any
  29873. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  29874. if (defines["LIGHT" + index] !== undefined) {
  29875. defines["LIGHT" + index] = false;
  29876. }
  29877. }
  29878. var caps = scene.getEngine().getCaps();
  29879. if (!needRebuild && defines["SHADOWFULLFLOAT"] === undefined) {
  29880. needRebuild = true;
  29881. }
  29882. defines["SHADOWFULLFLOAT"] = (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender);
  29883. if (!needRebuild && defines["LIGHTMAPEXCLUDED"] === undefined) {
  29884. needRebuild = true;
  29885. }
  29886. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  29887. if (needRebuild) {
  29888. defines.rebuild();
  29889. }
  29890. return needNormals;
  29891. };
  29892. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  29893. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29894. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  29895. if (!defines["LIGHT" + lightIndex]) {
  29896. break;
  29897. }
  29898. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  29899. samplersList.push("shadowSampler" + lightIndex);
  29900. }
  29901. };
  29902. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  29903. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29904. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  29905. if (!defines["LIGHT" + lightIndex]) {
  29906. break;
  29907. }
  29908. if (lightIndex > 0) {
  29909. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  29910. }
  29911. if (defines["SHADOW" + lightIndex]) {
  29912. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  29913. }
  29914. if (defines["SHADOWPCF" + lightIndex]) {
  29915. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  29916. }
  29917. if (defines["SHADOWESM" + lightIndex]) {
  29918. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  29919. }
  29920. }
  29921. };
  29922. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  29923. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  29924. fallbacks.addCPUSkinningFallback(0, mesh);
  29925. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29926. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29927. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  29928. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  29929. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  29930. }
  29931. }
  29932. };
  29933. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  29934. if (defines["INSTANCES"]) {
  29935. attribs.push("world0");
  29936. attribs.push("world1");
  29937. attribs.push("world2");
  29938. attribs.push("world3");
  29939. }
  29940. };
  29941. // Bindings
  29942. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  29943. var shadowGenerator = light.getShadowGenerator();
  29944. if (mesh.receiveShadows && shadowGenerator) {
  29945. if (!light.needCube()) {
  29946. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  29947. }
  29948. else {
  29949. if (!depthValuesAlreadySet) {
  29950. depthValuesAlreadySet = true;
  29951. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  29952. }
  29953. }
  29954. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  29955. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.depthScale);
  29956. }
  29957. return depthValuesAlreadySet;
  29958. };
  29959. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  29960. if (light instanceof BABYLON.PointLight) {
  29961. // Point Light
  29962. light.transferToEffect(effect, "vLightData" + lightIndex);
  29963. }
  29964. else if (light instanceof BABYLON.DirectionalLight) {
  29965. // Directional Light
  29966. light.transferToEffect(effect, "vLightData" + lightIndex);
  29967. }
  29968. else if (light instanceof BABYLON.SpotLight) {
  29969. // Spot Light
  29970. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  29971. }
  29972. else if (light instanceof BABYLON.HemisphericLight) {
  29973. // Hemispheric Light
  29974. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  29975. }
  29976. };
  29977. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  29978. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29979. var lightIndex = 0;
  29980. var depthValuesAlreadySet = false;
  29981. for (var index = 0; index < scene.lights.length; index++) {
  29982. var light = scene.lights[index];
  29983. if (!light.isEnabled()) {
  29984. continue;
  29985. }
  29986. if (!light.canAffectMesh(mesh)) {
  29987. continue;
  29988. }
  29989. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  29990. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  29991. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  29992. if (defines["SPECULARTERM"]) {
  29993. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  29994. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  29995. }
  29996. // Shadows
  29997. if (scene.shadowsEnabled) {
  29998. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  29999. }
  30000. lightIndex++;
  30001. if (lightIndex === maxSimultaneousLights)
  30002. break;
  30003. }
  30004. };
  30005. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  30006. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  30007. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  30008. effect.setColor3("vFogColor", scene.fogColor);
  30009. }
  30010. };
  30011. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  30012. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30013. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  30014. if (matrices) {
  30015. effect.setMatrices("mBones", matrices);
  30016. }
  30017. }
  30018. };
  30019. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  30020. if (defines["LOGARITHMICDEPTH"]) {
  30021. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  30022. }
  30023. };
  30024. MaterialHelper.BindClipPlane = function (effect, scene) {
  30025. if (scene.clipPlane) {
  30026. var clipPlane = scene.clipPlane;
  30027. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  30028. }
  30029. };
  30030. return MaterialHelper;
  30031. }());
  30032. BABYLON.MaterialHelper = MaterialHelper;
  30033. })(BABYLON || (BABYLON = {}));
  30034. //# sourceMappingURL=babylon.materialHelper.js.map
  30035. var BABYLON;
  30036. (function (BABYLON) {
  30037. var FresnelParameters = (function () {
  30038. function FresnelParameters() {
  30039. this._isEnabled = true;
  30040. this.leftColor = BABYLON.Color3.White();
  30041. this.rightColor = BABYLON.Color3.Black();
  30042. this.bias = 0;
  30043. this.power = 1;
  30044. }
  30045. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  30046. get: function () {
  30047. return this._isEnabled;
  30048. },
  30049. set: function (value) {
  30050. if (this._isEnabled === value) {
  30051. return;
  30052. }
  30053. this._isEnabled = value;
  30054. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  30055. },
  30056. enumerable: true,
  30057. configurable: true
  30058. });
  30059. FresnelParameters.prototype.clone = function () {
  30060. var newFresnelParameters = new FresnelParameters();
  30061. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  30062. return newFresnelParameters;
  30063. };
  30064. FresnelParameters.prototype.serialize = function () {
  30065. var serializationObject = {};
  30066. serializationObject.isEnabled = this.isEnabled;
  30067. serializationObject.leftColor = this.leftColor;
  30068. serializationObject.rightColor = this.rightColor;
  30069. serializationObject.bias = this.bias;
  30070. serializationObject.power = this.power;
  30071. return serializationObject;
  30072. };
  30073. FresnelParameters.Parse = function (parsedFresnelParameters) {
  30074. var fresnelParameters = new FresnelParameters();
  30075. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  30076. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  30077. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  30078. fresnelParameters.bias = parsedFresnelParameters.bias;
  30079. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  30080. return fresnelParameters;
  30081. };
  30082. return FresnelParameters;
  30083. }());
  30084. BABYLON.FresnelParameters = FresnelParameters;
  30085. })(BABYLON || (BABYLON = {}));
  30086. //# sourceMappingURL=babylon.fresnelParameters.js.map
  30087. var BABYLON;
  30088. (function (BABYLON) {
  30089. var MaterialDefines = (function () {
  30090. function MaterialDefines(trackIsDirty) {
  30091. this._isDirty = true;
  30092. this._trackIsDirty = false;
  30093. this._areLightsDirty = true;
  30094. this._areAttributesDirty = true;
  30095. this._needNormals = false;
  30096. this._needUVs = false;
  30097. this._trackIsDirty = trackIsDirty;
  30098. }
  30099. MaterialDefines.prototype._reBind = function (key) {
  30100. this["_" + key] = this[key];
  30101. Object.defineProperty(this, key, {
  30102. get: function () {
  30103. return this["_" + key];
  30104. },
  30105. set: function (value) {
  30106. if (this["_" + key] === value) {
  30107. return;
  30108. }
  30109. this["_" + key] = value;
  30110. this._isDirty = true;
  30111. },
  30112. enumerable: true,
  30113. configurable: true
  30114. });
  30115. };
  30116. MaterialDefines.prototype.rebuild = function () {
  30117. if (this._keys) {
  30118. delete this._keys;
  30119. }
  30120. this._keys = [];
  30121. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30122. var key = _a[_i];
  30123. if (key[0] === "_") {
  30124. continue;
  30125. }
  30126. this._keys.push(key);
  30127. if (!this._trackIsDirty) {
  30128. continue;
  30129. }
  30130. if (Object.getOwnPropertyDescriptor(this, key).get) {
  30131. continue;
  30132. }
  30133. this._reBind(key);
  30134. }
  30135. };
  30136. MaterialDefines.prototype.isEqual = function (other) {
  30137. if (this._keys.length !== other._keys.length) {
  30138. return false;
  30139. }
  30140. for (var index = 0; index < this._keys.length; index++) {
  30141. var prop = this._keys[index];
  30142. if (this[prop] !== other[prop]) {
  30143. return false;
  30144. }
  30145. }
  30146. return true;
  30147. };
  30148. MaterialDefines.prototype.cloneTo = function (other) {
  30149. if (this._keys.length !== other._keys.length) {
  30150. other._keys = this._keys.slice(0);
  30151. }
  30152. for (var index = 0; index < this._keys.length; index++) {
  30153. var prop = this._keys[index];
  30154. other[prop] = this[prop];
  30155. }
  30156. };
  30157. MaterialDefines.prototype.reset = function () {
  30158. for (var index = 0; index < this._keys.length; index++) {
  30159. var prop = this._keys[index];
  30160. if (typeof (this[prop]) === "number") {
  30161. this[prop] = 0;
  30162. }
  30163. else {
  30164. this[prop] = false;
  30165. }
  30166. }
  30167. };
  30168. MaterialDefines.prototype.toString = function () {
  30169. var result = "";
  30170. for (var index = 0; index < this._keys.length; index++) {
  30171. var prop = this._keys[index];
  30172. var value = this[prop];
  30173. if (typeof (value) === "number") {
  30174. result += "#define " + prop + " " + this[prop] + "\n";
  30175. }
  30176. else if (value) {
  30177. result += "#define " + prop + "\n";
  30178. }
  30179. }
  30180. return result;
  30181. };
  30182. return MaterialDefines;
  30183. }());
  30184. BABYLON.MaterialDefines = MaterialDefines;
  30185. var Material = (function () {
  30186. function Material(name, scene, doNotAdd) {
  30187. this.checkReadyOnEveryCall = false;
  30188. this.checkReadyOnlyOnce = false;
  30189. this.state = "";
  30190. this.alpha = 1.0;
  30191. this._backFaceCulling = true;
  30192. this.doNotSerialize = false;
  30193. this.storeEffectOnSubMeshes = false;
  30194. /**
  30195. * An event triggered when the material is disposed.
  30196. * @type {BABYLON.Observable}
  30197. */
  30198. this.onDisposeObservable = new BABYLON.Observable();
  30199. /**
  30200. * An event triggered when the material is bound.
  30201. * @type {BABYLON.Observable}
  30202. */
  30203. this.onBindObservable = new BABYLON.Observable();
  30204. /**
  30205. * An event triggered when the material is unbound.
  30206. * @type {BABYLON.Observable}
  30207. */
  30208. this.onUnBindObservable = new BABYLON.Observable();
  30209. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30210. this.disableDepthWrite = false;
  30211. this._fogEnabled = true;
  30212. this.pointSize = 1.0;
  30213. this.zOffset = 0;
  30214. this._wasPreviouslyReady = false;
  30215. this._fillMode = Material.TriangleFillMode;
  30216. this.name = name;
  30217. this.id = name;
  30218. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30219. if (this._scene.useRightHandedSystem) {
  30220. this.sideOrientation = Material.ClockWiseSideOrientation;
  30221. }
  30222. else {
  30223. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30224. }
  30225. if (!doNotAdd) {
  30226. this._scene.materials.push(this);
  30227. }
  30228. }
  30229. Object.defineProperty(Material, "TriangleFillMode", {
  30230. get: function () {
  30231. return Material._TriangleFillMode;
  30232. },
  30233. enumerable: true,
  30234. configurable: true
  30235. });
  30236. Object.defineProperty(Material, "WireFrameFillMode", {
  30237. get: function () {
  30238. return Material._WireFrameFillMode;
  30239. },
  30240. enumerable: true,
  30241. configurable: true
  30242. });
  30243. Object.defineProperty(Material, "PointFillMode", {
  30244. get: function () {
  30245. return Material._PointFillMode;
  30246. },
  30247. enumerable: true,
  30248. configurable: true
  30249. });
  30250. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30251. get: function () {
  30252. return Material._ClockWiseSideOrientation;
  30253. },
  30254. enumerable: true,
  30255. configurable: true
  30256. });
  30257. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30258. get: function () {
  30259. return Material._CounterClockWiseSideOrientation;
  30260. },
  30261. enumerable: true,
  30262. configurable: true
  30263. });
  30264. Object.defineProperty(Material, "TextureDirtyFlag", {
  30265. get: function () {
  30266. return Material._TextureDirtyFlag;
  30267. },
  30268. enumerable: true,
  30269. configurable: true
  30270. });
  30271. Object.defineProperty(Material, "LightDirtyFlag", {
  30272. get: function () {
  30273. return Material._LightDirtyFlag;
  30274. },
  30275. enumerable: true,
  30276. configurable: true
  30277. });
  30278. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30279. get: function () {
  30280. return Material._FresnelDirtyFlag;
  30281. },
  30282. enumerable: true,
  30283. configurable: true
  30284. });
  30285. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30286. get: function () {
  30287. return Material._AttributesDirtyFlag;
  30288. },
  30289. enumerable: true,
  30290. configurable: true
  30291. });
  30292. Object.defineProperty(Material, "MiscDirtyFlag", {
  30293. get: function () {
  30294. return Material._MiscDirtyFlag;
  30295. },
  30296. enumerable: true,
  30297. configurable: true
  30298. });
  30299. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30300. get: function () {
  30301. return this._backFaceCulling;
  30302. },
  30303. set: function (value) {
  30304. if (this._backFaceCulling === value) {
  30305. return;
  30306. }
  30307. this._backFaceCulling = value;
  30308. this.markAsDirty(Material.TextureDirtyFlag);
  30309. },
  30310. enumerable: true,
  30311. configurable: true
  30312. });
  30313. Object.defineProperty(Material.prototype, "onDispose", {
  30314. set: function (callback) {
  30315. if (this._onDisposeObserver) {
  30316. this.onDisposeObservable.remove(this._onDisposeObserver);
  30317. }
  30318. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30319. },
  30320. enumerable: true,
  30321. configurable: true
  30322. });
  30323. Object.defineProperty(Material.prototype, "onBind", {
  30324. set: function (callback) {
  30325. if (this._onBindObserver) {
  30326. this.onBindObservable.remove(this._onBindObserver);
  30327. }
  30328. this._onBindObserver = this.onBindObservable.add(callback);
  30329. },
  30330. enumerable: true,
  30331. configurable: true
  30332. });
  30333. Object.defineProperty(Material.prototype, "fogEnabled", {
  30334. get: function () {
  30335. return this._fogEnabled;
  30336. },
  30337. set: function (value) {
  30338. if (this._fogEnabled === value) {
  30339. return;
  30340. }
  30341. this._fogEnabled = value;
  30342. this.markAsDirty(Material.MiscDirtyFlag);
  30343. },
  30344. enumerable: true,
  30345. configurable: true
  30346. });
  30347. Object.defineProperty(Material.prototype, "wireframe", {
  30348. get: function () {
  30349. return this._fillMode === Material.WireFrameFillMode;
  30350. },
  30351. set: function (value) {
  30352. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30353. },
  30354. enumerable: true,
  30355. configurable: true
  30356. });
  30357. Object.defineProperty(Material.prototype, "pointsCloud", {
  30358. get: function () {
  30359. return this._fillMode === Material.PointFillMode;
  30360. },
  30361. set: function (value) {
  30362. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30363. },
  30364. enumerable: true,
  30365. configurable: true
  30366. });
  30367. Object.defineProperty(Material.prototype, "fillMode", {
  30368. get: function () {
  30369. return this._fillMode;
  30370. },
  30371. set: function (value) {
  30372. if (this._fillMode === value) {
  30373. return;
  30374. }
  30375. this._fillMode = value;
  30376. this.markAsDirty(Material.MiscDirtyFlag);
  30377. },
  30378. enumerable: true,
  30379. configurable: true
  30380. });
  30381. /**
  30382. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30383. * subclasses should override adding information pertainent to themselves
  30384. */
  30385. Material.prototype.toString = function (fullDetails) {
  30386. var ret = "Name: " + this.name;
  30387. if (fullDetails) {
  30388. }
  30389. return ret;
  30390. };
  30391. /**
  30392. * Child classes can use it to update shaders
  30393. */
  30394. Material.prototype.markAsDirty = function (flag) {
  30395. };
  30396. Material.prototype.getClassName = function () {
  30397. return "Material";
  30398. };
  30399. Object.defineProperty(Material.prototype, "isFrozen", {
  30400. get: function () {
  30401. return this.checkReadyOnlyOnce;
  30402. },
  30403. enumerable: true,
  30404. configurable: true
  30405. });
  30406. Material.prototype.freeze = function () {
  30407. this.checkReadyOnlyOnce = true;
  30408. };
  30409. Material.prototype.unfreeze = function () {
  30410. this.checkReadyOnlyOnce = false;
  30411. };
  30412. Material.prototype.isReady = function (mesh, useInstances) {
  30413. return true;
  30414. };
  30415. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30416. return false;
  30417. };
  30418. Material.prototype.getEffect = function () {
  30419. return this._effect;
  30420. };
  30421. Material.prototype.getScene = function () {
  30422. return this._scene;
  30423. };
  30424. Material.prototype.needAlphaBlending = function () {
  30425. return (this.alpha < 1.0);
  30426. };
  30427. Material.prototype.needAlphaTesting = function () {
  30428. return false;
  30429. };
  30430. Material.prototype.getAlphaTestTexture = function () {
  30431. return null;
  30432. };
  30433. Material.prototype.markDirty = function () {
  30434. this._wasPreviouslyReady = false;
  30435. };
  30436. Material.prototype._preBind = function (effect) {
  30437. var engine = this._scene.getEngine();
  30438. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  30439. engine.enableEffect(effect ? effect : this._effect);
  30440. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30441. };
  30442. Material.prototype.bind = function (world, mesh) {
  30443. this._scene._cachedMaterial = this;
  30444. this.onBindObservable.notifyObservers(mesh);
  30445. if (this.disableDepthWrite) {
  30446. var engine = this._scene.getEngine();
  30447. this._cachedDepthWriteState = engine.getDepthWrite();
  30448. engine.setDepthWrite(false);
  30449. }
  30450. };
  30451. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30452. };
  30453. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30454. };
  30455. Material.prototype.unbind = function () {
  30456. this.onUnBindObservable.notifyObservers(this);
  30457. if (this.disableDepthWrite) {
  30458. var engine = this._scene.getEngine();
  30459. engine.setDepthWrite(this._cachedDepthWriteState);
  30460. }
  30461. };
  30462. Material.prototype.clone = function (name) {
  30463. return null;
  30464. };
  30465. Material.prototype.getBindedMeshes = function () {
  30466. var result = new Array();
  30467. for (var index = 0; index < this._scene.meshes.length; index++) {
  30468. var mesh = this._scene.meshes[index];
  30469. if (mesh.material === this) {
  30470. result.push(mesh);
  30471. }
  30472. }
  30473. return result;
  30474. };
  30475. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30476. // Animations
  30477. this.getScene().stopAnimation(this);
  30478. // Remove from scene
  30479. var index = this._scene.materials.indexOf(this);
  30480. if (index >= 0) {
  30481. this._scene.materials.splice(index, 1);
  30482. }
  30483. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  30484. if (forceDisposeEffect && this._effect) {
  30485. this._scene.getEngine()._releaseEffect(this._effect);
  30486. this._effect = null;
  30487. }
  30488. // Remove from meshes
  30489. for (index = 0; index < this._scene.meshes.length; index++) {
  30490. var mesh = this._scene.meshes[index];
  30491. if (mesh.material === this) {
  30492. mesh.material = null;
  30493. }
  30494. }
  30495. // Callback
  30496. this.onDisposeObservable.notifyObservers(this);
  30497. this.onDisposeObservable.clear();
  30498. this.onBindObservable.clear();
  30499. this.onUnBindObservable.clear();
  30500. };
  30501. Material.prototype.serialize = function () {
  30502. return BABYLON.SerializationHelper.Serialize(this);
  30503. };
  30504. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  30505. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  30506. multiMaterial.id = parsedMultiMaterial.id;
  30507. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  30508. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  30509. var subMatId = parsedMultiMaterial.materials[matIndex];
  30510. if (subMatId) {
  30511. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  30512. }
  30513. else {
  30514. multiMaterial.subMaterials.push(null);
  30515. }
  30516. }
  30517. return multiMaterial;
  30518. };
  30519. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  30520. if (!parsedMaterial.customType) {
  30521. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  30522. }
  30523. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  30524. return materialType.Parse(parsedMaterial, scene, rootUrl);
  30525. ;
  30526. };
  30527. return Material;
  30528. }());
  30529. Material._TriangleFillMode = 0;
  30530. Material._WireFrameFillMode = 1;
  30531. Material._PointFillMode = 2;
  30532. Material._ClockWiseSideOrientation = 0;
  30533. Material._CounterClockWiseSideOrientation = 1;
  30534. Material._TextureDirtyFlag = 0;
  30535. Material._LightDirtyFlag = 1;
  30536. Material._FresnelDirtyFlag = 2;
  30537. Material._AttributesDirtyFlag = 4;
  30538. Material._MiscDirtyFlag = 8;
  30539. __decorate([
  30540. BABYLON.serialize()
  30541. ], Material.prototype, "id", void 0);
  30542. __decorate([
  30543. BABYLON.serialize()
  30544. ], Material.prototype, "name", void 0);
  30545. __decorate([
  30546. BABYLON.serialize()
  30547. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  30548. __decorate([
  30549. BABYLON.serialize()
  30550. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  30551. __decorate([
  30552. BABYLON.serialize()
  30553. ], Material.prototype, "state", void 0);
  30554. __decorate([
  30555. BABYLON.serialize()
  30556. ], Material.prototype, "alpha", void 0);
  30557. __decorate([
  30558. BABYLON.serialize("backFaceCulling")
  30559. ], Material.prototype, "_backFaceCulling", void 0);
  30560. __decorate([
  30561. BABYLON.serialize()
  30562. ], Material.prototype, "sideOrientation", void 0);
  30563. __decorate([
  30564. BABYLON.serialize()
  30565. ], Material.prototype, "alphaMode", void 0);
  30566. __decorate([
  30567. BABYLON.serialize()
  30568. ], Material.prototype, "disableDepthWrite", void 0);
  30569. __decorate([
  30570. BABYLON.serialize("fogEnabled")
  30571. ], Material.prototype, "_fogEnabled", void 0);
  30572. __decorate([
  30573. BABYLON.serialize()
  30574. ], Material.prototype, "pointSize", void 0);
  30575. __decorate([
  30576. BABYLON.serialize()
  30577. ], Material.prototype, "zOffset", void 0);
  30578. __decorate([
  30579. BABYLON.serialize()
  30580. ], Material.prototype, "wireframe", null);
  30581. __decorate([
  30582. BABYLON.serialize()
  30583. ], Material.prototype, "pointsCloud", null);
  30584. __decorate([
  30585. BABYLON.serialize()
  30586. ], Material.prototype, "fillMode", null);
  30587. BABYLON.Material = Material;
  30588. })(BABYLON || (BABYLON = {}));
  30589. //# sourceMappingURL=babylon.material.js.map
  30590. var BABYLON;
  30591. (function (BABYLON) {
  30592. var StandardMaterialDefines = (function (_super) {
  30593. __extends(StandardMaterialDefines, _super);
  30594. function StandardMaterialDefines() {
  30595. var _this = _super.call(this, true) || this;
  30596. _this.DIFFUSE = false;
  30597. _this.AMBIENT = false;
  30598. _this.OPACITY = false;
  30599. _this.OPACITYRGB = false;
  30600. _this.REFLECTION = false;
  30601. _this.EMISSIVE = false;
  30602. _this.SPECULAR = false;
  30603. _this.BUMP = false;
  30604. _this.PARALLAX = false;
  30605. _this.PARALLAXOCCLUSION = false;
  30606. _this.SPECULAROVERALPHA = false;
  30607. _this.CLIPPLANE = false;
  30608. _this.ALPHATEST = false;
  30609. _this.ALPHAFROMDIFFUSE = false;
  30610. _this.POINTSIZE = false;
  30611. _this.FOG = false;
  30612. _this.SPECULARTERM = false;
  30613. _this.DIFFUSEFRESNEL = false;
  30614. _this.OPACITYFRESNEL = false;
  30615. _this.REFLECTIONFRESNEL = false;
  30616. _this.REFRACTIONFRESNEL = false;
  30617. _this.EMISSIVEFRESNEL = false;
  30618. _this.FRESNEL = false;
  30619. _this.NORMAL = false;
  30620. _this.UV1 = false;
  30621. _this.UV2 = false;
  30622. _this.VERTEXCOLOR = false;
  30623. _this.VERTEXALPHA = false;
  30624. _this.NUM_BONE_INFLUENCERS = 0;
  30625. _this.BonesPerMesh = 0;
  30626. _this.INSTANCES = false;
  30627. _this.GLOSSINESS = false;
  30628. _this.ROUGHNESS = false;
  30629. _this.EMISSIVEASILLUMINATION = false;
  30630. _this.LINKEMISSIVEWITHDIFFUSE = false;
  30631. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  30632. _this.LIGHTMAP = false;
  30633. _this.USELIGHTMAPASSHADOWMAP = false;
  30634. _this.REFLECTIONMAP_3D = false;
  30635. _this.REFLECTIONMAP_SPHERICAL = false;
  30636. _this.REFLECTIONMAP_PLANAR = false;
  30637. _this.REFLECTIONMAP_CUBIC = false;
  30638. _this.REFLECTIONMAP_PROJECTION = false;
  30639. _this.REFLECTIONMAP_SKYBOX = false;
  30640. _this.REFLECTIONMAP_EXPLICIT = false;
  30641. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30642. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30643. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30644. _this.INVERTCUBICMAP = false;
  30645. _this.LOGARITHMICDEPTH = false;
  30646. _this.REFRACTION = false;
  30647. _this.REFRACTIONMAP_3D = false;
  30648. _this.REFLECTIONOVERALPHA = false;
  30649. _this.INVERTNORMALMAPX = false;
  30650. _this.INVERTNORMALMAPY = false;
  30651. _this.TWOSIDEDLIGHTING = false;
  30652. _this.SHADOWFULLFLOAT = false;
  30653. _this.CAMERACOLORGRADING = false;
  30654. _this.CAMERACOLORCURVES = false;
  30655. _this._areTexturesDirty = true;
  30656. _this._areFresnelDirty = true;
  30657. _this._areMiscDirty = true;
  30658. _this.rebuild();
  30659. return _this;
  30660. }
  30661. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  30662. var modes = [
  30663. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  30664. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  30665. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  30666. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  30667. ];
  30668. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  30669. var mode = modes_1[_i];
  30670. this[mode] = (mode === modeToEnable);
  30671. }
  30672. };
  30673. return StandardMaterialDefines;
  30674. }(BABYLON.MaterialDefines));
  30675. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  30676. var StandardMaterial = (function (_super) {
  30677. __extends(StandardMaterial, _super);
  30678. function StandardMaterial(name, scene) {
  30679. var _this = _super.call(this, name, scene) || this;
  30680. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30681. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  30682. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  30683. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30684. _this.specularPower = 64;
  30685. _this._useAlphaFromDiffuseTexture = false;
  30686. _this._useEmissiveAsIllumination = false;
  30687. _this._linkEmissiveWithDiffuse = false;
  30688. _this._useSpecularOverAlpha = false;
  30689. _this._useReflectionOverAlpha = false;
  30690. _this._disableLighting = false;
  30691. _this._useParallax = false;
  30692. _this._useParallaxOcclusion = false;
  30693. _this.parallaxScaleBias = 0.05;
  30694. _this._roughness = 0;
  30695. _this.indexOfRefraction = 0.98;
  30696. _this.invertRefractionY = true;
  30697. _this._useLightmapAsShadowmap = false;
  30698. _this._useReflectionFresnelFromSpecular = false;
  30699. _this._useGlossinessFromSpecularMapAlpha = false;
  30700. _this._maxSimultaneousLights = 4;
  30701. /**
  30702. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30703. */
  30704. _this._invertNormalMapX = false;
  30705. /**
  30706. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30707. */
  30708. _this._invertNormalMapY = false;
  30709. /**
  30710. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30711. */
  30712. _this._twoSidedLighting = false;
  30713. /**
  30714. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30715. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30716. * 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;
  30717. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30718. */
  30719. _this._cameraColorCurves = null;
  30720. _this._renderTargets = new BABYLON.SmartArray(16);
  30721. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30722. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30723. _this.storeEffectOnSubMeshes = true;
  30724. _this.getRenderTargetTextures = function () {
  30725. _this._renderTargets.reset();
  30726. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  30727. _this._renderTargets.push(_this._reflectionTexture);
  30728. }
  30729. if (_this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  30730. _this._renderTargets.push(_this._refractionTexture);
  30731. }
  30732. return _this._renderTargets;
  30733. };
  30734. return _this;
  30735. }
  30736. Object.defineProperty(StandardMaterial.prototype, "diffuseTexture", {
  30737. get: function () {
  30738. return this._diffuseTexture;
  30739. },
  30740. set: function (value) {
  30741. if (this._diffuseTexture === value) {
  30742. return;
  30743. }
  30744. this._diffuseTexture = value;
  30745. this._markAllSubMeshesAsTexturesDirty();
  30746. },
  30747. enumerable: true,
  30748. configurable: true
  30749. });
  30750. Object.defineProperty(StandardMaterial.prototype, "ambientTexture", {
  30751. get: function () {
  30752. return this._ambientTexture;
  30753. },
  30754. set: function (value) {
  30755. if (this._ambientTexture === value) {
  30756. return;
  30757. }
  30758. this._ambientTexture = value;
  30759. this._markAllSubMeshesAsTexturesDirty();
  30760. },
  30761. enumerable: true,
  30762. configurable: true
  30763. });
  30764. Object.defineProperty(StandardMaterial.prototype, "opacityTexture", {
  30765. get: function () {
  30766. return this._opacityTexture;
  30767. },
  30768. set: function (value) {
  30769. if (this._opacityTexture === value) {
  30770. return;
  30771. }
  30772. this._opacityTexture = value;
  30773. this._markAllSubMeshesAsTexturesDirty();
  30774. },
  30775. enumerable: true,
  30776. configurable: true
  30777. });
  30778. Object.defineProperty(StandardMaterial.prototype, "reflectionTexture", {
  30779. get: function () {
  30780. return this._reflectionTexture;
  30781. },
  30782. set: function (value) {
  30783. if (this._reflectionTexture === value) {
  30784. return;
  30785. }
  30786. this._reflectionTexture = value;
  30787. this._markAllSubMeshesAsTexturesDirty();
  30788. },
  30789. enumerable: true,
  30790. configurable: true
  30791. });
  30792. Object.defineProperty(StandardMaterial.prototype, "emissiveTexture", {
  30793. get: function () {
  30794. return this._emissiveTexture;
  30795. },
  30796. set: function (value) {
  30797. if (this._emissiveTexture === value) {
  30798. return;
  30799. }
  30800. this._emissiveTexture = value;
  30801. this._markAllSubMeshesAsTexturesDirty();
  30802. },
  30803. enumerable: true,
  30804. configurable: true
  30805. });
  30806. Object.defineProperty(StandardMaterial.prototype, "specularTexture", {
  30807. get: function () {
  30808. return this._specularTexture;
  30809. },
  30810. set: function (value) {
  30811. if (this._specularTexture === value) {
  30812. return;
  30813. }
  30814. this._specularTexture = value;
  30815. this._markAllSubMeshesAsTexturesDirty();
  30816. },
  30817. enumerable: true,
  30818. configurable: true
  30819. });
  30820. Object.defineProperty(StandardMaterial.prototype, "bumpTexture", {
  30821. get: function () {
  30822. return this._bumpTexture;
  30823. },
  30824. set: function (value) {
  30825. if (this._bumpTexture === value) {
  30826. return;
  30827. }
  30828. this._bumpTexture = value;
  30829. this._markAllSubMeshesAsTexturesDirty();
  30830. },
  30831. enumerable: true,
  30832. configurable: true
  30833. });
  30834. Object.defineProperty(StandardMaterial.prototype, "lightmapTexture", {
  30835. get: function () {
  30836. return this._lightmapTexture;
  30837. },
  30838. set: function (value) {
  30839. if (this._lightmapTexture === value) {
  30840. return;
  30841. }
  30842. this._lightmapTexture = value;
  30843. this._markAllSubMeshesAsTexturesDirty();
  30844. },
  30845. enumerable: true,
  30846. configurable: true
  30847. });
  30848. Object.defineProperty(StandardMaterial.prototype, "refractionTexture", {
  30849. get: function () {
  30850. return this._refractionTexture;
  30851. },
  30852. set: function (value) {
  30853. if (this._refractionTexture === value) {
  30854. return;
  30855. }
  30856. this._refractionTexture = value;
  30857. this._markAllSubMeshesAsTexturesDirty();
  30858. },
  30859. enumerable: true,
  30860. configurable: true
  30861. });
  30862. Object.defineProperty(StandardMaterial.prototype, "useAlphaFromDiffuseTexture", {
  30863. get: function () {
  30864. return this._useAlphaFromDiffuseTexture;
  30865. },
  30866. set: function (value) {
  30867. if (this._useAlphaFromDiffuseTexture === value) {
  30868. return;
  30869. }
  30870. this._useAlphaFromDiffuseTexture = value;
  30871. this._markAllSubMeshesAsTexturesDirty();
  30872. },
  30873. enumerable: true,
  30874. configurable: true
  30875. });
  30876. Object.defineProperty(StandardMaterial.prototype, "useEmissiveAsIllumination", {
  30877. get: function () {
  30878. return this._useEmissiveAsIllumination;
  30879. },
  30880. set: function (value) {
  30881. if (this._useAlphaFromDiffuseTexture === value) {
  30882. return;
  30883. }
  30884. this._useEmissiveAsIllumination = value;
  30885. this._markAllSubMeshesAsTexturesDirty();
  30886. },
  30887. enumerable: true,
  30888. configurable: true
  30889. });
  30890. Object.defineProperty(StandardMaterial.prototype, "linkEmissiveWithDiffuse", {
  30891. get: function () {
  30892. return this._linkEmissiveWithDiffuse;
  30893. },
  30894. set: function (value) {
  30895. if (this._linkEmissiveWithDiffuse === value) {
  30896. return;
  30897. }
  30898. this._linkEmissiveWithDiffuse = value;
  30899. this._markAllSubMeshesAsTexturesDirty();
  30900. },
  30901. enumerable: true,
  30902. configurable: true
  30903. });
  30904. Object.defineProperty(StandardMaterial.prototype, "useSpecularOverAlpha", {
  30905. get: function () {
  30906. return this._useSpecularOverAlpha;
  30907. },
  30908. set: function (value) {
  30909. if (this._useSpecularOverAlpha === value) {
  30910. return;
  30911. }
  30912. this._useSpecularOverAlpha = value;
  30913. this._markAllSubMeshesAsTexturesDirty();
  30914. },
  30915. enumerable: true,
  30916. configurable: true
  30917. });
  30918. Object.defineProperty(StandardMaterial.prototype, "useReflectionOverAlpha", {
  30919. get: function () {
  30920. return this._useReflectionOverAlpha;
  30921. },
  30922. set: function (value) {
  30923. if (this._useReflectionOverAlpha === value) {
  30924. return;
  30925. }
  30926. this._useReflectionOverAlpha = value;
  30927. this._markAllSubMeshesAsTexturesDirty();
  30928. },
  30929. enumerable: true,
  30930. configurable: true
  30931. });
  30932. Object.defineProperty(StandardMaterial.prototype, "disableLighting", {
  30933. get: function () {
  30934. return this._disableLighting;
  30935. },
  30936. set: function (value) {
  30937. if (this._disableLighting === value) {
  30938. return;
  30939. }
  30940. this._disableLighting = value;
  30941. this._markAllSubMeshesAsLightsDirty();
  30942. },
  30943. enumerable: true,
  30944. configurable: true
  30945. });
  30946. Object.defineProperty(StandardMaterial.prototype, "useParallax", {
  30947. get: function () {
  30948. return this._useParallax;
  30949. },
  30950. set: function (value) {
  30951. if (this._useParallax === value) {
  30952. return;
  30953. }
  30954. this._useParallax = value;
  30955. this._markAllSubMeshesAsTexturesDirty();
  30956. },
  30957. enumerable: true,
  30958. configurable: true
  30959. });
  30960. Object.defineProperty(StandardMaterial.prototype, "useParallaxOcclusion", {
  30961. get: function () {
  30962. return this._useParallaxOcclusion;
  30963. },
  30964. set: function (value) {
  30965. if (this._useParallaxOcclusion === value) {
  30966. return;
  30967. }
  30968. this._useParallaxOcclusion = value;
  30969. this._markAllSubMeshesAsTexturesDirty();
  30970. },
  30971. enumerable: true,
  30972. configurable: true
  30973. });
  30974. Object.defineProperty(StandardMaterial.prototype, "roughness", {
  30975. get: function () {
  30976. return this._roughness;
  30977. },
  30978. set: function (value) {
  30979. if (this._roughness === value) {
  30980. return;
  30981. }
  30982. this._roughness = value;
  30983. this._markAllSubMeshesAsTexturesDirty();
  30984. },
  30985. enumerable: true,
  30986. configurable: true
  30987. });
  30988. Object.defineProperty(StandardMaterial.prototype, "useLightmapAsShadowmap", {
  30989. get: function () {
  30990. return this._useLightmapAsShadowmap;
  30991. },
  30992. set: function (value) {
  30993. if (this._useLightmapAsShadowmap === value) {
  30994. return;
  30995. }
  30996. this._useLightmapAsShadowmap = value;
  30997. this._markAllSubMeshesAsTexturesDirty();
  30998. },
  30999. enumerable: true,
  31000. configurable: true
  31001. });
  31002. Object.defineProperty(StandardMaterial.prototype, "diffuseFresnelParameters", {
  31003. get: function () {
  31004. return this._diffuseFresnelParameters;
  31005. },
  31006. set: function (value) {
  31007. if (this._diffuseFresnelParameters === value) {
  31008. return;
  31009. }
  31010. this._diffuseFresnelParameters = value;
  31011. this._markAllSubMeshesAsFresnelDirty();
  31012. },
  31013. enumerable: true,
  31014. configurable: true
  31015. });
  31016. Object.defineProperty(StandardMaterial.prototype, "opacityFresnelParameters", {
  31017. get: function () {
  31018. return this._opacityFresnelParameters;
  31019. },
  31020. set: function (value) {
  31021. if (this._opacityFresnelParameters === value) {
  31022. return;
  31023. }
  31024. this._opacityFresnelParameters = value;
  31025. this._markAllSubMeshesAsFresnelDirty();
  31026. },
  31027. enumerable: true,
  31028. configurable: true
  31029. });
  31030. Object.defineProperty(StandardMaterial.prototype, "reflectionFresnelParameters", {
  31031. get: function () {
  31032. return this._reflectionFresnelParameters;
  31033. },
  31034. set: function (value) {
  31035. if (this._reflectionFresnelParameters === value) {
  31036. return;
  31037. }
  31038. this._reflectionFresnelParameters = value;
  31039. this._markAllSubMeshesAsFresnelDirty();
  31040. },
  31041. enumerable: true,
  31042. configurable: true
  31043. });
  31044. Object.defineProperty(StandardMaterial.prototype, "refractionFresnelParameters", {
  31045. get: function () {
  31046. return this._refractionFresnelParameters;
  31047. },
  31048. set: function (value) {
  31049. if (this._refractionFresnelParameters === value) {
  31050. return;
  31051. }
  31052. this._refractionFresnelParameters = value;
  31053. this._markAllSubMeshesAsFresnelDirty();
  31054. },
  31055. enumerable: true,
  31056. configurable: true
  31057. });
  31058. Object.defineProperty(StandardMaterial.prototype, "emissiveFresnelParameters", {
  31059. get: function () {
  31060. return this._emissiveFresnelParameters;
  31061. },
  31062. set: function (value) {
  31063. if (this._emissiveFresnelParameters === value) {
  31064. return;
  31065. }
  31066. this._emissiveFresnelParameters = value;
  31067. this._markAllSubMeshesAsFresnelDirty();
  31068. },
  31069. enumerable: true,
  31070. configurable: true
  31071. });
  31072. Object.defineProperty(StandardMaterial.prototype, "useReflectionFresnelFromSpecular", {
  31073. get: function () {
  31074. return this._useReflectionFresnelFromSpecular;
  31075. },
  31076. set: function (value) {
  31077. if (this._useReflectionFresnelFromSpecular === value) {
  31078. return;
  31079. }
  31080. this._useReflectionFresnelFromSpecular = value;
  31081. this._markAllSubMeshesAsFresnelDirty();
  31082. },
  31083. enumerable: true,
  31084. configurable: true
  31085. });
  31086. Object.defineProperty(StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", {
  31087. get: function () {
  31088. return this._useGlossinessFromSpecularMapAlpha;
  31089. },
  31090. set: function (value) {
  31091. if (this._useGlossinessFromSpecularMapAlpha === value) {
  31092. return;
  31093. }
  31094. this._useGlossinessFromSpecularMapAlpha = value;
  31095. this._markAllSubMeshesAsTexturesDirty();
  31096. },
  31097. enumerable: true,
  31098. configurable: true
  31099. });
  31100. Object.defineProperty(StandardMaterial.prototype, "maxSimultaneousLights", {
  31101. get: function () {
  31102. return this._maxSimultaneousLights;
  31103. },
  31104. set: function (value) {
  31105. if (this._maxSimultaneousLights === value) {
  31106. return;
  31107. }
  31108. this._maxSimultaneousLights = value;
  31109. this._markAllSubMeshesAsLightsDirty();
  31110. },
  31111. enumerable: true,
  31112. configurable: true
  31113. });
  31114. Object.defineProperty(StandardMaterial.prototype, "invertNormalMapX", {
  31115. get: function () {
  31116. return this._invertNormalMapX;
  31117. },
  31118. set: function (value) {
  31119. if (this._invertNormalMapX === value) {
  31120. return;
  31121. }
  31122. this._invertNormalMapX = value;
  31123. this._markAllSubMeshesAsTexturesDirty();
  31124. },
  31125. enumerable: true,
  31126. configurable: true
  31127. });
  31128. Object.defineProperty(StandardMaterial.prototype, "invertNormalMapY", {
  31129. get: function () {
  31130. return this._invertNormalMapY;
  31131. },
  31132. set: function (value) {
  31133. if (this._invertNormalMapY === value) {
  31134. return;
  31135. }
  31136. this._invertNormalMapY = value;
  31137. this._markAllSubMeshesAsTexturesDirty();
  31138. },
  31139. enumerable: true,
  31140. configurable: true
  31141. });
  31142. Object.defineProperty(StandardMaterial.prototype, "twoSidedLighting", {
  31143. set: function (value) {
  31144. if (this._twoSidedLighting === value) {
  31145. return;
  31146. }
  31147. this._twoSidedLighting = value;
  31148. this._markAllSubMeshesAsTexturesDirty();
  31149. },
  31150. enumerable: true,
  31151. configurable: true
  31152. });
  31153. Object.defineProperty(StandardMaterial.prototype, "inverttwoSidedLightingNormalMapY", {
  31154. get: function () {
  31155. return this._twoSidedLighting;
  31156. },
  31157. enumerable: true,
  31158. configurable: true
  31159. });
  31160. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  31161. get: function () {
  31162. return this._cameraColorGradingTexture;
  31163. },
  31164. set: function (value) {
  31165. if (this._cameraColorGradingTexture === value) {
  31166. return;
  31167. }
  31168. this._cameraColorGradingTexture = value;
  31169. this._markAllSubMeshesAsTexturesDirty();
  31170. },
  31171. enumerable: true,
  31172. configurable: true
  31173. });
  31174. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  31175. get: function () {
  31176. return this._cameraColorCurves;
  31177. },
  31178. set: function (value) {
  31179. if (this._cameraColorCurves === value) {
  31180. return;
  31181. }
  31182. this._cameraColorCurves = value;
  31183. this._markAllSubMeshesAsTexturesDirty();
  31184. },
  31185. enumerable: true,
  31186. configurable: true
  31187. });
  31188. StandardMaterial.prototype.getClassName = function () {
  31189. return "StandardMaterial";
  31190. };
  31191. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  31192. get: function () {
  31193. return this._useLogarithmicDepth;
  31194. },
  31195. set: function (value) {
  31196. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  31197. this._markAllSubMeshesAsMiscDirty();
  31198. },
  31199. enumerable: true,
  31200. configurable: true
  31201. });
  31202. StandardMaterial.prototype.needAlphaBlending = function () {
  31203. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  31204. };
  31205. StandardMaterial.prototype.needAlphaTesting = function () {
  31206. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  31207. };
  31208. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  31209. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  31210. };
  31211. StandardMaterial.prototype.getAlphaTestTexture = function () {
  31212. return this.diffuseTexture;
  31213. };
  31214. /**
  31215. * Child classes can use it to update shaders
  31216. */
  31217. StandardMaterial.prototype.markAsDirty = function (flag) {
  31218. if (flag & BABYLON.Material.TextureDirtyFlag) {
  31219. this._markAllSubMeshesAsTexturesDirty();
  31220. }
  31221. if (flag & BABYLON.Material.LightDirtyFlag) {
  31222. this._markAllSubMeshesAsLightsDirty();
  31223. }
  31224. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  31225. this._markAllSubMeshesAsFresnelDirty();
  31226. }
  31227. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  31228. this._markAllSubMeshesAsAttributesDirty();
  31229. }
  31230. if (flag & BABYLON.Material.MiscDirtyFlag) {
  31231. this._markAllSubMeshesAsMiscDirty();
  31232. }
  31233. };
  31234. StandardMaterial.prototype.getEffect = function () {
  31235. return this._activeEffect;
  31236. };
  31237. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  31238. if (!mesh) {
  31239. return false;
  31240. }
  31241. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  31242. };
  31243. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31244. if (this.isFrozen) {
  31245. if (this._wasPreviouslyReady) {
  31246. return true;
  31247. }
  31248. }
  31249. if (!subMesh._materialDefines) {
  31250. subMesh._materialDefines = new StandardMaterialDefines();
  31251. }
  31252. var defines = subMesh._materialDefines;
  31253. var scene = this.getScene();
  31254. var engine = scene.getEngine();
  31255. // Lights
  31256. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, this._maxSimultaneousLights, this._disableLighting);
  31257. defines._areLightsDirty = false;
  31258. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  31259. if (defines._renderId === scene.getRenderId()) {
  31260. return true;
  31261. }
  31262. }
  31263. // Textures
  31264. if (defines._areTexturesDirty) {
  31265. defines._needUVs = false;
  31266. if (scene.texturesEnabled) {
  31267. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31268. if (!this._diffuseTexture.isReady()) {
  31269. return false;
  31270. }
  31271. else {
  31272. defines._needUVs = true;
  31273. defines.DIFFUSE = true;
  31274. }
  31275. }
  31276. else {
  31277. defines.DIFFUSE = false;
  31278. }
  31279. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31280. if (!this._ambientTexture.isReady()) {
  31281. return false;
  31282. }
  31283. else {
  31284. defines._needUVs = true;
  31285. defines.AMBIENT = true;
  31286. }
  31287. }
  31288. else {
  31289. defines.AMBIENT = false;
  31290. }
  31291. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31292. if (!this._opacityTexture.isReady()) {
  31293. return false;
  31294. }
  31295. else {
  31296. defines._needUVs = true;
  31297. defines.OPACITY = true;
  31298. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  31299. }
  31300. }
  31301. else {
  31302. defines.OPACITY = false;
  31303. }
  31304. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31305. if (!this._reflectionTexture.isReady()) {
  31306. return false;
  31307. }
  31308. else {
  31309. defines._needNormals = true;
  31310. defines.REFLECTION = true;
  31311. defines.ROUGHNESS = (this._roughness > 0);
  31312. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  31313. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  31314. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  31315. switch (this._reflectionTexture.coordinatesMode) {
  31316. case BABYLON.Texture.CUBIC_MODE:
  31317. case BABYLON.Texture.INVCUBIC_MODE:
  31318. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  31319. break;
  31320. case BABYLON.Texture.EXPLICIT_MODE:
  31321. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  31322. break;
  31323. case BABYLON.Texture.PLANAR_MODE:
  31324. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  31325. break;
  31326. case BABYLON.Texture.PROJECTION_MODE:
  31327. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  31328. break;
  31329. case BABYLON.Texture.SKYBOX_MODE:
  31330. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  31331. break;
  31332. case BABYLON.Texture.SPHERICAL_MODE:
  31333. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  31334. break;
  31335. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  31336. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  31337. break;
  31338. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  31339. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  31340. break;
  31341. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  31342. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  31343. break;
  31344. }
  31345. }
  31346. }
  31347. else {
  31348. defines.REFLECTION = false;
  31349. }
  31350. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31351. if (!this._emissiveTexture.isReady()) {
  31352. return false;
  31353. }
  31354. else {
  31355. defines._needUVs = true;
  31356. defines.EMISSIVE = true;
  31357. }
  31358. }
  31359. else {
  31360. defines.EMISSIVE = false;
  31361. }
  31362. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31363. if (!this._lightmapTexture.isReady()) {
  31364. return false;
  31365. }
  31366. else {
  31367. defines._needUVs = true;
  31368. defines.LIGHTMAP = true;
  31369. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  31370. }
  31371. }
  31372. else {
  31373. defines.LIGHTMAP = false;
  31374. }
  31375. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31376. if (!this._specularTexture.isReady()) {
  31377. return false;
  31378. }
  31379. else {
  31380. defines._needUVs = true;
  31381. defines.SPECULAR = true;
  31382. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  31383. }
  31384. }
  31385. else {
  31386. defines.SPECULAR = false;
  31387. }
  31388. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  31389. if (!this._bumpTexture.isReady()) {
  31390. return false;
  31391. }
  31392. else {
  31393. defines._needUVs = true;
  31394. defines.BUMP = true;
  31395. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  31396. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  31397. defines.PARALLAX = this._useParallax;
  31398. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  31399. }
  31400. }
  31401. else {
  31402. defines.BUMP = false;
  31403. }
  31404. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31405. if (!this._refractionTexture.isReady()) {
  31406. return false;
  31407. }
  31408. else {
  31409. defines._needUVs = true;
  31410. defines.REFRACTION = true;
  31411. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  31412. }
  31413. }
  31414. else {
  31415. defines.REFRACTION = false;
  31416. }
  31417. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  31418. if (!this._cameraColorGradingTexture.isReady()) {
  31419. return false;
  31420. }
  31421. else {
  31422. defines.CAMERACOLORGRADING = true;
  31423. }
  31424. }
  31425. else {
  31426. defines.CAMERACOLORGRADING = false;
  31427. }
  31428. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  31429. }
  31430. else {
  31431. defines.DIFFUSE = false;
  31432. defines.AMBIENT = false;
  31433. defines.OPACITY = false;
  31434. defines.REFLECTION = false;
  31435. defines.EMISSIVE = false;
  31436. defines.LIGHTMAP = false;
  31437. defines.BUMP = false;
  31438. defines.REFRACTION = false;
  31439. defines.CAMERACOLORGRADING = false;
  31440. }
  31441. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  31442. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  31443. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  31444. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  31445. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  31446. defines._areTexturesDirty = false;
  31447. }
  31448. if (defines._areFresnelDirty) {
  31449. if (StandardMaterial.FresnelEnabled) {
  31450. // Fresnel
  31451. if (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled ||
  31452. this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  31453. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled ||
  31454. this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled ||
  31455. this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled) {
  31456. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  31457. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  31458. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  31459. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  31460. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  31461. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  31462. defines._needNormals = true;
  31463. defines.FRESNEL = true;
  31464. }
  31465. }
  31466. else {
  31467. defines.FRESNEL = false;
  31468. }
  31469. defines._areFresnelDirty = false;
  31470. }
  31471. // Misc.
  31472. if (defines._areMiscDirty) {
  31473. defines.LOGARITHMICDEPTH = this._useLogarithmicDepth;
  31474. defines.POINTSIZE = (this.pointsCloud || scene.forcePointsCloud);
  31475. defines.FOG = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled);
  31476. defines._areMiscDirty = false;
  31477. }
  31478. // Attribs
  31479. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, useInstances);
  31480. defines._areAttributesDirty = false;
  31481. // Values that need to be evaluated on every frame
  31482. defines.CLIPPLANE = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  31483. defines.ALPHATEST = engine.getAlphaTesting();
  31484. defines.INSTANCES = useInstances;
  31485. if (scene._mirroredCameraPosition && defines.BUMP) {
  31486. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  31487. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  31488. }
  31489. // Get correct effect
  31490. if (defines._isDirty) {
  31491. defines._isDirty = false;
  31492. scene.resetCachedMaterial();
  31493. // Fallbacks
  31494. var fallbacks = new BABYLON.EffectFallbacks();
  31495. if (defines.REFLECTION) {
  31496. fallbacks.addFallback(0, "REFLECTION");
  31497. }
  31498. if (defines.SPECULAR) {
  31499. fallbacks.addFallback(0, "SPECULAR");
  31500. }
  31501. if (defines.BUMP) {
  31502. fallbacks.addFallback(0, "BUMP");
  31503. }
  31504. if (defines.PARALLAX) {
  31505. fallbacks.addFallback(1, "PARALLAX");
  31506. }
  31507. if (defines.PARALLAXOCCLUSION) {
  31508. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  31509. }
  31510. if (defines.SPECULAROVERALPHA) {
  31511. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  31512. }
  31513. if (defines.FOG) {
  31514. fallbacks.addFallback(1, "FOG");
  31515. }
  31516. if (defines.POINTSIZE) {
  31517. fallbacks.addFallback(0, "POINTSIZE");
  31518. }
  31519. if (defines.LOGARITHMICDEPTH) {
  31520. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  31521. }
  31522. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  31523. if (defines.SPECULARTERM) {
  31524. fallbacks.addFallback(0, "SPECULARTERM");
  31525. }
  31526. if (defines.DIFFUSEFRESNEL) {
  31527. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  31528. }
  31529. if (defines.OPACITYFRESNEL) {
  31530. fallbacks.addFallback(2, "OPACITYFRESNEL");
  31531. }
  31532. if (defines.REFLECTIONFRESNEL) {
  31533. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  31534. }
  31535. if (defines.EMISSIVEFRESNEL) {
  31536. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  31537. }
  31538. if (defines.FRESNEL) {
  31539. fallbacks.addFallback(4, "FRESNEL");
  31540. }
  31541. //Attributes
  31542. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31543. if (defines.NORMAL) {
  31544. attribs.push(BABYLON.VertexBuffer.NormalKind);
  31545. }
  31546. if (defines.UV1) {
  31547. attribs.push(BABYLON.VertexBuffer.UVKind);
  31548. }
  31549. if (defines.UV2) {
  31550. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31551. }
  31552. if (defines.VERTEXCOLOR) {
  31553. attribs.push(BABYLON.VertexBuffer.ColorKind);
  31554. }
  31555. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  31556. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  31557. var shaderName = "default";
  31558. if (this.customShaderNameResolve) {
  31559. shaderName = this.customShaderNameResolve(shaderName);
  31560. }
  31561. var join = defines.toString();
  31562. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  31563. "vFogInfos", "vFogColor", "pointSize",
  31564. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  31565. "mBones",
  31566. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  31567. "depthValues",
  31568. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  31569. "logarithmicDepthConstant"
  31570. ];
  31571. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  31572. if (defines.CAMERACOLORCURVES) {
  31573. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  31574. }
  31575. if (defines.CAMERACOLORGRADING) {
  31576. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  31577. }
  31578. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, defines, this._maxSimultaneousLights);
  31579. subMesh.effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this._maxSimultaneousLights - 1 });
  31580. }
  31581. if (!subMesh.effect.isReady()) {
  31582. return false;
  31583. }
  31584. defines._renderId = scene.getRenderId();
  31585. this._wasPreviouslyReady = true;
  31586. return true;
  31587. };
  31588. StandardMaterial.prototype.unbind = function () {
  31589. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  31590. this._activeEffect.setTexture("reflection2DSampler", null);
  31591. }
  31592. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  31593. this._activeEffect.setTexture("refraction2DSampler", null);
  31594. }
  31595. _super.prototype.unbind.call(this);
  31596. };
  31597. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  31598. this._activeEffect.setMatrix("world", world);
  31599. };
  31600. StandardMaterial.prototype.bind = function (world, mesh) {
  31601. if (!mesh) {
  31602. return;
  31603. }
  31604. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  31605. };
  31606. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31607. var scene = this.getScene();
  31608. var defines = subMesh._materialDefines;
  31609. var effect = subMesh.effect;
  31610. this._activeEffect = effect;
  31611. // Matrices
  31612. this.bindOnlyWorldMatrix(world);
  31613. // Bones
  31614. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  31615. if (scene.getCachedMaterial() !== this) {
  31616. effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31617. if (StandardMaterial.FresnelEnabled) {
  31618. // Fresnel
  31619. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  31620. effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  31621. effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  31622. }
  31623. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  31624. effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  31625. }
  31626. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  31627. effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  31628. effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  31629. }
  31630. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  31631. effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  31632. effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  31633. }
  31634. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  31635. effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  31636. effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  31637. }
  31638. }
  31639. // Textures
  31640. if (scene.texturesEnabled) {
  31641. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31642. effect.setTexture("diffuseSampler", this._diffuseTexture);
  31643. effect.setFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  31644. effect.setMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  31645. }
  31646. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31647. effect.setTexture("ambientSampler", this._ambientTexture);
  31648. effect.setFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  31649. effect.setMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  31650. }
  31651. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31652. effect.setTexture("opacitySampler", this._opacityTexture);
  31653. effect.setFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  31654. effect.setMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  31655. }
  31656. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31657. if (this._reflectionTexture.isCube) {
  31658. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  31659. }
  31660. else {
  31661. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  31662. }
  31663. effect.setMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  31664. effect.setFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  31665. }
  31666. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31667. effect.setTexture("emissiveSampler", this._emissiveTexture);
  31668. effect.setFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  31669. effect.setMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  31670. }
  31671. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31672. effect.setTexture("lightmapSampler", this._lightmapTexture);
  31673. effect.setFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  31674. effect.setMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  31675. }
  31676. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31677. effect.setTexture("specularSampler", this._specularTexture);
  31678. effect.setFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  31679. effect.setMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  31680. }
  31681. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  31682. effect.setTexture("bumpSampler", this._bumpTexture);
  31683. effect.setFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  31684. effect.setMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  31685. }
  31686. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31687. var depth = 1.0;
  31688. if (this._refractionTexture.isCube) {
  31689. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  31690. }
  31691. else {
  31692. effect.setTexture("refraction2DSampler", this._refractionTexture);
  31693. effect.setMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  31694. if (this._refractionTexture.depth) {
  31695. depth = this._refractionTexture.depth;
  31696. }
  31697. }
  31698. effect.setFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  31699. }
  31700. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  31701. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  31702. }
  31703. }
  31704. // Clip plane
  31705. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  31706. // Point size
  31707. if (this.pointsCloud) {
  31708. effect.setFloat("pointSize", this.pointSize);
  31709. }
  31710. // Colors
  31711. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  31712. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  31713. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  31714. if (defines.SPECULARTERM) {
  31715. effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  31716. }
  31717. effect.setColor3("vEmissiveColor", this.emissiveColor);
  31718. }
  31719. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  31720. // Diffuse
  31721. effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  31722. // Lights
  31723. if (scene.lightsEnabled && !this.disableLighting) {
  31724. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  31725. }
  31726. // View
  31727. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  31728. effect.setMatrix("view", scene.getViewMatrix());
  31729. }
  31730. // Fog
  31731. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  31732. // Log. depth
  31733. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  31734. // Color Curves
  31735. if (this.cameraColorCurves) {
  31736. BABYLON.ColorCurves.Bind(this.cameraColorCurves, effect);
  31737. }
  31738. }
  31739. _super.prototype.bind.call(this, world, mesh);
  31740. };
  31741. StandardMaterial.prototype.getAnimatables = function () {
  31742. var results = [];
  31743. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  31744. results.push(this._diffuseTexture);
  31745. }
  31746. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  31747. results.push(this._ambientTexture);
  31748. }
  31749. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  31750. results.push(this._opacityTexture);
  31751. }
  31752. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  31753. results.push(this._reflectionTexture);
  31754. }
  31755. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  31756. results.push(this._emissiveTexture);
  31757. }
  31758. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  31759. results.push(this._specularTexture);
  31760. }
  31761. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  31762. results.push(this._bumpTexture);
  31763. }
  31764. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  31765. results.push(this._lightmapTexture);
  31766. }
  31767. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  31768. results.push(this._refractionTexture);
  31769. }
  31770. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  31771. results.push(this._cameraColorGradingTexture);
  31772. }
  31773. return results;
  31774. };
  31775. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31776. if (forceDisposeTextures) {
  31777. if (this._diffuseTexture) {
  31778. this._diffuseTexture.dispose();
  31779. }
  31780. if (this._ambientTexture) {
  31781. this._ambientTexture.dispose();
  31782. }
  31783. if (this._opacityTexture) {
  31784. this._opacityTexture.dispose();
  31785. }
  31786. if (this._reflectionTexture) {
  31787. this._reflectionTexture.dispose();
  31788. }
  31789. if (this._emissiveTexture) {
  31790. this._emissiveTexture.dispose();
  31791. }
  31792. if (this._specularTexture) {
  31793. this._specularTexture.dispose();
  31794. }
  31795. if (this._bumpTexture) {
  31796. this._bumpTexture.dispose();
  31797. }
  31798. if (this._lightmapTexture) {
  31799. this._lightmapTexture.dispose();
  31800. }
  31801. if (this._refractionTexture) {
  31802. this._refractionTexture.dispose();
  31803. }
  31804. if (this._cameraColorGradingTexture) {
  31805. this._cameraColorGradingTexture.dispose();
  31806. }
  31807. }
  31808. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  31809. };
  31810. StandardMaterial.prototype.clone = function (name) {
  31811. var _this = this;
  31812. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  31813. };
  31814. StandardMaterial.prototype.serialize = function () {
  31815. return BABYLON.SerializationHelper.Serialize(this);
  31816. };
  31817. StandardMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  31818. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31819. var mesh = _a[_i];
  31820. if (!mesh.subMeshes) {
  31821. continue;
  31822. }
  31823. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31824. var subMesh = _c[_b];
  31825. if (subMesh.getMaterial() !== this) {
  31826. continue;
  31827. }
  31828. if (!subMesh._materialDefines) {
  31829. subMesh._materialDefines = new StandardMaterialDefines();
  31830. }
  31831. func((subMesh._materialDefines));
  31832. }
  31833. }
  31834. };
  31835. StandardMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31836. this._markAllSubMeshesAsDirty(function (defines) { return defines._areTexturesDirty = true; });
  31837. };
  31838. StandardMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31839. this._markAllSubMeshesAsDirty(function (defines) { return defines._areFresnelDirty = true; });
  31840. };
  31841. StandardMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  31842. this._markAllSubMeshesAsDirty(function (defines) { return defines._areLightsDirty = true; });
  31843. };
  31844. StandardMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31845. this._markAllSubMeshesAsDirty(function (defines) { return defines._areAttributesDirty = true; });
  31846. };
  31847. StandardMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  31848. this._markAllSubMeshesAsDirty(function (defines) { return defines._areMiscDirty = true; });
  31849. };
  31850. // Statics
  31851. StandardMaterial.Parse = function (source, scene, rootUrl) {
  31852. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  31853. };
  31854. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  31855. get: function () {
  31856. return StandardMaterial._DiffuseTextureEnabled;
  31857. },
  31858. set: function (value) {
  31859. if (StandardMaterial._DiffuseTextureEnabled === value) {
  31860. return;
  31861. }
  31862. StandardMaterial._DiffuseTextureEnabled = value;
  31863. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31864. },
  31865. enumerable: true,
  31866. configurable: true
  31867. });
  31868. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  31869. get: function () {
  31870. return StandardMaterial._AmbientTextureEnabled;
  31871. },
  31872. set: function (value) {
  31873. if (StandardMaterial._AmbientTextureEnabled === value) {
  31874. return;
  31875. }
  31876. StandardMaterial._AmbientTextureEnabled = value;
  31877. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31878. },
  31879. enumerable: true,
  31880. configurable: true
  31881. });
  31882. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  31883. get: function () {
  31884. return StandardMaterial._OpacityTextureEnabled;
  31885. },
  31886. set: function (value) {
  31887. if (StandardMaterial._OpacityTextureEnabled === value) {
  31888. return;
  31889. }
  31890. StandardMaterial._OpacityTextureEnabled = value;
  31891. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31892. },
  31893. enumerable: true,
  31894. configurable: true
  31895. });
  31896. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  31897. get: function () {
  31898. return StandardMaterial._ReflectionTextureEnabled;
  31899. },
  31900. set: function (value) {
  31901. if (StandardMaterial._ReflectionTextureEnabled === value) {
  31902. return;
  31903. }
  31904. StandardMaterial._ReflectionTextureEnabled = value;
  31905. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31906. },
  31907. enumerable: true,
  31908. configurable: true
  31909. });
  31910. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  31911. get: function () {
  31912. return StandardMaterial._EmissiveTextureEnabled;
  31913. },
  31914. set: function (value) {
  31915. if (StandardMaterial._EmissiveTextureEnabled === value) {
  31916. return;
  31917. }
  31918. StandardMaterial._EmissiveTextureEnabled = value;
  31919. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31920. },
  31921. enumerable: true,
  31922. configurable: true
  31923. });
  31924. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  31925. get: function () {
  31926. return StandardMaterial._SpecularTextureEnabled;
  31927. },
  31928. set: function (value) {
  31929. if (StandardMaterial._SpecularTextureEnabled === value) {
  31930. return;
  31931. }
  31932. StandardMaterial._SpecularTextureEnabled = value;
  31933. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31934. },
  31935. enumerable: true,
  31936. configurable: true
  31937. });
  31938. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  31939. get: function () {
  31940. return StandardMaterial._BumpTextureEnabled;
  31941. },
  31942. set: function (value) {
  31943. if (StandardMaterial._BumpTextureEnabled === value) {
  31944. return;
  31945. }
  31946. StandardMaterial._BumpTextureEnabled = value;
  31947. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31948. },
  31949. enumerable: true,
  31950. configurable: true
  31951. });
  31952. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  31953. get: function () {
  31954. return StandardMaterial._LightmapTextureEnabled;
  31955. },
  31956. set: function (value) {
  31957. if (StandardMaterial._LightmapTextureEnabled === value) {
  31958. return;
  31959. }
  31960. StandardMaterial._LightmapTextureEnabled = value;
  31961. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31962. },
  31963. enumerable: true,
  31964. configurable: true
  31965. });
  31966. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  31967. get: function () {
  31968. return StandardMaterial._RefractionTextureEnabled;
  31969. },
  31970. set: function (value) {
  31971. if (StandardMaterial._RefractionTextureEnabled === value) {
  31972. return;
  31973. }
  31974. StandardMaterial._RefractionTextureEnabled = value;
  31975. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31976. },
  31977. enumerable: true,
  31978. configurable: true
  31979. });
  31980. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  31981. get: function () {
  31982. return StandardMaterial._ColorGradingTextureEnabled;
  31983. },
  31984. set: function (value) {
  31985. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  31986. return;
  31987. }
  31988. StandardMaterial._ColorGradingTextureEnabled = value;
  31989. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31990. },
  31991. enumerable: true,
  31992. configurable: true
  31993. });
  31994. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  31995. get: function () {
  31996. return StandardMaterial._FresnelEnabled;
  31997. },
  31998. set: function (value) {
  31999. if (StandardMaterial._FresnelEnabled === value) {
  32000. return;
  32001. }
  32002. StandardMaterial._FresnelEnabled = value;
  32003. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  32004. },
  32005. enumerable: true,
  32006. configurable: true
  32007. });
  32008. return StandardMaterial;
  32009. }(BABYLON.Material));
  32010. // Flags used to enable or disable a type of texture for all Standard Materials
  32011. StandardMaterial._DiffuseTextureEnabled = true;
  32012. StandardMaterial._AmbientTextureEnabled = true;
  32013. StandardMaterial._OpacityTextureEnabled = true;
  32014. StandardMaterial._ReflectionTextureEnabled = true;
  32015. StandardMaterial._EmissiveTextureEnabled = true;
  32016. StandardMaterial._SpecularTextureEnabled = true;
  32017. StandardMaterial._BumpTextureEnabled = true;
  32018. StandardMaterial._LightmapTextureEnabled = true;
  32019. StandardMaterial._RefractionTextureEnabled = true;
  32020. StandardMaterial._ColorGradingTextureEnabled = true;
  32021. StandardMaterial._FresnelEnabled = true;
  32022. __decorate([
  32023. BABYLON.serializeAsTexture("diffuseTexture")
  32024. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  32025. __decorate([
  32026. BABYLON.serializeAsTexture("ambientTexture")
  32027. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  32028. __decorate([
  32029. BABYLON.serializeAsTexture("opacityTexture")
  32030. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  32031. __decorate([
  32032. BABYLON.serializeAsTexture("reflectionTexture")
  32033. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  32034. __decorate([
  32035. BABYLON.serializeAsTexture("emissiveTexture")
  32036. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  32037. __decorate([
  32038. BABYLON.serializeAsTexture("specularTexture")
  32039. ], StandardMaterial.prototype, "_specularTexture", void 0);
  32040. __decorate([
  32041. BABYLON.serializeAsTexture("bumpTexture")
  32042. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  32043. __decorate([
  32044. BABYLON.serializeAsTexture("lightmapTexture")
  32045. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  32046. __decorate([
  32047. BABYLON.serializeAsTexture("refractionTexture")
  32048. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  32049. __decorate([
  32050. BABYLON.serializeAsColor3("ambient")
  32051. ], StandardMaterial.prototype, "ambientColor", void 0);
  32052. __decorate([
  32053. BABYLON.serializeAsColor3("diffuse")
  32054. ], StandardMaterial.prototype, "diffuseColor", void 0);
  32055. __decorate([
  32056. BABYLON.serializeAsColor3("specular")
  32057. ], StandardMaterial.prototype, "specularColor", void 0);
  32058. __decorate([
  32059. BABYLON.serializeAsColor3("emissive")
  32060. ], StandardMaterial.prototype, "emissiveColor", void 0);
  32061. __decorate([
  32062. BABYLON.serialize()
  32063. ], StandardMaterial.prototype, "specularPower", void 0);
  32064. __decorate([
  32065. BABYLON.serialize("useAlphaFromDiffuseTexture")
  32066. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  32067. __decorate([
  32068. BABYLON.serialize("useEmissiveAsIllumination")
  32069. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  32070. __decorate([
  32071. BABYLON.serialize("linkEmissiveWithDiffuse")
  32072. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  32073. __decorate([
  32074. BABYLON.serialize("useSpecularOverAlpha")
  32075. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  32076. __decorate([
  32077. BABYLON.serialize("useReflectionOverAlpha")
  32078. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  32079. __decorate([
  32080. BABYLON.serialize("disableLighting")
  32081. ], StandardMaterial.prototype, "_disableLighting", void 0);
  32082. __decorate([
  32083. BABYLON.serialize("useParallax")
  32084. ], StandardMaterial.prototype, "_useParallax", void 0);
  32085. __decorate([
  32086. BABYLON.serialize("useParallaxOcclusion")
  32087. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  32088. __decorate([
  32089. BABYLON.serialize()
  32090. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  32091. __decorate([
  32092. BABYLON.serialize("roughness")
  32093. ], StandardMaterial.prototype, "_roughness", void 0);
  32094. __decorate([
  32095. BABYLON.serialize()
  32096. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  32097. __decorate([
  32098. BABYLON.serialize()
  32099. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  32100. __decorate([
  32101. BABYLON.serialize("useLightmapAsShadowmap")
  32102. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  32103. __decorate([
  32104. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  32105. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  32106. __decorate([
  32107. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  32108. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  32109. __decorate([
  32110. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  32111. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  32112. __decorate([
  32113. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  32114. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  32115. __decorate([
  32116. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  32117. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  32118. __decorate([
  32119. BABYLON.serialize("useReflectionFresnelFromSpecular")
  32120. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  32121. __decorate([
  32122. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  32123. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  32124. __decorate([
  32125. BABYLON.serialize("maxSimultaneousLights")
  32126. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  32127. __decorate([
  32128. BABYLON.serialize("invertNormalMapX")
  32129. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  32130. __decorate([
  32131. BABYLON.serialize("invertNormalMapY")
  32132. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  32133. __decorate([
  32134. BABYLON.serialize("twoSidedLighting")
  32135. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  32136. __decorate([
  32137. BABYLON.serializeAsTexture()
  32138. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  32139. __decorate([
  32140. BABYLON.serializeAsColorCurves("cameraColorCurves")
  32141. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  32142. __decorate([
  32143. BABYLON.serialize()
  32144. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  32145. BABYLON.StandardMaterial = StandardMaterial;
  32146. })(BABYLON || (BABYLON = {}));
  32147. //# sourceMappingURL=babylon.standardMaterial.js.map
  32148. var BABYLON;
  32149. (function (BABYLON) {
  32150. var MultiMaterial = (function (_super) {
  32151. __extends(MultiMaterial, _super);
  32152. function MultiMaterial(name, scene) {
  32153. var _this = _super.call(this, name, scene, true) || this;
  32154. _this.subMaterials = new Array();
  32155. scene.multiMaterials.push(_this);
  32156. return _this;
  32157. }
  32158. // Properties
  32159. MultiMaterial.prototype.getSubMaterial = function (index) {
  32160. if (index < 0 || index >= this.subMaterials.length) {
  32161. return this.getScene().defaultMaterial;
  32162. }
  32163. return this.subMaterials[index];
  32164. };
  32165. // Methods
  32166. MultiMaterial.prototype.getClassName = function () {
  32167. return "MultiMaterial";
  32168. };
  32169. MultiMaterial.prototype.isReady = function (mesh) {
  32170. for (var index = 0; index < this.subMaterials.length; index++) {
  32171. var subMaterial = this.subMaterials[index];
  32172. if (subMaterial) {
  32173. if (!this.subMaterials[index].isReady(mesh)) {
  32174. return false;
  32175. }
  32176. }
  32177. }
  32178. return true;
  32179. };
  32180. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  32181. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  32182. for (var index = 0; index < this.subMaterials.length; index++) {
  32183. var subMaterial = null;
  32184. if (cloneChildren) {
  32185. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  32186. }
  32187. else {
  32188. subMaterial = this.subMaterials[index];
  32189. }
  32190. newMultiMaterial.subMaterials.push(subMaterial);
  32191. }
  32192. return newMultiMaterial;
  32193. };
  32194. MultiMaterial.prototype.serialize = function () {
  32195. var serializationObject = {};
  32196. serializationObject.name = this.name;
  32197. serializationObject.id = this.id;
  32198. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32199. serializationObject.materials = [];
  32200. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  32201. var subMat = this.subMaterials[matIndex];
  32202. if (subMat) {
  32203. serializationObject.materials.push(subMat.id);
  32204. }
  32205. else {
  32206. serializationObject.materials.push(null);
  32207. }
  32208. }
  32209. return serializationObject;
  32210. };
  32211. return MultiMaterial;
  32212. }(BABYLON.Material));
  32213. BABYLON.MultiMaterial = MultiMaterial;
  32214. })(BABYLON || (BABYLON = {}));
  32215. //# sourceMappingURL=babylon.multiMaterial.js.map
  32216. var BABYLON;
  32217. (function (BABYLON) {
  32218. var SceneLoader = (function () {
  32219. function SceneLoader() {
  32220. }
  32221. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  32222. get: function () {
  32223. return 0;
  32224. },
  32225. enumerable: true,
  32226. configurable: true
  32227. });
  32228. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  32229. get: function () {
  32230. return 1;
  32231. },
  32232. enumerable: true,
  32233. configurable: true
  32234. });
  32235. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  32236. get: function () {
  32237. return 2;
  32238. },
  32239. enumerable: true,
  32240. configurable: true
  32241. });
  32242. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  32243. get: function () {
  32244. return 3;
  32245. },
  32246. enumerable: true,
  32247. configurable: true
  32248. });
  32249. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  32250. get: function () {
  32251. return SceneLoader._ForceFullSceneLoadingForIncremental;
  32252. },
  32253. set: function (value) {
  32254. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  32255. },
  32256. enumerable: true,
  32257. configurable: true
  32258. });
  32259. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  32260. get: function () {
  32261. return SceneLoader._ShowLoadingScreen;
  32262. },
  32263. set: function (value) {
  32264. SceneLoader._ShowLoadingScreen = value;
  32265. },
  32266. enumerable: true,
  32267. configurable: true
  32268. });
  32269. Object.defineProperty(SceneLoader, "loggingLevel", {
  32270. get: function () {
  32271. return SceneLoader._loggingLevel;
  32272. },
  32273. set: function (value) {
  32274. SceneLoader._loggingLevel = value;
  32275. },
  32276. enumerable: true,
  32277. configurable: true
  32278. });
  32279. SceneLoader._getDefaultPlugin = function () {
  32280. return SceneLoader._registeredPlugins[".babylon"];
  32281. };
  32282. SceneLoader._getPluginForExtension = function (extension) {
  32283. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  32284. if (registeredPlugin) {
  32285. return registeredPlugin;
  32286. }
  32287. return SceneLoader._getDefaultPlugin();
  32288. };
  32289. SceneLoader._getPluginForFilename = function (sceneFilename) {
  32290. if (sceneFilename.name) {
  32291. sceneFilename = sceneFilename.name;
  32292. }
  32293. var dotPosition = sceneFilename.lastIndexOf(".");
  32294. var queryStringPosition = sceneFilename.indexOf("?");
  32295. if (queryStringPosition === -1) {
  32296. queryStringPosition = sceneFilename.length;
  32297. }
  32298. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  32299. return SceneLoader._getPluginForExtension(extension);
  32300. };
  32301. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  32302. SceneLoader._getDirectLoad = function (sceneFilename) {
  32303. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  32304. return sceneFilename.substr(5);
  32305. }
  32306. return null;
  32307. };
  32308. // Public functions
  32309. SceneLoader.GetPluginForExtension = function (extension) {
  32310. return SceneLoader._getPluginForExtension(extension).plugin;
  32311. };
  32312. SceneLoader.RegisterPlugin = function (plugin) {
  32313. if (typeof plugin.extensions === "string") {
  32314. var extension = plugin.extensions;
  32315. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  32316. plugin: plugin,
  32317. isBinary: false
  32318. };
  32319. }
  32320. else {
  32321. var extensions = plugin.extensions;
  32322. Object.keys(extensions).forEach(function (extension) {
  32323. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  32324. plugin: plugin,
  32325. isBinary: extensions[extension].isBinary
  32326. };
  32327. });
  32328. }
  32329. };
  32330. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  32331. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  32332. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  32333. return;
  32334. }
  32335. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  32336. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  32337. return;
  32338. }
  32339. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  32340. var loadingToken = {};
  32341. scene._addPendingData(loadingToken);
  32342. var manifestChecked = function (success) {
  32343. scene.database = database;
  32344. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  32345. var plugin = registeredPlugin.plugin;
  32346. var useArrayBuffer = registeredPlugin.isBinary;
  32347. var importMeshFromData = function (data) {
  32348. var meshes = [];
  32349. var particleSystems = [];
  32350. var skeletons = [];
  32351. if (scene.isDisposed) {
  32352. if (onerror) {
  32353. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  32354. }
  32355. return;
  32356. }
  32357. try {
  32358. if (plugin.importMesh) {
  32359. var syncedPlugin = plugin;
  32360. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  32361. if (onerror) {
  32362. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  32363. }
  32364. scene._removePendingData(loadingToken);
  32365. return;
  32366. }
  32367. if (onsuccess) {
  32368. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  32369. onsuccess(meshes, particleSystems, skeletons);
  32370. scene._removePendingData(loadingToken);
  32371. }
  32372. }
  32373. else {
  32374. var asyncedPlugin = plugin;
  32375. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  32376. if (onsuccess) {
  32377. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  32378. onsuccess(meshes, particleSystems, skeletons);
  32379. scene._removePendingData(loadingToken);
  32380. }
  32381. }, function () {
  32382. if (onerror) {
  32383. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  32384. }
  32385. scene._removePendingData(loadingToken);
  32386. });
  32387. }
  32388. }
  32389. catch (e) {
  32390. if (onerror) {
  32391. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  32392. }
  32393. scene._removePendingData(loadingToken);
  32394. }
  32395. };
  32396. if (directLoad) {
  32397. importMeshFromData(directLoad);
  32398. return;
  32399. }
  32400. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  32401. importMeshFromData(data);
  32402. }, progressCallBack, database, useArrayBuffer, function () {
  32403. if (onerror) {
  32404. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  32405. }
  32406. });
  32407. };
  32408. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  32409. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  32410. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  32411. }
  32412. else {
  32413. // If the scene is a data stream or offline support is not enabled, it's a direct load
  32414. manifestChecked(true);
  32415. }
  32416. };
  32417. /**
  32418. * Load a scene
  32419. * @param rootUrl a string that defines the root url for scene and resources
  32420. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  32421. * @param engine is the instance of BABYLON.Engine to use to create the scene
  32422. */
  32423. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  32424. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  32425. };
  32426. /**
  32427. * Append a scene
  32428. * @param rootUrl a string that defines the root url for scene and resources
  32429. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  32430. * @param scene is the instance of BABYLON.Scene to append to
  32431. */
  32432. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  32433. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  32434. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  32435. return;
  32436. }
  32437. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  32438. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  32439. var plugin = registeredPlugin.plugin;
  32440. var useArrayBuffer = registeredPlugin.isBinary;
  32441. var database;
  32442. var loadingToken = {};
  32443. scene._addPendingData(loadingToken);
  32444. if (SceneLoader.ShowLoadingScreen) {
  32445. scene.getEngine().displayLoadingUI();
  32446. }
  32447. var loadSceneFromData = function (data) {
  32448. scene.database = database;
  32449. if (plugin.load) {
  32450. var syncedPlugin = plugin;
  32451. if (!syncedPlugin.load(scene, data, rootUrl)) {
  32452. if (onerror) {
  32453. onerror(scene);
  32454. }
  32455. scene._removePendingData(loadingToken);
  32456. scene.getEngine().hideLoadingUI();
  32457. return;
  32458. }
  32459. if (onsuccess) {
  32460. onsuccess(scene);
  32461. }
  32462. scene._removePendingData(loadingToken);
  32463. }
  32464. else {
  32465. var asyncedPlugin = plugin;
  32466. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  32467. if (onsuccess) {
  32468. onsuccess(scene);
  32469. }
  32470. scene._removePendingData(loadingToken);
  32471. }, function () {
  32472. if (onerror) {
  32473. onerror(scene);
  32474. }
  32475. scene._removePendingData(loadingToken);
  32476. scene.getEngine().hideLoadingUI();
  32477. });
  32478. }
  32479. if (SceneLoader.ShowLoadingScreen) {
  32480. scene.executeWhenReady(function () {
  32481. scene.getEngine().hideLoadingUI();
  32482. });
  32483. }
  32484. };
  32485. var manifestChecked = function (success) {
  32486. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  32487. };
  32488. if (directLoad) {
  32489. loadSceneFromData(directLoad);
  32490. return;
  32491. }
  32492. if (rootUrl.indexOf("file:") === -1) {
  32493. if (scene.getEngine().enableOfflineSupport) {
  32494. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  32495. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  32496. }
  32497. else {
  32498. manifestChecked(true);
  32499. }
  32500. }
  32501. else {
  32502. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  32503. }
  32504. };
  32505. return SceneLoader;
  32506. }());
  32507. // Flags
  32508. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  32509. SceneLoader._ShowLoadingScreen = true;
  32510. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  32511. // Members
  32512. SceneLoader._registeredPlugins = {};
  32513. BABYLON.SceneLoader = SceneLoader;
  32514. ;
  32515. })(BABYLON || (BABYLON = {}));
  32516. //# sourceMappingURL=babylon.sceneLoader.js.map
  32517. var BABYLON;
  32518. (function (BABYLON) {
  32519. var Internals;
  32520. (function (Internals) {
  32521. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  32522. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  32523. var parsedMaterial = parsedData.materials[index];
  32524. if (parsedMaterial.id === id) {
  32525. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  32526. }
  32527. }
  32528. return null;
  32529. };
  32530. var isDescendantOf = function (mesh, names, hierarchyIds) {
  32531. names = (names instanceof Array) ? names : [names];
  32532. for (var i in names) {
  32533. if (mesh.name === names[i]) {
  32534. hierarchyIds.push(mesh.id);
  32535. return true;
  32536. }
  32537. }
  32538. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  32539. hierarchyIds.push(mesh.id);
  32540. return true;
  32541. }
  32542. return false;
  32543. };
  32544. var logOperation = function (operation, producer) {
  32545. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  32546. };
  32547. BABYLON.SceneLoader.RegisterPlugin({
  32548. extensions: ".babylon",
  32549. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  32550. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  32551. // when SceneLoader.debugLogging = true (default), or exception encountered.
  32552. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  32553. // and avoid problems with multiple concurrent .babylon loads.
  32554. var log = "importMesh has failed JSON parse";
  32555. try {
  32556. var parsedData = JSON.parse(data);
  32557. log = "";
  32558. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  32559. var loadedSkeletonsIds = [];
  32560. var loadedMaterialsIds = [];
  32561. var hierarchyIds = [];
  32562. var index;
  32563. var cache;
  32564. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  32565. var parsedMesh = parsedData.meshes[index];
  32566. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  32567. if (meshesNames instanceof Array) {
  32568. // Remove found mesh name from list.
  32569. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  32570. }
  32571. //Geometry?
  32572. if (parsedMesh.geometryId) {
  32573. //does the file contain geometries?
  32574. if (parsedData.geometries) {
  32575. //find the correct geometry and add it to the scene
  32576. var found = false;
  32577. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  32578. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  32579. return;
  32580. }
  32581. else {
  32582. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  32583. if (parsedGeometryData.id === parsedMesh.geometryId) {
  32584. switch (geometryType) {
  32585. case "boxes":
  32586. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  32587. break;
  32588. case "spheres":
  32589. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  32590. break;
  32591. case "cylinders":
  32592. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  32593. break;
  32594. case "toruses":
  32595. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  32596. break;
  32597. case "grounds":
  32598. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  32599. break;
  32600. case "planes":
  32601. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  32602. break;
  32603. case "torusKnots":
  32604. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  32605. break;
  32606. case "vertexData":
  32607. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  32608. break;
  32609. }
  32610. found = true;
  32611. }
  32612. });
  32613. }
  32614. });
  32615. if (!found) {
  32616. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  32617. }
  32618. }
  32619. }
  32620. // Material ?
  32621. if (parsedMesh.materialId) {
  32622. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  32623. if (!materialFound && parsedData.multiMaterials) {
  32624. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  32625. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  32626. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  32627. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  32628. var subMatId = parsedMultiMaterial.materials[matIndex];
  32629. loadedMaterialsIds.push(subMatId);
  32630. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  32631. log += "\n\tMaterial " + mat.toString(fullDetails);
  32632. }
  32633. loadedMaterialsIds.push(parsedMultiMaterial.id);
  32634. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  32635. materialFound = true;
  32636. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  32637. break;
  32638. }
  32639. }
  32640. }
  32641. if (!materialFound) {
  32642. loadedMaterialsIds.push(parsedMesh.materialId);
  32643. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  32644. if (!mat) {
  32645. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  32646. }
  32647. else {
  32648. log += "\n\tMaterial " + mat.toString(fullDetails);
  32649. }
  32650. }
  32651. }
  32652. // Skeleton ?
  32653. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  32654. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  32655. if (!skeletonAlreadyLoaded) {
  32656. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  32657. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  32658. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  32659. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  32660. skeletons.push(skeleton);
  32661. loadedSkeletonsIds.push(parsedSkeleton.id);
  32662. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  32663. }
  32664. }
  32665. }
  32666. }
  32667. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  32668. meshes.push(mesh);
  32669. log += "\n\tMesh " + mesh.toString(fullDetails);
  32670. }
  32671. }
  32672. // Connecting parents
  32673. var currentMesh;
  32674. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  32675. currentMesh = scene.meshes[index];
  32676. if (currentMesh._waitingParentId) {
  32677. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  32678. currentMesh._waitingParentId = undefined;
  32679. }
  32680. }
  32681. // freeze and compute world matrix application
  32682. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  32683. currentMesh = scene.meshes[index];
  32684. if (currentMesh._waitingFreezeWorldMatrix) {
  32685. currentMesh.freezeWorldMatrix();
  32686. currentMesh._waitingFreezeWorldMatrix = undefined;
  32687. }
  32688. else {
  32689. currentMesh.computeWorldMatrix(true);
  32690. }
  32691. }
  32692. // Particles
  32693. if (parsedData.particleSystems) {
  32694. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  32695. var parsedParticleSystem = parsedData.particleSystems[index];
  32696. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  32697. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  32698. }
  32699. }
  32700. }
  32701. return true;
  32702. }
  32703. catch (err) {
  32704. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  32705. log = null;
  32706. throw err;
  32707. }
  32708. finally {
  32709. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  32710. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  32711. }
  32712. }
  32713. },
  32714. load: function (scene, data, rootUrl) {
  32715. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  32716. // when SceneLoader.debugLogging = true (default), or exception encountered.
  32717. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  32718. // and avoid problems with multiple concurrent .babylon loads.
  32719. var log = "importScene has failed JSON parse";
  32720. try {
  32721. var parsedData = JSON.parse(data);
  32722. log = "";
  32723. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  32724. // Scene
  32725. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  32726. scene.autoClear = parsedData.autoClear;
  32727. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  32728. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  32729. if (parsedData.gravity) {
  32730. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  32731. }
  32732. // Fog
  32733. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  32734. scene.fogMode = parsedData.fogMode;
  32735. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  32736. scene.fogStart = parsedData.fogStart;
  32737. scene.fogEnd = parsedData.fogEnd;
  32738. scene.fogDensity = parsedData.fogDensity;
  32739. log += "\tFog mode for scene: ";
  32740. switch (scene.fogMode) {
  32741. // getters not compiling, so using hardcoded
  32742. case 1:
  32743. log += "exp\n";
  32744. break;
  32745. case 2:
  32746. log += "exp2\n";
  32747. break;
  32748. case 3:
  32749. log += "linear\n";
  32750. break;
  32751. }
  32752. }
  32753. //Physics
  32754. if (parsedData.physicsEnabled) {
  32755. var physicsPlugin;
  32756. if (parsedData.physicsEngine === "cannon") {
  32757. physicsPlugin = new BABYLON.CannonJSPlugin();
  32758. }
  32759. else if (parsedData.physicsEngine === "oimo") {
  32760. physicsPlugin = new BABYLON.OimoJSPlugin();
  32761. }
  32762. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  32763. //else - default engine, which is currently oimo
  32764. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  32765. scene.enablePhysics(physicsGravity, physicsPlugin);
  32766. }
  32767. // Metadata
  32768. if (parsedData.metadata !== undefined) {
  32769. scene.metadata = parsedData.metadata;
  32770. }
  32771. //collisions, if defined. otherwise, default is true
  32772. if (parsedData.collisionsEnabled != undefined) {
  32773. scene.collisionsEnabled = parsedData.collisionsEnabled;
  32774. }
  32775. scene.workerCollisions = !!parsedData.workerCollisions;
  32776. var index;
  32777. var cache;
  32778. // Lights
  32779. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  32780. var parsedLight = parsedData.lights[index];
  32781. var light = BABYLON.Light.Parse(parsedLight, scene);
  32782. log += (index === 0 ? "\n\tLights:" : "");
  32783. log += "\n\t\t" + light.toString(fullDetails);
  32784. }
  32785. // Animations
  32786. if (parsedData.animations) {
  32787. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  32788. var parsedAnimation = parsedData.animations[index];
  32789. var animation = BABYLON.Animation.Parse(parsedAnimation);
  32790. scene.animations.push(animation);
  32791. log += (index === 0 ? "\n\tAnimations:" : "");
  32792. log += "\n\t\t" + animation.toString(fullDetails);
  32793. }
  32794. }
  32795. if (parsedData.autoAnimate) {
  32796. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  32797. }
  32798. // Materials
  32799. if (parsedData.materials) {
  32800. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  32801. var parsedMaterial = parsedData.materials[index];
  32802. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  32803. log += (index === 0 ? "\n\tMaterials:" : "");
  32804. log += "\n\t\t" + mat.toString(fullDetails);
  32805. }
  32806. }
  32807. if (parsedData.multiMaterials) {
  32808. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  32809. var parsedMultiMaterial = parsedData.multiMaterials[index];
  32810. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  32811. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  32812. log += "\n\t\t" + mmat.toString(fullDetails);
  32813. }
  32814. }
  32815. // Skeletons
  32816. if (parsedData.skeletons) {
  32817. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  32818. var parsedSkeleton = parsedData.skeletons[index];
  32819. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  32820. log += (index === 0 ? "\n\tSkeletons:" : "");
  32821. log += "\n\t\t" + skeleton.toString(fullDetails);
  32822. }
  32823. }
  32824. // Geometries
  32825. var geometries = parsedData.geometries;
  32826. if (geometries) {
  32827. // Boxes
  32828. var boxes = geometries.boxes;
  32829. if (boxes) {
  32830. for (index = 0, cache = boxes.length; index < cache; index++) {
  32831. var parsedBox = boxes[index];
  32832. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  32833. }
  32834. }
  32835. // Spheres
  32836. var spheres = geometries.spheres;
  32837. if (spheres) {
  32838. for (index = 0, cache = spheres.length; index < cache; index++) {
  32839. var parsedSphere = spheres[index];
  32840. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  32841. }
  32842. }
  32843. // Cylinders
  32844. var cylinders = geometries.cylinders;
  32845. if (cylinders) {
  32846. for (index = 0, cache = cylinders.length; index < cache; index++) {
  32847. var parsedCylinder = cylinders[index];
  32848. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  32849. }
  32850. }
  32851. // Toruses
  32852. var toruses = geometries.toruses;
  32853. if (toruses) {
  32854. for (index = 0, cache = toruses.length; index < cache; index++) {
  32855. var parsedTorus = toruses[index];
  32856. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  32857. }
  32858. }
  32859. // Grounds
  32860. var grounds = geometries.grounds;
  32861. if (grounds) {
  32862. for (index = 0, cache = grounds.length; index < cache; index++) {
  32863. var parsedGround = grounds[index];
  32864. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  32865. }
  32866. }
  32867. // Planes
  32868. var planes = geometries.planes;
  32869. if (planes) {
  32870. for (index = 0, cache = planes.length; index < cache; index++) {
  32871. var parsedPlane = planes[index];
  32872. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  32873. }
  32874. }
  32875. // TorusKnots
  32876. var torusKnots = geometries.torusKnots;
  32877. if (torusKnots) {
  32878. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  32879. var parsedTorusKnot = torusKnots[index];
  32880. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  32881. }
  32882. }
  32883. // VertexData
  32884. var vertexData = geometries.vertexData;
  32885. if (vertexData) {
  32886. for (index = 0, cache = vertexData.length; index < cache; index++) {
  32887. var parsedVertexData = vertexData[index];
  32888. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  32889. }
  32890. }
  32891. }
  32892. // Meshes
  32893. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  32894. var parsedMesh = parsedData.meshes[index];
  32895. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  32896. log += (index === 0 ? "\n\tMeshes:" : "");
  32897. log += "\n\t\t" + mesh.toString(fullDetails);
  32898. }
  32899. // Cameras
  32900. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  32901. var parsedCamera = parsedData.cameras[index];
  32902. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  32903. log += (index === 0 ? "\n\tCameras:" : "");
  32904. log += "\n\t\t" + camera.toString(fullDetails);
  32905. }
  32906. if (parsedData.activeCameraID) {
  32907. scene.setActiveCameraByID(parsedData.activeCameraID);
  32908. }
  32909. // Browsing all the graph to connect the dots
  32910. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  32911. var camera = scene.cameras[index];
  32912. if (camera._waitingParentId) {
  32913. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  32914. camera._waitingParentId = undefined;
  32915. }
  32916. }
  32917. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  32918. var light = scene.lights[index];
  32919. if (light._waitingParentId) {
  32920. light.parent = scene.getLastEntryByID(light._waitingParentId);
  32921. light._waitingParentId = undefined;
  32922. }
  32923. }
  32924. // Sounds
  32925. var loadedSounds = [];
  32926. var loadedSound;
  32927. if (BABYLON.AudioEngine && parsedData.sounds) {
  32928. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  32929. var parsedSound = parsedData.sounds[index];
  32930. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32931. if (!parsedSound.url)
  32932. parsedSound.url = parsedSound.name;
  32933. if (!loadedSounds[parsedSound.url]) {
  32934. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  32935. loadedSounds[parsedSound.url] = loadedSound;
  32936. }
  32937. else {
  32938. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  32939. }
  32940. }
  32941. else {
  32942. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  32943. }
  32944. }
  32945. }
  32946. loadedSounds = [];
  32947. // Connect parents & children and parse actions
  32948. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  32949. var mesh = scene.meshes[index];
  32950. if (mesh._waitingParentId) {
  32951. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  32952. mesh._waitingParentId = undefined;
  32953. }
  32954. if (mesh._waitingActions) {
  32955. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  32956. mesh._waitingActions = undefined;
  32957. }
  32958. }
  32959. // freeze world matrix application
  32960. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  32961. var currentMesh = scene.meshes[index];
  32962. if (currentMesh._waitingFreezeWorldMatrix) {
  32963. currentMesh.freezeWorldMatrix();
  32964. currentMesh._waitingFreezeWorldMatrix = undefined;
  32965. }
  32966. else {
  32967. currentMesh.computeWorldMatrix(true);
  32968. }
  32969. }
  32970. // Particles Systems
  32971. if (parsedData.particleSystems) {
  32972. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  32973. var parsedParticleSystem = parsedData.particleSystems[index];
  32974. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  32975. }
  32976. }
  32977. // Lens flares
  32978. if (parsedData.lensFlareSystems) {
  32979. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  32980. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  32981. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  32982. }
  32983. }
  32984. // Shadows
  32985. if (parsedData.shadowGenerators) {
  32986. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  32987. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  32988. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  32989. }
  32990. }
  32991. // Lights exclusions / inclusions
  32992. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  32993. var light = scene.lights[index];
  32994. // Excluded check
  32995. if (light._excludedMeshesIds.length > 0) {
  32996. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  32997. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  32998. if (excludedMesh) {
  32999. light.excludedMeshes.push(excludedMesh);
  33000. }
  33001. }
  33002. light._excludedMeshesIds = [];
  33003. }
  33004. // Included check
  33005. if (light._includedOnlyMeshesIds.length > 0) {
  33006. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  33007. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  33008. if (includedOnlyMesh) {
  33009. light.includedOnlyMeshes.push(includedOnlyMesh);
  33010. }
  33011. }
  33012. light._includedOnlyMeshesIds = [];
  33013. }
  33014. }
  33015. // Actions (scene)
  33016. if (parsedData.actions) {
  33017. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  33018. }
  33019. // Finish
  33020. return true;
  33021. }
  33022. catch (err) {
  33023. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  33024. log = null;
  33025. throw err;
  33026. }
  33027. finally {
  33028. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  33029. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  33030. }
  33031. }
  33032. }
  33033. });
  33034. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33035. })(BABYLON || (BABYLON = {}));
  33036. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  33037. var BABYLON;
  33038. (function (BABYLON) {
  33039. var SpriteManager = (function () {
  33040. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  33041. if (epsilon === void 0) { epsilon = 0.01; }
  33042. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33043. this.name = name;
  33044. this.sprites = new Array();
  33045. this.renderingGroupId = 0;
  33046. this.layerMask = 0x0FFFFFFF;
  33047. this.fogEnabled = true;
  33048. this.isPickable = false;
  33049. /**
  33050. * An event triggered when the manager is disposed.
  33051. * @type {BABYLON.Observable}
  33052. */
  33053. this.onDisposeObservable = new BABYLON.Observable();
  33054. this._vertexBuffers = {};
  33055. this._capacity = capacity;
  33056. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  33057. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33058. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33059. if (cellSize.width && cellSize.height) {
  33060. this.cellWidth = cellSize.width;
  33061. this.cellHeight = cellSize.height;
  33062. }
  33063. else if (cellSize !== undefined) {
  33064. this.cellWidth = cellSize;
  33065. this.cellHeight = cellSize;
  33066. }
  33067. else {
  33068. return;
  33069. }
  33070. this._epsilon = epsilon;
  33071. this._scene = scene;
  33072. this._scene.spriteManagers.push(this);
  33073. var indices = [];
  33074. var index = 0;
  33075. for (var count = 0; count < capacity; count++) {
  33076. indices.push(index);
  33077. indices.push(index + 1);
  33078. indices.push(index + 2);
  33079. indices.push(index);
  33080. indices.push(index + 2);
  33081. indices.push(index + 3);
  33082. index += 4;
  33083. }
  33084. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  33085. // VBO
  33086. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  33087. this._vertexData = new Float32Array(capacity * 16 * 4);
  33088. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  33089. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  33090. var options = this._buffer.createVertexBuffer("options", 4, 4);
  33091. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  33092. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  33093. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  33094. this._vertexBuffers["options"] = options;
  33095. this._vertexBuffers["cellInfo"] = cellInfo;
  33096. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  33097. // Effects
  33098. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  33099. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  33100. }
  33101. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  33102. set: function (callback) {
  33103. if (this._onDisposeObserver) {
  33104. this.onDisposeObservable.remove(this._onDisposeObserver);
  33105. }
  33106. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  33107. },
  33108. enumerable: true,
  33109. configurable: true
  33110. });
  33111. Object.defineProperty(SpriteManager.prototype, "texture", {
  33112. get: function () {
  33113. return this._spriteTexture;
  33114. },
  33115. set: function (value) {
  33116. this._spriteTexture = value;
  33117. },
  33118. enumerable: true,
  33119. configurable: true
  33120. });
  33121. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  33122. var arrayOffset = index * 16;
  33123. if (offsetX === 0)
  33124. offsetX = this._epsilon;
  33125. else if (offsetX === 1)
  33126. offsetX = 1 - this._epsilon;
  33127. if (offsetY === 0)
  33128. offsetY = this._epsilon;
  33129. else if (offsetY === 1)
  33130. offsetY = 1 - this._epsilon;
  33131. this._vertexData[arrayOffset] = sprite.position.x;
  33132. this._vertexData[arrayOffset + 1] = sprite.position.y;
  33133. this._vertexData[arrayOffset + 2] = sprite.position.z;
  33134. this._vertexData[arrayOffset + 3] = sprite.angle;
  33135. this._vertexData[arrayOffset + 4] = sprite.width;
  33136. this._vertexData[arrayOffset + 5] = sprite.height;
  33137. this._vertexData[arrayOffset + 6] = offsetX;
  33138. this._vertexData[arrayOffset + 7] = offsetY;
  33139. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  33140. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  33141. var offset = (sprite.cellIndex / rowSize) >> 0;
  33142. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  33143. this._vertexData[arrayOffset + 11] = offset;
  33144. // Color
  33145. this._vertexData[arrayOffset + 12] = sprite.color.r;
  33146. this._vertexData[arrayOffset + 13] = sprite.color.g;
  33147. this._vertexData[arrayOffset + 14] = sprite.color.b;
  33148. this._vertexData[arrayOffset + 15] = sprite.color.a;
  33149. };
  33150. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  33151. var count = Math.min(this._capacity, this.sprites.length);
  33152. var min = BABYLON.Vector3.Zero();
  33153. var max = BABYLON.Vector3.Zero();
  33154. var distance = Number.MAX_VALUE;
  33155. var currentSprite;
  33156. var cameraSpacePosition = BABYLON.Vector3.Zero();
  33157. var cameraView = camera.getViewMatrix();
  33158. for (var index = 0; index < count; index++) {
  33159. var sprite = this.sprites[index];
  33160. if (!sprite) {
  33161. continue;
  33162. }
  33163. if (predicate) {
  33164. if (!predicate(sprite)) {
  33165. continue;
  33166. }
  33167. }
  33168. else if (!sprite.isPickable) {
  33169. continue;
  33170. }
  33171. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  33172. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  33173. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  33174. if (ray.intersectsBoxMinMax(min, max)) {
  33175. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  33176. if (distance > currentDistance) {
  33177. distance = currentDistance;
  33178. currentSprite = sprite;
  33179. if (fastCheck) {
  33180. break;
  33181. }
  33182. }
  33183. }
  33184. }
  33185. if (currentSprite) {
  33186. var result = new BABYLON.PickingInfo();
  33187. result.hit = true;
  33188. result.pickedSprite = currentSprite;
  33189. result.distance = distance;
  33190. return result;
  33191. }
  33192. return null;
  33193. };
  33194. SpriteManager.prototype.render = function () {
  33195. // Check
  33196. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  33197. return;
  33198. var engine = this._scene.getEngine();
  33199. var baseSize = this._spriteTexture.getBaseSize();
  33200. // Sprites
  33201. var deltaTime = engine.getDeltaTime();
  33202. var max = Math.min(this._capacity, this.sprites.length);
  33203. var rowSize = baseSize.width / this.cellWidth;
  33204. var offset = 0;
  33205. for (var index = 0; index < max; index++) {
  33206. var sprite = this.sprites[index];
  33207. if (!sprite) {
  33208. continue;
  33209. }
  33210. sprite._animate(deltaTime);
  33211. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  33212. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  33213. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  33214. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  33215. }
  33216. this._buffer.update(this._vertexData);
  33217. // Render
  33218. var effect = this._effectBase;
  33219. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  33220. effect = this._effectFog;
  33221. }
  33222. engine.enableEffect(effect);
  33223. var viewMatrix = this._scene.getViewMatrix();
  33224. effect.setTexture("diffuseSampler", this._spriteTexture);
  33225. effect.setMatrix("view", viewMatrix);
  33226. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  33227. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  33228. // Fog
  33229. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  33230. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  33231. effect.setColor3("vFogColor", this._scene.fogColor);
  33232. }
  33233. // VBOs
  33234. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33235. // Draw order
  33236. engine.setDepthFunctionToLessOrEqual();
  33237. effect.setBool("alphaTest", true);
  33238. engine.setColorWrite(false);
  33239. engine.draw(true, 0, max * 6);
  33240. engine.setColorWrite(true);
  33241. effect.setBool("alphaTest", false);
  33242. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  33243. engine.draw(true, 0, max * 6);
  33244. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33245. };
  33246. SpriteManager.prototype.dispose = function () {
  33247. if (this._buffer) {
  33248. this._buffer.dispose();
  33249. this._buffer = null;
  33250. }
  33251. if (this._indexBuffer) {
  33252. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33253. this._indexBuffer = null;
  33254. }
  33255. if (this._spriteTexture) {
  33256. this._spriteTexture.dispose();
  33257. this._spriteTexture = null;
  33258. }
  33259. // Remove from scene
  33260. var index = this._scene.spriteManagers.indexOf(this);
  33261. this._scene.spriteManagers.splice(index, 1);
  33262. // Callback
  33263. this.onDisposeObservable.notifyObservers(this);
  33264. this.onDisposeObservable.clear();
  33265. };
  33266. return SpriteManager;
  33267. }());
  33268. BABYLON.SpriteManager = SpriteManager;
  33269. })(BABYLON || (BABYLON = {}));
  33270. //# sourceMappingURL=babylon.spriteManager.js.map
  33271. var BABYLON;
  33272. (function (BABYLON) {
  33273. var Sprite = (function () {
  33274. function Sprite(name, manager) {
  33275. this.name = name;
  33276. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  33277. this.width = 1.0;
  33278. this.height = 1.0;
  33279. this.angle = 0;
  33280. this.cellIndex = 0;
  33281. this.invertU = 0;
  33282. this.invertV = 0;
  33283. this.animations = new Array();
  33284. this.isPickable = false;
  33285. this._animationStarted = false;
  33286. this._loopAnimation = false;
  33287. this._fromIndex = 0;
  33288. this._toIndex = 0;
  33289. this._delay = 0;
  33290. this._direction = 1;
  33291. this._frameCount = 0;
  33292. this._time = 0;
  33293. this._manager = manager;
  33294. this._manager.sprites.push(this);
  33295. this.position = BABYLON.Vector3.Zero();
  33296. }
  33297. Object.defineProperty(Sprite.prototype, "size", {
  33298. get: function () {
  33299. return this.width;
  33300. },
  33301. set: function (value) {
  33302. this.width = value;
  33303. this.height = value;
  33304. },
  33305. enumerable: true,
  33306. configurable: true
  33307. });
  33308. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  33309. this._fromIndex = from;
  33310. this._toIndex = to;
  33311. this._loopAnimation = loop;
  33312. this._delay = delay;
  33313. this._animationStarted = true;
  33314. this._direction = from < to ? 1 : -1;
  33315. this.cellIndex = from;
  33316. this._time = 0;
  33317. this._onAnimationEnd = onAnimationEnd;
  33318. };
  33319. Sprite.prototype.stopAnimation = function () {
  33320. this._animationStarted = false;
  33321. };
  33322. Sprite.prototype._animate = function (deltaTime) {
  33323. if (!this._animationStarted)
  33324. return;
  33325. this._time += deltaTime;
  33326. if (this._time > this._delay) {
  33327. this._time = this._time % this._delay;
  33328. this.cellIndex += this._direction;
  33329. if (this.cellIndex === this._toIndex) {
  33330. if (this._loopAnimation) {
  33331. this.cellIndex = this._fromIndex;
  33332. }
  33333. else {
  33334. this._animationStarted = false;
  33335. if (this._onAnimationEnd) {
  33336. this._onAnimationEnd();
  33337. }
  33338. if (this.disposeWhenFinishedAnimating) {
  33339. this.dispose();
  33340. }
  33341. }
  33342. }
  33343. }
  33344. };
  33345. Sprite.prototype.dispose = function () {
  33346. for (var i = 0; i < this._manager.sprites.length; i++) {
  33347. if (this._manager.sprites[i] == this) {
  33348. this._manager.sprites.splice(i, 1);
  33349. }
  33350. }
  33351. };
  33352. return Sprite;
  33353. }());
  33354. BABYLON.Sprite = Sprite;
  33355. })(BABYLON || (BABYLON = {}));
  33356. //# sourceMappingURL=babylon.sprite.js.map
  33357. var BABYLON;
  33358. (function (BABYLON) {
  33359. var Layer = (function () {
  33360. function Layer(name, imgUrl, scene, isBackground, color) {
  33361. this.name = name;
  33362. this.scale = new BABYLON.Vector2(1, 1);
  33363. this.offset = new BABYLON.Vector2(0, 0);
  33364. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  33365. this._vertexBuffers = {};
  33366. // Events
  33367. /**
  33368. * An event triggered when the layer is disposed.
  33369. * @type {BABYLON.Observable}
  33370. */
  33371. this.onDisposeObservable = new BABYLON.Observable();
  33372. /**
  33373. * An event triggered before rendering the scene
  33374. * @type {BABYLON.Observable}
  33375. */
  33376. this.onBeforeRenderObservable = new BABYLON.Observable();
  33377. /**
  33378. * An event triggered after rendering the scene
  33379. * @type {BABYLON.Observable}
  33380. */
  33381. this.onAfterRenderObservable = new BABYLON.Observable();
  33382. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  33383. this.isBackground = isBackground === undefined ? true : isBackground;
  33384. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  33385. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  33386. this._scene.layers.push(this);
  33387. var engine = scene.getEngine();
  33388. // VBO
  33389. var vertices = [];
  33390. vertices.push(1, 1);
  33391. vertices.push(-1, 1);
  33392. vertices.push(-1, -1);
  33393. vertices.push(1, -1);
  33394. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  33395. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  33396. // Indices
  33397. var indices = [];
  33398. indices.push(0);
  33399. indices.push(1);
  33400. indices.push(2);
  33401. indices.push(0);
  33402. indices.push(2);
  33403. indices.push(3);
  33404. this._indexBuffer = engine.createIndexBuffer(indices);
  33405. // Effects
  33406. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  33407. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  33408. }
  33409. Object.defineProperty(Layer.prototype, "onDispose", {
  33410. set: function (callback) {
  33411. if (this._onDisposeObserver) {
  33412. this.onDisposeObservable.remove(this._onDisposeObserver);
  33413. }
  33414. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  33415. },
  33416. enumerable: true,
  33417. configurable: true
  33418. });
  33419. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  33420. set: function (callback) {
  33421. if (this._onBeforeRenderObserver) {
  33422. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  33423. }
  33424. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  33425. },
  33426. enumerable: true,
  33427. configurable: true
  33428. });
  33429. Object.defineProperty(Layer.prototype, "onAfterRender", {
  33430. set: function (callback) {
  33431. if (this._onAfterRenderObserver) {
  33432. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  33433. }
  33434. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  33435. },
  33436. enumerable: true,
  33437. configurable: true
  33438. });
  33439. Layer.prototype.render = function () {
  33440. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  33441. // Check
  33442. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  33443. return;
  33444. var engine = this._scene.getEngine();
  33445. this.onBeforeRenderObservable.notifyObservers(this);
  33446. // Render
  33447. engine.enableEffect(currentEffect);
  33448. engine.setState(false);
  33449. // Texture
  33450. currentEffect.setTexture("textureSampler", this.texture);
  33451. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  33452. // Color
  33453. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  33454. // Scale / offset
  33455. currentEffect.setVector2("offset", this.offset);
  33456. currentEffect.setVector2("scale", this.scale);
  33457. // VBOs
  33458. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  33459. // Draw order
  33460. if (!this.alphaTest) {
  33461. engine.setAlphaMode(this.alphaBlendingMode);
  33462. engine.draw(true, 0, 6);
  33463. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33464. }
  33465. else {
  33466. engine.draw(true, 0, 6);
  33467. }
  33468. this.onAfterRenderObservable.notifyObservers(this);
  33469. };
  33470. Layer.prototype.dispose = function () {
  33471. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33472. if (vertexBuffer) {
  33473. vertexBuffer.dispose();
  33474. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33475. }
  33476. if (this._indexBuffer) {
  33477. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33478. this._indexBuffer = null;
  33479. }
  33480. if (this.texture) {
  33481. this.texture.dispose();
  33482. this.texture = null;
  33483. }
  33484. // Remove from scene
  33485. var index = this._scene.layers.indexOf(this);
  33486. this._scene.layers.splice(index, 1);
  33487. // Callback
  33488. this.onDisposeObservable.notifyObservers(this);
  33489. this.onDisposeObservable.clear();
  33490. this.onAfterRenderObservable.clear();
  33491. this.onBeforeRenderObservable.clear();
  33492. };
  33493. return Layer;
  33494. }());
  33495. BABYLON.Layer = Layer;
  33496. })(BABYLON || (BABYLON = {}));
  33497. //# sourceMappingURL=babylon.layer.js.map
  33498. var BABYLON;
  33499. (function (BABYLON) {
  33500. var Particle = (function () {
  33501. function Particle() {
  33502. this.position = BABYLON.Vector3.Zero();
  33503. this.direction = BABYLON.Vector3.Zero();
  33504. this.color = new BABYLON.Color4(0, 0, 0, 0);
  33505. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  33506. this.lifeTime = 1.0;
  33507. this.age = 0;
  33508. this.size = 0;
  33509. this.angle = 0;
  33510. this.angularSpeed = 0;
  33511. }
  33512. Particle.prototype.copyTo = function (other) {
  33513. other.position.copyFrom(this.position);
  33514. other.direction.copyFrom(this.direction);
  33515. other.color.copyFrom(this.color);
  33516. other.colorStep.copyFrom(this.colorStep);
  33517. other.lifeTime = this.lifeTime;
  33518. other.age = this.age;
  33519. other.size = this.size;
  33520. other.angle = this.angle;
  33521. other.angularSpeed = this.angularSpeed;
  33522. };
  33523. return Particle;
  33524. }());
  33525. BABYLON.Particle = Particle;
  33526. })(BABYLON || (BABYLON = {}));
  33527. //# sourceMappingURL=babylon.particle.js.map
  33528. var BABYLON;
  33529. (function (BABYLON) {
  33530. var randomNumber = function (min, max) {
  33531. if (min === max) {
  33532. return (min);
  33533. }
  33534. var random = Math.random();
  33535. return ((random * (max - min)) + min);
  33536. };
  33537. var ParticleSystem = (function () {
  33538. function ParticleSystem(name, capacity, scene, customEffect) {
  33539. var _this = this;
  33540. this.name = name;
  33541. // Members
  33542. this.animations = [];
  33543. this.renderingGroupId = 0;
  33544. this.emitter = null;
  33545. this.emitRate = 10;
  33546. this.manualEmitCount = -1;
  33547. this.updateSpeed = 0.01;
  33548. this.targetStopDuration = 0;
  33549. this.disposeOnStop = false;
  33550. this.minEmitPower = 1;
  33551. this.maxEmitPower = 1;
  33552. this.minLifeTime = 1;
  33553. this.maxLifeTime = 1;
  33554. this.minSize = 1;
  33555. this.maxSize = 1;
  33556. this.minAngularSpeed = 0;
  33557. this.maxAngularSpeed = 0;
  33558. this.layerMask = 0x0FFFFFFF;
  33559. this.customShader = null;
  33560. this.preventAutoStart = false;
  33561. /**
  33562. * An event triggered when the system is disposed.
  33563. * @type {BABYLON.Observable}
  33564. */
  33565. this.onDisposeObservable = new BABYLON.Observable();
  33566. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  33567. this.forceDepthWrite = false;
  33568. this.gravity = BABYLON.Vector3.Zero();
  33569. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  33570. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  33571. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  33572. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  33573. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  33574. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  33575. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  33576. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  33577. this.particles = new Array();
  33578. this._stockParticles = new Array();
  33579. this._newPartsExcess = 0;
  33580. this._vertexBuffers = {};
  33581. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  33582. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  33583. this._scaledDirection = BABYLON.Vector3.Zero();
  33584. this._scaledGravity = BABYLON.Vector3.Zero();
  33585. this._currentRenderId = -1;
  33586. this._started = false;
  33587. this._stopped = false;
  33588. this._actualFrame = 0;
  33589. this.id = name;
  33590. this._capacity = capacity;
  33591. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  33592. this._customEffect = customEffect;
  33593. scene.particleSystems.push(this);
  33594. var indices = [];
  33595. var index = 0;
  33596. for (var count = 0; count < capacity; count++) {
  33597. indices.push(index);
  33598. indices.push(index + 1);
  33599. indices.push(index + 2);
  33600. indices.push(index);
  33601. indices.push(index + 2);
  33602. indices.push(index + 3);
  33603. index += 4;
  33604. }
  33605. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  33606. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  33607. this._vertexData = new Float32Array(capacity * 11 * 4);
  33608. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  33609. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  33610. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  33611. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  33612. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  33613. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  33614. this._vertexBuffers["options"] = options;
  33615. // Default behaviors
  33616. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  33617. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  33618. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  33619. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  33620. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  33621. };
  33622. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  33623. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  33624. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  33625. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  33626. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  33627. };
  33628. this.updateFunction = function (particles) {
  33629. for (var index = 0; index < particles.length; index++) {
  33630. var particle = particles[index];
  33631. particle.age += _this._scaledUpdateSpeed;
  33632. if (particle.age >= particle.lifeTime) {
  33633. _this.recycleParticle(particle);
  33634. index--;
  33635. continue;
  33636. }
  33637. else {
  33638. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  33639. particle.color.addInPlace(_this._scaledColorStep);
  33640. if (particle.color.a < 0)
  33641. particle.color.a = 0;
  33642. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  33643. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  33644. particle.position.addInPlace(_this._scaledDirection);
  33645. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  33646. particle.direction.addInPlace(_this._scaledGravity);
  33647. }
  33648. }
  33649. };
  33650. }
  33651. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  33652. set: function (callback) {
  33653. if (this._onDisposeObserver) {
  33654. this.onDisposeObservable.remove(this._onDisposeObserver);
  33655. }
  33656. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  33657. },
  33658. enumerable: true,
  33659. configurable: true
  33660. });
  33661. ParticleSystem.prototype.recycleParticle = function (particle) {
  33662. var lastParticle = this.particles.pop();
  33663. if (lastParticle !== particle) {
  33664. lastParticle.copyTo(particle);
  33665. this._stockParticles.push(lastParticle);
  33666. }
  33667. };
  33668. ParticleSystem.prototype.getCapacity = function () {
  33669. return this._capacity;
  33670. };
  33671. ParticleSystem.prototype.isAlive = function () {
  33672. return this._alive;
  33673. };
  33674. ParticleSystem.prototype.isStarted = function () {
  33675. return this._started;
  33676. };
  33677. ParticleSystem.prototype.start = function () {
  33678. this._started = true;
  33679. this._stopped = false;
  33680. this._actualFrame = 0;
  33681. };
  33682. ParticleSystem.prototype.stop = function () {
  33683. this._stopped = true;
  33684. };
  33685. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  33686. var offset = index * 11;
  33687. this._vertexData[offset] = particle.position.x;
  33688. this._vertexData[offset + 1] = particle.position.y;
  33689. this._vertexData[offset + 2] = particle.position.z;
  33690. this._vertexData[offset + 3] = particle.color.r;
  33691. this._vertexData[offset + 4] = particle.color.g;
  33692. this._vertexData[offset + 5] = particle.color.b;
  33693. this._vertexData[offset + 6] = particle.color.a;
  33694. this._vertexData[offset + 7] = particle.angle;
  33695. this._vertexData[offset + 8] = particle.size;
  33696. this._vertexData[offset + 9] = offsetX;
  33697. this._vertexData[offset + 10] = offsetY;
  33698. };
  33699. ParticleSystem.prototype._update = function (newParticles) {
  33700. // Update current
  33701. this._alive = this.particles.length > 0;
  33702. this.updateFunction(this.particles);
  33703. // Add new ones
  33704. var worldMatrix;
  33705. if (this.emitter.position) {
  33706. worldMatrix = this.emitter.getWorldMatrix();
  33707. }
  33708. else {
  33709. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  33710. }
  33711. var particle;
  33712. for (var index = 0; index < newParticles; index++) {
  33713. if (this.particles.length === this._capacity) {
  33714. break;
  33715. }
  33716. if (this._stockParticles.length !== 0) {
  33717. particle = this._stockParticles.pop();
  33718. particle.age = 0;
  33719. }
  33720. else {
  33721. particle = new BABYLON.Particle();
  33722. }
  33723. this.particles.push(particle);
  33724. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  33725. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  33726. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  33727. particle.size = randomNumber(this.minSize, this.maxSize);
  33728. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  33729. this.startPositionFunction(worldMatrix, particle.position, particle);
  33730. var step = randomNumber(0, 1.0);
  33731. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  33732. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  33733. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  33734. }
  33735. };
  33736. ParticleSystem.prototype._getEffect = function () {
  33737. if (this._customEffect) {
  33738. return this._customEffect;
  33739. }
  33740. ;
  33741. var defines = [];
  33742. if (this._scene.clipPlane) {
  33743. defines.push("#define CLIPPLANE");
  33744. }
  33745. // Effect
  33746. var join = defines.join("\n");
  33747. if (this._cachedDefines !== join) {
  33748. this._cachedDefines = join;
  33749. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  33750. }
  33751. return this._effect;
  33752. };
  33753. ParticleSystem.prototype.animate = function () {
  33754. if (!this._started)
  33755. return;
  33756. var effect = this._getEffect();
  33757. // Check
  33758. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  33759. return;
  33760. if (this._currentRenderId === this._scene.getRenderId()) {
  33761. return;
  33762. }
  33763. this._currentRenderId = this._scene.getRenderId();
  33764. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  33765. // determine the number of particles we need to create
  33766. var newParticles;
  33767. if (this.manualEmitCount > -1) {
  33768. newParticles = this.manualEmitCount;
  33769. this._newPartsExcess = 0;
  33770. this.manualEmitCount = 0;
  33771. }
  33772. else {
  33773. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  33774. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  33775. }
  33776. if (this._newPartsExcess > 1.0) {
  33777. newParticles += this._newPartsExcess >> 0;
  33778. this._newPartsExcess -= this._newPartsExcess >> 0;
  33779. }
  33780. this._alive = false;
  33781. if (!this._stopped) {
  33782. this._actualFrame += this._scaledUpdateSpeed;
  33783. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  33784. this.stop();
  33785. }
  33786. else {
  33787. newParticles = 0;
  33788. }
  33789. this._update(newParticles);
  33790. // Stopped?
  33791. if (this._stopped) {
  33792. if (!this._alive) {
  33793. this._started = false;
  33794. if (this.disposeOnStop) {
  33795. this._scene._toBeDisposed.push(this);
  33796. }
  33797. }
  33798. }
  33799. // Update VBO
  33800. var offset = 0;
  33801. for (var index = 0; index < this.particles.length; index++) {
  33802. var particle = this.particles[index];
  33803. this._appendParticleVertex(offset++, particle, 0, 0);
  33804. this._appendParticleVertex(offset++, particle, 1, 0);
  33805. this._appendParticleVertex(offset++, particle, 1, 1);
  33806. this._appendParticleVertex(offset++, particle, 0, 1);
  33807. }
  33808. this._vertexBuffer.update(this._vertexData);
  33809. };
  33810. ParticleSystem.prototype.render = function () {
  33811. var effect = this._getEffect();
  33812. // Check
  33813. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  33814. return 0;
  33815. var engine = this._scene.getEngine();
  33816. // Render
  33817. engine.enableEffect(effect);
  33818. engine.setState(false);
  33819. var viewMatrix = this._scene.getViewMatrix();
  33820. effect.setTexture("diffuseSampler", this.particleTexture);
  33821. effect.setMatrix("view", viewMatrix);
  33822. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  33823. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  33824. if (this._scene.clipPlane) {
  33825. var clipPlane = this._scene.clipPlane;
  33826. var invView = viewMatrix.clone();
  33827. invView.invert();
  33828. effect.setMatrix("invView", invView);
  33829. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  33830. }
  33831. // VBOs
  33832. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33833. // Draw order
  33834. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  33835. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  33836. }
  33837. else {
  33838. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  33839. }
  33840. if (this.forceDepthWrite) {
  33841. engine.setDepthWrite(true);
  33842. }
  33843. engine.draw(true, 0, this.particles.length * 6);
  33844. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33845. return this.particles.length;
  33846. };
  33847. ParticleSystem.prototype.dispose = function () {
  33848. if (this._vertexBuffer) {
  33849. this._vertexBuffer.dispose();
  33850. this._vertexBuffer = null;
  33851. }
  33852. if (this._indexBuffer) {
  33853. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33854. this._indexBuffer = null;
  33855. }
  33856. if (this.particleTexture) {
  33857. this.particleTexture.dispose();
  33858. this.particleTexture = null;
  33859. }
  33860. // Remove from scene
  33861. var index = this._scene.particleSystems.indexOf(this);
  33862. this._scene.particleSystems.splice(index, 1);
  33863. // Callback
  33864. this.onDisposeObservable.notifyObservers(this);
  33865. this.onDisposeObservable.clear();
  33866. };
  33867. // Clone
  33868. ParticleSystem.prototype.clone = function (name, newEmitter) {
  33869. var custom = null;
  33870. var program = null;
  33871. if (this.customShader != null) {
  33872. program = this.customShader;
  33873. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  33874. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  33875. }
  33876. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  33877. result.customShader = program;
  33878. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  33879. if (newEmitter === undefined) {
  33880. newEmitter = this.emitter;
  33881. }
  33882. result.emitter = newEmitter;
  33883. if (this.particleTexture) {
  33884. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  33885. }
  33886. if (!this.preventAutoStart) {
  33887. result.start();
  33888. }
  33889. return result;
  33890. };
  33891. ParticleSystem.prototype.serialize = function () {
  33892. var serializationObject = {};
  33893. serializationObject.name = this.name;
  33894. serializationObject.id = this.id;
  33895. // Emitter
  33896. if (this.emitter.position) {
  33897. serializationObject.emitterId = this.emitter.id;
  33898. }
  33899. else {
  33900. serializationObject.emitter = this.emitter.asArray();
  33901. }
  33902. serializationObject.capacity = this.getCapacity();
  33903. if (this.particleTexture) {
  33904. serializationObject.textureName = this.particleTexture.name;
  33905. }
  33906. // Animations
  33907. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33908. // Particle system
  33909. serializationObject.minAngularSpeed = this.minAngularSpeed;
  33910. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  33911. serializationObject.minSize = this.minSize;
  33912. serializationObject.maxSize = this.maxSize;
  33913. serializationObject.minEmitPower = this.minEmitPower;
  33914. serializationObject.maxEmitPower = this.maxEmitPower;
  33915. serializationObject.minLifeTime = this.minLifeTime;
  33916. serializationObject.maxLifeTime = this.maxLifeTime;
  33917. serializationObject.emitRate = this.emitRate;
  33918. serializationObject.minEmitBox = this.minEmitBox.asArray();
  33919. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  33920. serializationObject.gravity = this.gravity.asArray();
  33921. serializationObject.direction1 = this.direction1.asArray();
  33922. serializationObject.direction2 = this.direction2.asArray();
  33923. serializationObject.color1 = this.color1.asArray();
  33924. serializationObject.color2 = this.color2.asArray();
  33925. serializationObject.colorDead = this.colorDead.asArray();
  33926. serializationObject.updateSpeed = this.updateSpeed;
  33927. serializationObject.targetStopDuration = this.targetStopDuration;
  33928. serializationObject.textureMask = this.textureMask.asArray();
  33929. serializationObject.blendMode = this.blendMode;
  33930. serializationObject.customShader = this.customShader;
  33931. serializationObject.preventAutoStart = this.preventAutoStart;
  33932. return serializationObject;
  33933. };
  33934. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  33935. var name = parsedParticleSystem.name;
  33936. var custom = null;
  33937. var program = null;
  33938. if (parsedParticleSystem.customShader) {
  33939. program = parsedParticleSystem.customShader;
  33940. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  33941. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  33942. }
  33943. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  33944. particleSystem.customShader = program;
  33945. if (parsedParticleSystem.id) {
  33946. particleSystem.id = parsedParticleSystem.id;
  33947. }
  33948. // Auto start
  33949. if (parsedParticleSystem.preventAutoStart) {
  33950. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  33951. }
  33952. // Texture
  33953. if (parsedParticleSystem.textureName) {
  33954. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  33955. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  33956. }
  33957. // Emitter
  33958. if (parsedParticleSystem.emitterId) {
  33959. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  33960. }
  33961. else {
  33962. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  33963. }
  33964. // Animations
  33965. if (parsedParticleSystem.animations) {
  33966. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  33967. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  33968. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33969. }
  33970. }
  33971. if (parsedParticleSystem.autoAnimate) {
  33972. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  33973. }
  33974. // Particle system
  33975. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  33976. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  33977. particleSystem.minSize = parsedParticleSystem.minSize;
  33978. particleSystem.maxSize = parsedParticleSystem.maxSize;
  33979. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  33980. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  33981. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  33982. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  33983. particleSystem.emitRate = parsedParticleSystem.emitRate;
  33984. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  33985. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  33986. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  33987. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  33988. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  33989. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  33990. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  33991. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  33992. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  33993. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  33994. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  33995. particleSystem.blendMode = parsedParticleSystem.blendMode;
  33996. if (!particleSystem.preventAutoStart) {
  33997. particleSystem.start();
  33998. }
  33999. return particleSystem;
  34000. };
  34001. return ParticleSystem;
  34002. }());
  34003. // Statics
  34004. ParticleSystem.BLENDMODE_ONEONE = 0;
  34005. ParticleSystem.BLENDMODE_STANDARD = 1;
  34006. BABYLON.ParticleSystem = ParticleSystem;
  34007. })(BABYLON || (BABYLON = {}));
  34008. //# sourceMappingURL=babylon.particleSystem.js.map
  34009. var BABYLON;
  34010. (function (BABYLON) {
  34011. var AnimationRange = (function () {
  34012. function AnimationRange(name, from, to) {
  34013. this.name = name;
  34014. this.from = from;
  34015. this.to = to;
  34016. }
  34017. AnimationRange.prototype.clone = function () {
  34018. return new AnimationRange(this.name, this.from, this.to);
  34019. };
  34020. return AnimationRange;
  34021. }());
  34022. BABYLON.AnimationRange = AnimationRange;
  34023. /**
  34024. * Composed of a frame, and an action function
  34025. */
  34026. var AnimationEvent = (function () {
  34027. function AnimationEvent(frame, action, onlyOnce) {
  34028. this.frame = frame;
  34029. this.action = action;
  34030. this.onlyOnce = onlyOnce;
  34031. this.isDone = false;
  34032. }
  34033. return AnimationEvent;
  34034. }());
  34035. BABYLON.AnimationEvent = AnimationEvent;
  34036. var PathCursor = (function () {
  34037. function PathCursor(path) {
  34038. this.path = path;
  34039. this._onchange = new Array();
  34040. this.value = 0;
  34041. this.animations = new Array();
  34042. }
  34043. PathCursor.prototype.getPoint = function () {
  34044. var point = this.path.getPointAtLengthPosition(this.value);
  34045. return new BABYLON.Vector3(point.x, 0, point.y);
  34046. };
  34047. PathCursor.prototype.moveAhead = function (step) {
  34048. if (step === void 0) { step = 0.002; }
  34049. this.move(step);
  34050. return this;
  34051. };
  34052. PathCursor.prototype.moveBack = function (step) {
  34053. if (step === void 0) { step = 0.002; }
  34054. this.move(-step);
  34055. return this;
  34056. };
  34057. PathCursor.prototype.move = function (step) {
  34058. if (Math.abs(step) > 1) {
  34059. throw "step size should be less than 1.";
  34060. }
  34061. this.value += step;
  34062. this.ensureLimits();
  34063. this.raiseOnChange();
  34064. return this;
  34065. };
  34066. PathCursor.prototype.ensureLimits = function () {
  34067. while (this.value > 1) {
  34068. this.value -= 1;
  34069. }
  34070. while (this.value < 0) {
  34071. this.value += 1;
  34072. }
  34073. return this;
  34074. };
  34075. // used by animation engine
  34076. PathCursor.prototype.markAsDirty = function (propertyName) {
  34077. this.ensureLimits();
  34078. this.raiseOnChange();
  34079. return this;
  34080. };
  34081. PathCursor.prototype.raiseOnChange = function () {
  34082. var _this = this;
  34083. this._onchange.forEach(function (f) { return f(_this); });
  34084. return this;
  34085. };
  34086. PathCursor.prototype.onchange = function (f) {
  34087. this._onchange.push(f);
  34088. return this;
  34089. };
  34090. return PathCursor;
  34091. }());
  34092. BABYLON.PathCursor = PathCursor;
  34093. var Animation = (function () {
  34094. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  34095. this.name = name;
  34096. this.targetProperty = targetProperty;
  34097. this.framePerSecond = framePerSecond;
  34098. this.dataType = dataType;
  34099. this.loopMode = loopMode;
  34100. this.enableBlending = enableBlending;
  34101. this._offsetsCache = {};
  34102. this._highLimitsCache = {};
  34103. this._stopped = false;
  34104. this._blendingFactor = 0;
  34105. // The set of event that will be linked to this animation
  34106. this._events = new Array();
  34107. this.allowMatricesInterpolation = false;
  34108. this.blendingSpeed = 0.01;
  34109. this._ranges = {};
  34110. this.targetPropertyPath = targetProperty.split(".");
  34111. this.dataType = dataType;
  34112. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  34113. }
  34114. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  34115. var dataType = undefined;
  34116. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  34117. dataType = Animation.ANIMATIONTYPE_FLOAT;
  34118. }
  34119. else if (from instanceof BABYLON.Quaternion) {
  34120. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  34121. }
  34122. else if (from instanceof BABYLON.Vector3) {
  34123. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  34124. }
  34125. else if (from instanceof BABYLON.Vector2) {
  34126. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  34127. }
  34128. else if (from instanceof BABYLON.Color3) {
  34129. dataType = Animation.ANIMATIONTYPE_COLOR3;
  34130. }
  34131. else if (from instanceof BABYLON.Size) {
  34132. dataType = Animation.ANIMATIONTYPE_SIZE;
  34133. }
  34134. if (dataType == undefined) {
  34135. return null;
  34136. }
  34137. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  34138. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  34139. animation.setKeys(keys);
  34140. if (easingFunction !== undefined) {
  34141. animation.setEasingFunction(easingFunction);
  34142. }
  34143. return animation;
  34144. };
  34145. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  34146. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  34147. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  34148. };
  34149. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  34150. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  34151. node.animations.push(animation);
  34152. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  34153. };
  34154. // Methods
  34155. /**
  34156. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  34157. */
  34158. Animation.prototype.toString = function (fullDetails) {
  34159. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  34160. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  34161. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  34162. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  34163. if (fullDetails) {
  34164. ret += ", Ranges: {";
  34165. var first = true;
  34166. for (var name in this._ranges) {
  34167. if (first) {
  34168. ret += ", ";
  34169. first = false;
  34170. }
  34171. ret += name;
  34172. }
  34173. ret += "}";
  34174. }
  34175. return ret;
  34176. };
  34177. /**
  34178. * Add an event to this animation.
  34179. */
  34180. Animation.prototype.addEvent = function (event) {
  34181. this._events.push(event);
  34182. };
  34183. /**
  34184. * Remove all events found at the given frame
  34185. * @param frame
  34186. */
  34187. Animation.prototype.removeEvents = function (frame) {
  34188. for (var index = 0; index < this._events.length; index++) {
  34189. if (this._events[index].frame === frame) {
  34190. this._events.splice(index, 1);
  34191. index--;
  34192. }
  34193. }
  34194. };
  34195. Animation.prototype.createRange = function (name, from, to) {
  34196. // check name not already in use; could happen for bones after serialized
  34197. if (!this._ranges[name]) {
  34198. this._ranges[name] = new AnimationRange(name, from, to);
  34199. }
  34200. };
  34201. Animation.prototype.deleteRange = function (name, deleteFrames) {
  34202. if (deleteFrames === void 0) { deleteFrames = true; }
  34203. if (this._ranges[name]) {
  34204. if (deleteFrames) {
  34205. var from = this._ranges[name].from;
  34206. var to = this._ranges[name].to;
  34207. // this loop MUST go high to low for multiple splices to work
  34208. for (var key = this._keys.length - 1; key >= 0; key--) {
  34209. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  34210. this._keys.splice(key, 1);
  34211. }
  34212. }
  34213. }
  34214. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  34215. }
  34216. };
  34217. Animation.prototype.getRange = function (name) {
  34218. return this._ranges[name];
  34219. };
  34220. Animation.prototype.reset = function () {
  34221. this._offsetsCache = {};
  34222. this._highLimitsCache = {};
  34223. this.currentFrame = 0;
  34224. this._blendingFactor = 0;
  34225. this._originalBlendValue = null;
  34226. };
  34227. Animation.prototype.isStopped = function () {
  34228. return this._stopped;
  34229. };
  34230. Animation.prototype.getKeys = function () {
  34231. return this._keys;
  34232. };
  34233. Animation.prototype.getHighestFrame = function () {
  34234. var ret = 0;
  34235. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  34236. if (ret < this._keys[key].frame) {
  34237. ret = this._keys[key].frame;
  34238. }
  34239. }
  34240. return ret;
  34241. };
  34242. Animation.prototype.getEasingFunction = function () {
  34243. return this._easingFunction;
  34244. };
  34245. Animation.prototype.setEasingFunction = function (easingFunction) {
  34246. this._easingFunction = easingFunction;
  34247. };
  34248. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  34249. return startValue + (endValue - startValue) * gradient;
  34250. };
  34251. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  34252. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  34253. };
  34254. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  34255. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  34256. };
  34257. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  34258. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  34259. };
  34260. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  34261. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  34262. };
  34263. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  34264. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  34265. };
  34266. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  34267. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  34268. };
  34269. Animation.prototype.clone = function () {
  34270. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  34271. clone.enableBlending = this.enableBlending;
  34272. clone.blendingSpeed = this.blendingSpeed;
  34273. if (this._keys) {
  34274. clone.setKeys(this._keys);
  34275. }
  34276. if (this._ranges) {
  34277. clone._ranges = {};
  34278. for (var name in this._ranges) {
  34279. clone._ranges[name] = this._ranges[name].clone();
  34280. }
  34281. }
  34282. return clone;
  34283. };
  34284. Animation.prototype.setKeys = function (values) {
  34285. this._keys = values.slice(0);
  34286. this._offsetsCache = {};
  34287. this._highLimitsCache = {};
  34288. };
  34289. Animation.prototype._getKeyValue = function (value) {
  34290. if (typeof value === "function") {
  34291. return value();
  34292. }
  34293. return value;
  34294. };
  34295. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  34296. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  34297. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  34298. }
  34299. this.currentFrame = currentFrame;
  34300. // Try to get a hash to find the right key
  34301. 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));
  34302. if (this._keys[startKey].frame >= currentFrame) {
  34303. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  34304. startKey--;
  34305. }
  34306. }
  34307. for (var key = startKey; key < this._keys.length; key++) {
  34308. if (this._keys[key + 1].frame >= currentFrame) {
  34309. var startValue = this._getKeyValue(this._keys[key].value);
  34310. var endValue = this._getKeyValue(this._keys[key + 1].value);
  34311. // gradient : percent of currentFrame between the frame inf and the frame sup
  34312. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  34313. // check for easingFunction and correction of gradient
  34314. if (this._easingFunction != null) {
  34315. gradient = this._easingFunction.ease(gradient);
  34316. }
  34317. switch (this.dataType) {
  34318. // Float
  34319. case Animation.ANIMATIONTYPE_FLOAT:
  34320. switch (loopMode) {
  34321. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34322. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34323. return this.floatInterpolateFunction(startValue, endValue, gradient);
  34324. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34325. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  34326. }
  34327. break;
  34328. // Quaternion
  34329. case Animation.ANIMATIONTYPE_QUATERNION:
  34330. var quaternion = null;
  34331. switch (loopMode) {
  34332. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34333. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34334. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  34335. break;
  34336. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34337. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34338. break;
  34339. }
  34340. return quaternion;
  34341. // Vector3
  34342. case Animation.ANIMATIONTYPE_VECTOR3:
  34343. switch (loopMode) {
  34344. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34345. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34346. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  34347. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34348. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34349. }
  34350. // Vector2
  34351. case Animation.ANIMATIONTYPE_VECTOR2:
  34352. switch (loopMode) {
  34353. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34354. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34355. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  34356. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34357. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34358. }
  34359. // Size
  34360. case Animation.ANIMATIONTYPE_SIZE:
  34361. switch (loopMode) {
  34362. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34363. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34364. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  34365. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34366. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34367. }
  34368. // Color3
  34369. case Animation.ANIMATIONTYPE_COLOR3:
  34370. switch (loopMode) {
  34371. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34372. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34373. return this.color3InterpolateFunction(startValue, endValue, gradient);
  34374. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34375. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34376. }
  34377. // Matrix
  34378. case Animation.ANIMATIONTYPE_MATRIX:
  34379. switch (loopMode) {
  34380. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34381. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34382. if (this.allowMatricesInterpolation) {
  34383. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  34384. }
  34385. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34386. return startValue;
  34387. }
  34388. default:
  34389. break;
  34390. }
  34391. break;
  34392. }
  34393. }
  34394. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  34395. };
  34396. Animation.prototype.setValue = function (currentValue, blend) {
  34397. if (blend === void 0) { blend = false; }
  34398. // Set value
  34399. var path;
  34400. var destination;
  34401. if (this.targetPropertyPath.length > 1) {
  34402. var property = this._target[this.targetPropertyPath[0]];
  34403. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  34404. property = property[this.targetPropertyPath[index]];
  34405. }
  34406. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  34407. destination = property;
  34408. }
  34409. else {
  34410. path = this.targetPropertyPath[0];
  34411. destination = this._target;
  34412. }
  34413. // Blending
  34414. if (this.enableBlending && this._blendingFactor <= 1.0) {
  34415. if (!this._originalBlendValue) {
  34416. if (destination[path].clone) {
  34417. this._originalBlendValue = destination[path].clone();
  34418. }
  34419. else {
  34420. this._originalBlendValue = destination[path];
  34421. }
  34422. }
  34423. if (this._originalBlendValue.prototype) {
  34424. if (this._originalBlendValue.prototype.Lerp) {
  34425. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  34426. }
  34427. else {
  34428. destination[path] = currentValue;
  34429. }
  34430. }
  34431. else if (this._originalBlendValue.m) {
  34432. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  34433. }
  34434. else {
  34435. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  34436. }
  34437. this._blendingFactor += this.blendingSpeed;
  34438. }
  34439. else {
  34440. destination[path] = currentValue;
  34441. }
  34442. if (this._target.markAsDirty) {
  34443. this._target.markAsDirty(this.targetProperty);
  34444. }
  34445. };
  34446. Animation.prototype.goToFrame = function (frame) {
  34447. if (frame < this._keys[0].frame) {
  34448. frame = this._keys[0].frame;
  34449. }
  34450. else if (frame > this._keys[this._keys.length - 1].frame) {
  34451. frame = this._keys[this._keys.length - 1].frame;
  34452. }
  34453. var currentValue = this._interpolate(frame, 0, this.loopMode);
  34454. this.setValue(currentValue);
  34455. };
  34456. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  34457. if (blend === void 0) { blend = false; }
  34458. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  34459. this._stopped = true;
  34460. return false;
  34461. }
  34462. var returnValue = true;
  34463. // Adding a start key at frame 0 if missing
  34464. if (this._keys[0].frame !== 0) {
  34465. var newKey = { frame: 0, value: this._keys[0].value };
  34466. this._keys.splice(0, 0, newKey);
  34467. }
  34468. // Check limits
  34469. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  34470. from = this._keys[0].frame;
  34471. }
  34472. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  34473. to = this._keys[this._keys.length - 1].frame;
  34474. }
  34475. //to and from cannot be the same key
  34476. if (from === to) {
  34477. from++;
  34478. }
  34479. // Compute ratio
  34480. var range = to - from;
  34481. var offsetValue;
  34482. // ratio represents the frame delta between from and to
  34483. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  34484. var highLimitValue = 0;
  34485. if (ratio > range && !loop) {
  34486. returnValue = false;
  34487. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  34488. }
  34489. else {
  34490. // Get max value if required
  34491. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  34492. var keyOffset = to.toString() + from.toString();
  34493. if (!this._offsetsCache[keyOffset]) {
  34494. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34495. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34496. switch (this.dataType) {
  34497. // Float
  34498. case Animation.ANIMATIONTYPE_FLOAT:
  34499. this._offsetsCache[keyOffset] = toValue - fromValue;
  34500. break;
  34501. // Quaternion
  34502. case Animation.ANIMATIONTYPE_QUATERNION:
  34503. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34504. break;
  34505. // Vector3
  34506. case Animation.ANIMATIONTYPE_VECTOR3:
  34507. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34508. // Vector2
  34509. case Animation.ANIMATIONTYPE_VECTOR2:
  34510. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34511. // Size
  34512. case Animation.ANIMATIONTYPE_SIZE:
  34513. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34514. // Color3
  34515. case Animation.ANIMATIONTYPE_COLOR3:
  34516. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34517. default:
  34518. break;
  34519. }
  34520. this._highLimitsCache[keyOffset] = toValue;
  34521. }
  34522. highLimitValue = this._highLimitsCache[keyOffset];
  34523. offsetValue = this._offsetsCache[keyOffset];
  34524. }
  34525. }
  34526. if (offsetValue === undefined) {
  34527. switch (this.dataType) {
  34528. // Float
  34529. case Animation.ANIMATIONTYPE_FLOAT:
  34530. offsetValue = 0;
  34531. break;
  34532. // Quaternion
  34533. case Animation.ANIMATIONTYPE_QUATERNION:
  34534. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  34535. break;
  34536. // Vector3
  34537. case Animation.ANIMATIONTYPE_VECTOR3:
  34538. offsetValue = BABYLON.Vector3.Zero();
  34539. break;
  34540. // Vector2
  34541. case Animation.ANIMATIONTYPE_VECTOR2:
  34542. offsetValue = BABYLON.Vector2.Zero();
  34543. break;
  34544. // Size
  34545. case Animation.ANIMATIONTYPE_SIZE:
  34546. offsetValue = BABYLON.Size.Zero();
  34547. break;
  34548. // Color3
  34549. case Animation.ANIMATIONTYPE_COLOR3:
  34550. offsetValue = BABYLON.Color3.Black();
  34551. }
  34552. }
  34553. // Compute value
  34554. var repeatCount = (ratio / range) >> 0;
  34555. var currentFrame = returnValue ? from + ratio % range : to;
  34556. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  34557. // Set value
  34558. this.setValue(currentValue);
  34559. // Check events
  34560. for (var index = 0; index < this._events.length; index++) {
  34561. if (currentFrame >= this._events[index].frame) {
  34562. var event = this._events[index];
  34563. if (!event.isDone) {
  34564. // If event should be done only once, remove it.
  34565. if (event.onlyOnce) {
  34566. this._events.splice(index, 1);
  34567. index--;
  34568. }
  34569. event.isDone = true;
  34570. event.action();
  34571. } // Don't do anything if the event has already be done.
  34572. }
  34573. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  34574. // reset event, the animation is looping
  34575. this._events[index].isDone = false;
  34576. }
  34577. }
  34578. if (!returnValue) {
  34579. this._stopped = true;
  34580. }
  34581. return returnValue;
  34582. };
  34583. Animation.prototype.serialize = function () {
  34584. var serializationObject = {};
  34585. serializationObject.name = this.name;
  34586. serializationObject.property = this.targetProperty;
  34587. serializationObject.framePerSecond = this.framePerSecond;
  34588. serializationObject.dataType = this.dataType;
  34589. serializationObject.loopBehavior = this.loopMode;
  34590. serializationObject.enableBlending = this.enableBlending;
  34591. serializationObject.blendingSpeed = this.blendingSpeed;
  34592. var dataType = this.dataType;
  34593. serializationObject.keys = [];
  34594. var keys = this.getKeys();
  34595. for (var index = 0; index < keys.length; index++) {
  34596. var animationKey = keys[index];
  34597. var key = {};
  34598. key.frame = animationKey.frame;
  34599. switch (dataType) {
  34600. case Animation.ANIMATIONTYPE_FLOAT:
  34601. key.values = [animationKey.value];
  34602. break;
  34603. case Animation.ANIMATIONTYPE_QUATERNION:
  34604. case Animation.ANIMATIONTYPE_MATRIX:
  34605. case Animation.ANIMATIONTYPE_VECTOR3:
  34606. case Animation.ANIMATIONTYPE_COLOR3:
  34607. key.values = animationKey.value.asArray();
  34608. break;
  34609. }
  34610. serializationObject.keys.push(key);
  34611. }
  34612. serializationObject.ranges = [];
  34613. for (var name in this._ranges) {
  34614. var range = {};
  34615. range.name = name;
  34616. range.from = this._ranges[name].from;
  34617. range.to = this._ranges[name].to;
  34618. serializationObject.ranges.push(range);
  34619. }
  34620. return serializationObject;
  34621. };
  34622. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  34623. get: function () {
  34624. return Animation._ANIMATIONTYPE_FLOAT;
  34625. },
  34626. enumerable: true,
  34627. configurable: true
  34628. });
  34629. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  34630. get: function () {
  34631. return Animation._ANIMATIONTYPE_VECTOR3;
  34632. },
  34633. enumerable: true,
  34634. configurable: true
  34635. });
  34636. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  34637. get: function () {
  34638. return Animation._ANIMATIONTYPE_VECTOR2;
  34639. },
  34640. enumerable: true,
  34641. configurable: true
  34642. });
  34643. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  34644. get: function () {
  34645. return Animation._ANIMATIONTYPE_SIZE;
  34646. },
  34647. enumerable: true,
  34648. configurable: true
  34649. });
  34650. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  34651. get: function () {
  34652. return Animation._ANIMATIONTYPE_QUATERNION;
  34653. },
  34654. enumerable: true,
  34655. configurable: true
  34656. });
  34657. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  34658. get: function () {
  34659. return Animation._ANIMATIONTYPE_MATRIX;
  34660. },
  34661. enumerable: true,
  34662. configurable: true
  34663. });
  34664. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  34665. get: function () {
  34666. return Animation._ANIMATIONTYPE_COLOR3;
  34667. },
  34668. enumerable: true,
  34669. configurable: true
  34670. });
  34671. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  34672. get: function () {
  34673. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  34674. },
  34675. enumerable: true,
  34676. configurable: true
  34677. });
  34678. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  34679. get: function () {
  34680. return Animation._ANIMATIONLOOPMODE_CYCLE;
  34681. },
  34682. enumerable: true,
  34683. configurable: true
  34684. });
  34685. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  34686. get: function () {
  34687. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  34688. },
  34689. enumerable: true,
  34690. configurable: true
  34691. });
  34692. Animation.Parse = function (parsedAnimation) {
  34693. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  34694. var dataType = parsedAnimation.dataType;
  34695. var keys = [];
  34696. var data;
  34697. var index;
  34698. if (parsedAnimation.enableBlending) {
  34699. animation.enableBlending = parsedAnimation.enableBlending;
  34700. }
  34701. if (parsedAnimation.blendingSpeed) {
  34702. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  34703. }
  34704. for (index = 0; index < parsedAnimation.keys.length; index++) {
  34705. var key = parsedAnimation.keys[index];
  34706. switch (dataType) {
  34707. case Animation.ANIMATIONTYPE_FLOAT:
  34708. data = key.values[0];
  34709. break;
  34710. case Animation.ANIMATIONTYPE_QUATERNION:
  34711. data = BABYLON.Quaternion.FromArray(key.values);
  34712. break;
  34713. case Animation.ANIMATIONTYPE_MATRIX:
  34714. data = BABYLON.Matrix.FromArray(key.values);
  34715. break;
  34716. case Animation.ANIMATIONTYPE_COLOR3:
  34717. data = BABYLON.Color3.FromArray(key.values);
  34718. break;
  34719. case Animation.ANIMATIONTYPE_VECTOR3:
  34720. default:
  34721. data = BABYLON.Vector3.FromArray(key.values);
  34722. break;
  34723. }
  34724. keys.push({
  34725. frame: key.frame,
  34726. value: data
  34727. });
  34728. }
  34729. animation.setKeys(keys);
  34730. if (parsedAnimation.ranges) {
  34731. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  34732. data = parsedAnimation.ranges[index];
  34733. animation.createRange(data.name, data.from, data.to);
  34734. }
  34735. }
  34736. return animation;
  34737. };
  34738. Animation.AppendSerializedAnimations = function (source, destination) {
  34739. if (source.animations) {
  34740. destination.animations = [];
  34741. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  34742. var animation = source.animations[animationIndex];
  34743. destination.animations.push(animation.serialize());
  34744. }
  34745. }
  34746. };
  34747. return Animation;
  34748. }());
  34749. // Statics
  34750. Animation._ANIMATIONTYPE_FLOAT = 0;
  34751. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  34752. Animation._ANIMATIONTYPE_QUATERNION = 2;
  34753. Animation._ANIMATIONTYPE_MATRIX = 3;
  34754. Animation._ANIMATIONTYPE_COLOR3 = 4;
  34755. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  34756. Animation._ANIMATIONTYPE_SIZE = 6;
  34757. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  34758. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  34759. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  34760. BABYLON.Animation = Animation;
  34761. })(BABYLON || (BABYLON = {}));
  34762. //# sourceMappingURL=babylon.animation.js.map
  34763. var BABYLON;
  34764. (function (BABYLON) {
  34765. var Animatable = (function () {
  34766. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  34767. if (fromFrame === void 0) { fromFrame = 0; }
  34768. if (toFrame === void 0) { toFrame = 100; }
  34769. if (loopAnimation === void 0) { loopAnimation = false; }
  34770. if (speedRatio === void 0) { speedRatio = 1.0; }
  34771. this.target = target;
  34772. this.fromFrame = fromFrame;
  34773. this.toFrame = toFrame;
  34774. this.loopAnimation = loopAnimation;
  34775. this.speedRatio = speedRatio;
  34776. this.onAnimationEnd = onAnimationEnd;
  34777. this._animations = new Array();
  34778. this._paused = false;
  34779. this.animationStarted = false;
  34780. if (animations) {
  34781. this.appendAnimations(target, animations);
  34782. }
  34783. this._scene = scene;
  34784. scene._activeAnimatables.push(this);
  34785. }
  34786. // Methods
  34787. Animatable.prototype.getAnimations = function () {
  34788. return this._animations;
  34789. };
  34790. Animatable.prototype.appendAnimations = function (target, animations) {
  34791. for (var index = 0; index < animations.length; index++) {
  34792. var animation = animations[index];
  34793. animation._target = target;
  34794. this._animations.push(animation);
  34795. }
  34796. };
  34797. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  34798. var animations = this._animations;
  34799. for (var index = 0; index < animations.length; index++) {
  34800. if (animations[index].targetProperty === property) {
  34801. return animations[index];
  34802. }
  34803. }
  34804. return null;
  34805. };
  34806. Animatable.prototype.reset = function () {
  34807. var animations = this._animations;
  34808. for (var index = 0; index < animations.length; index++) {
  34809. animations[index].reset();
  34810. }
  34811. this._localDelayOffset = null;
  34812. this._pausedDelay = null;
  34813. };
  34814. Animatable.prototype.enableBlending = function (blendingSpeed) {
  34815. var animations = this._animations;
  34816. for (var index = 0; index < animations.length; index++) {
  34817. animations[index].enableBlending = true;
  34818. animations[index].blendingSpeed = blendingSpeed;
  34819. }
  34820. };
  34821. Animatable.prototype.disableBlending = function () {
  34822. var animations = this._animations;
  34823. for (var index = 0; index < animations.length; index++) {
  34824. animations[index].enableBlending = false;
  34825. }
  34826. };
  34827. Animatable.prototype.goToFrame = function (frame) {
  34828. var animations = this._animations;
  34829. if (animations[0]) {
  34830. var fps = animations[0].framePerSecond;
  34831. var currentFrame = animations[0].currentFrame;
  34832. var adjustTime = frame - currentFrame;
  34833. var delay = adjustTime * 1000 / fps;
  34834. this._localDelayOffset -= delay;
  34835. }
  34836. for (var index = 0; index < animations.length; index++) {
  34837. animations[index].goToFrame(frame);
  34838. }
  34839. };
  34840. Animatable.prototype.pause = function () {
  34841. if (this._paused) {
  34842. return;
  34843. }
  34844. this._paused = true;
  34845. };
  34846. Animatable.prototype.restart = function () {
  34847. this._paused = false;
  34848. };
  34849. Animatable.prototype.stop = function (animationName) {
  34850. if (animationName) {
  34851. var idx = this._scene._activeAnimatables.indexOf(this);
  34852. if (idx > -1) {
  34853. var animations = this._animations;
  34854. for (var index = animations.length - 1; index >= 0; index--) {
  34855. if (typeof animationName === "string" && animations[index].name != animationName) {
  34856. continue;
  34857. }
  34858. animations[index].reset();
  34859. animations.splice(index, 1);
  34860. }
  34861. if (animations.length == 0) {
  34862. this._scene._activeAnimatables.splice(idx, 1);
  34863. if (this.onAnimationEnd) {
  34864. this.onAnimationEnd();
  34865. }
  34866. }
  34867. }
  34868. }
  34869. else {
  34870. var index = this._scene._activeAnimatables.indexOf(this);
  34871. if (index > -1) {
  34872. this._scene._activeAnimatables.splice(index, 1);
  34873. var animations = this._animations;
  34874. for (var index = 0; index < animations.length; index++) {
  34875. animations[index].reset();
  34876. }
  34877. if (this.onAnimationEnd) {
  34878. this.onAnimationEnd();
  34879. }
  34880. }
  34881. }
  34882. };
  34883. Animatable.prototype._animate = function (delay) {
  34884. if (this._paused) {
  34885. this.animationStarted = false;
  34886. if (!this._pausedDelay) {
  34887. this._pausedDelay = delay;
  34888. }
  34889. return true;
  34890. }
  34891. if (!this._localDelayOffset) {
  34892. this._localDelayOffset = delay;
  34893. }
  34894. else if (this._pausedDelay) {
  34895. this._localDelayOffset += delay - this._pausedDelay;
  34896. this._pausedDelay = null;
  34897. }
  34898. // Animating
  34899. var running = false;
  34900. var animations = this._animations;
  34901. var index;
  34902. for (index = 0; index < animations.length; index++) {
  34903. var animation = animations[index];
  34904. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  34905. running = running || isRunning;
  34906. }
  34907. this.animationStarted = running;
  34908. if (!running) {
  34909. // Remove from active animatables
  34910. index = this._scene._activeAnimatables.indexOf(this);
  34911. this._scene._activeAnimatables.splice(index, 1);
  34912. }
  34913. if (!running && this.onAnimationEnd) {
  34914. this.onAnimationEnd();
  34915. this.onAnimationEnd = null;
  34916. }
  34917. return running;
  34918. };
  34919. return Animatable;
  34920. }());
  34921. BABYLON.Animatable = Animatable;
  34922. })(BABYLON || (BABYLON = {}));
  34923. //# sourceMappingURL=babylon.animatable.js.map
  34924. var BABYLON;
  34925. (function (BABYLON) {
  34926. var EasingFunction = (function () {
  34927. function EasingFunction() {
  34928. // Properties
  34929. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  34930. }
  34931. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  34932. get: function () {
  34933. return EasingFunction._EASINGMODE_EASEIN;
  34934. },
  34935. enumerable: true,
  34936. configurable: true
  34937. });
  34938. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  34939. get: function () {
  34940. return EasingFunction._EASINGMODE_EASEOUT;
  34941. },
  34942. enumerable: true,
  34943. configurable: true
  34944. });
  34945. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  34946. get: function () {
  34947. return EasingFunction._EASINGMODE_EASEINOUT;
  34948. },
  34949. enumerable: true,
  34950. configurable: true
  34951. });
  34952. EasingFunction.prototype.setEasingMode = function (easingMode) {
  34953. var n = Math.min(Math.max(easingMode, 0), 2);
  34954. this._easingMode = n;
  34955. };
  34956. EasingFunction.prototype.getEasingMode = function () {
  34957. return this._easingMode;
  34958. };
  34959. EasingFunction.prototype.easeInCore = function (gradient) {
  34960. throw new Error('You must implement this method');
  34961. };
  34962. EasingFunction.prototype.ease = function (gradient) {
  34963. switch (this._easingMode) {
  34964. case EasingFunction.EASINGMODE_EASEIN:
  34965. return this.easeInCore(gradient);
  34966. case EasingFunction.EASINGMODE_EASEOUT:
  34967. return (1 - this.easeInCore(1 - gradient));
  34968. }
  34969. if (gradient >= 0.5) {
  34970. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  34971. }
  34972. return (this.easeInCore(gradient * 2) * 0.5);
  34973. };
  34974. return EasingFunction;
  34975. }());
  34976. //Statics
  34977. EasingFunction._EASINGMODE_EASEIN = 0;
  34978. EasingFunction._EASINGMODE_EASEOUT = 1;
  34979. EasingFunction._EASINGMODE_EASEINOUT = 2;
  34980. BABYLON.EasingFunction = EasingFunction;
  34981. var CircleEase = (function (_super) {
  34982. __extends(CircleEase, _super);
  34983. function CircleEase() {
  34984. return _super !== null && _super.apply(this, arguments) || this;
  34985. }
  34986. CircleEase.prototype.easeInCore = function (gradient) {
  34987. gradient = Math.max(0, Math.min(1, gradient));
  34988. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  34989. };
  34990. return CircleEase;
  34991. }(EasingFunction));
  34992. BABYLON.CircleEase = CircleEase;
  34993. var BackEase = (function (_super) {
  34994. __extends(BackEase, _super);
  34995. function BackEase(amplitude) {
  34996. if (amplitude === void 0) { amplitude = 1; }
  34997. var _this = _super.call(this) || this;
  34998. _this.amplitude = amplitude;
  34999. return _this;
  35000. }
  35001. BackEase.prototype.easeInCore = function (gradient) {
  35002. var num = Math.max(0, this.amplitude);
  35003. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  35004. };
  35005. return BackEase;
  35006. }(EasingFunction));
  35007. BABYLON.BackEase = BackEase;
  35008. var BounceEase = (function (_super) {
  35009. __extends(BounceEase, _super);
  35010. function BounceEase(bounces, bounciness) {
  35011. if (bounces === void 0) { bounces = 3; }
  35012. if (bounciness === void 0) { bounciness = 2; }
  35013. var _this = _super.call(this) || this;
  35014. _this.bounces = bounces;
  35015. _this.bounciness = bounciness;
  35016. return _this;
  35017. }
  35018. BounceEase.prototype.easeInCore = function (gradient) {
  35019. var y = Math.max(0.0, this.bounces);
  35020. var bounciness = this.bounciness;
  35021. if (bounciness <= 1.0) {
  35022. bounciness = 1.001;
  35023. }
  35024. var num9 = Math.pow(bounciness, y);
  35025. var num5 = 1.0 - bounciness;
  35026. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  35027. var num15 = gradient * num4;
  35028. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  35029. var num3 = Math.floor(num65);
  35030. var num13 = num3 + 1.0;
  35031. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  35032. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  35033. var num7 = (num8 + num12) * 0.5;
  35034. var num6 = gradient - num7;
  35035. var num2 = num7 - num8;
  35036. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  35037. };
  35038. return BounceEase;
  35039. }(EasingFunction));
  35040. BABYLON.BounceEase = BounceEase;
  35041. var CubicEase = (function (_super) {
  35042. __extends(CubicEase, _super);
  35043. function CubicEase() {
  35044. return _super !== null && _super.apply(this, arguments) || this;
  35045. }
  35046. CubicEase.prototype.easeInCore = function (gradient) {
  35047. return (gradient * gradient * gradient);
  35048. };
  35049. return CubicEase;
  35050. }(EasingFunction));
  35051. BABYLON.CubicEase = CubicEase;
  35052. var ElasticEase = (function (_super) {
  35053. __extends(ElasticEase, _super);
  35054. function ElasticEase(oscillations, springiness) {
  35055. if (oscillations === void 0) { oscillations = 3; }
  35056. if (springiness === void 0) { springiness = 3; }
  35057. var _this = _super.call(this) || this;
  35058. _this.oscillations = oscillations;
  35059. _this.springiness = springiness;
  35060. return _this;
  35061. }
  35062. ElasticEase.prototype.easeInCore = function (gradient) {
  35063. var num2;
  35064. var num3 = Math.max(0.0, this.oscillations);
  35065. var num = Math.max(0.0, this.springiness);
  35066. if (num == 0) {
  35067. num2 = gradient;
  35068. }
  35069. else {
  35070. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  35071. }
  35072. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  35073. };
  35074. return ElasticEase;
  35075. }(EasingFunction));
  35076. BABYLON.ElasticEase = ElasticEase;
  35077. var ExponentialEase = (function (_super) {
  35078. __extends(ExponentialEase, _super);
  35079. function ExponentialEase(exponent) {
  35080. if (exponent === void 0) { exponent = 2; }
  35081. var _this = _super.call(this) || this;
  35082. _this.exponent = exponent;
  35083. return _this;
  35084. }
  35085. ExponentialEase.prototype.easeInCore = function (gradient) {
  35086. if (this.exponent <= 0) {
  35087. return gradient;
  35088. }
  35089. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  35090. };
  35091. return ExponentialEase;
  35092. }(EasingFunction));
  35093. BABYLON.ExponentialEase = ExponentialEase;
  35094. var PowerEase = (function (_super) {
  35095. __extends(PowerEase, _super);
  35096. function PowerEase(power) {
  35097. if (power === void 0) { power = 2; }
  35098. var _this = _super.call(this) || this;
  35099. _this.power = power;
  35100. return _this;
  35101. }
  35102. PowerEase.prototype.easeInCore = function (gradient) {
  35103. var y = Math.max(0.0, this.power);
  35104. return Math.pow(gradient, y);
  35105. };
  35106. return PowerEase;
  35107. }(EasingFunction));
  35108. BABYLON.PowerEase = PowerEase;
  35109. var QuadraticEase = (function (_super) {
  35110. __extends(QuadraticEase, _super);
  35111. function QuadraticEase() {
  35112. return _super !== null && _super.apply(this, arguments) || this;
  35113. }
  35114. QuadraticEase.prototype.easeInCore = function (gradient) {
  35115. return (gradient * gradient);
  35116. };
  35117. return QuadraticEase;
  35118. }(EasingFunction));
  35119. BABYLON.QuadraticEase = QuadraticEase;
  35120. var QuarticEase = (function (_super) {
  35121. __extends(QuarticEase, _super);
  35122. function QuarticEase() {
  35123. return _super !== null && _super.apply(this, arguments) || this;
  35124. }
  35125. QuarticEase.prototype.easeInCore = function (gradient) {
  35126. return (gradient * gradient * gradient * gradient);
  35127. };
  35128. return QuarticEase;
  35129. }(EasingFunction));
  35130. BABYLON.QuarticEase = QuarticEase;
  35131. var QuinticEase = (function (_super) {
  35132. __extends(QuinticEase, _super);
  35133. function QuinticEase() {
  35134. return _super !== null && _super.apply(this, arguments) || this;
  35135. }
  35136. QuinticEase.prototype.easeInCore = function (gradient) {
  35137. return (gradient * gradient * gradient * gradient * gradient);
  35138. };
  35139. return QuinticEase;
  35140. }(EasingFunction));
  35141. BABYLON.QuinticEase = QuinticEase;
  35142. var SineEase = (function (_super) {
  35143. __extends(SineEase, _super);
  35144. function SineEase() {
  35145. return _super !== null && _super.apply(this, arguments) || this;
  35146. }
  35147. SineEase.prototype.easeInCore = function (gradient) {
  35148. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  35149. };
  35150. return SineEase;
  35151. }(EasingFunction));
  35152. BABYLON.SineEase = SineEase;
  35153. var BezierCurveEase = (function (_super) {
  35154. __extends(BezierCurveEase, _super);
  35155. function BezierCurveEase(x1, y1, x2, y2) {
  35156. if (x1 === void 0) { x1 = 0; }
  35157. if (y1 === void 0) { y1 = 0; }
  35158. if (x2 === void 0) { x2 = 1; }
  35159. if (y2 === void 0) { y2 = 1; }
  35160. var _this = _super.call(this) || this;
  35161. _this.x1 = x1;
  35162. _this.y1 = y1;
  35163. _this.x2 = x2;
  35164. _this.y2 = y2;
  35165. return _this;
  35166. }
  35167. BezierCurveEase.prototype.easeInCore = function (gradient) {
  35168. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  35169. };
  35170. return BezierCurveEase;
  35171. }(EasingFunction));
  35172. BABYLON.BezierCurveEase = BezierCurveEase;
  35173. })(BABYLON || (BABYLON = {}));
  35174. //# sourceMappingURL=babylon.easing.js.map
  35175. /// <reference path="..\babylon.node.ts" />
  35176. var BABYLON;
  35177. (function (BABYLON) {
  35178. var Bone = (function (_super) {
  35179. __extends(Bone, _super);
  35180. function Bone(name, skeleton, parentBone, matrix, restPose) {
  35181. var _this = _super.call(this, name, skeleton.getScene()) || this;
  35182. _this.name = name;
  35183. _this.children = new Array();
  35184. _this.animations = new Array();
  35185. _this._worldTransform = new BABYLON.Matrix();
  35186. _this._absoluteTransform = new BABYLON.Matrix();
  35187. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  35188. _this._scaleMatrix = BABYLON.Matrix.Identity();
  35189. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  35190. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  35191. _this._scalingDeterminant = 1;
  35192. _this._skeleton = skeleton;
  35193. _this._localMatrix = matrix;
  35194. _this._baseMatrix = matrix.clone();
  35195. _this._restPose = restPose ? restPose : matrix.clone();
  35196. skeleton.bones.push(_this);
  35197. if (parentBone) {
  35198. _this._parent = parentBone;
  35199. parentBone.children.push(_this);
  35200. }
  35201. else {
  35202. _this._parent = null;
  35203. }
  35204. _this._updateDifferenceMatrix();
  35205. if (_this.getAbsoluteTransform().determinant() < 0) {
  35206. _this._scalingDeterminant *= -1;
  35207. }
  35208. return _this;
  35209. }
  35210. Object.defineProperty(Bone.prototype, "_matrix", {
  35211. get: function () {
  35212. return this._localMatrix;
  35213. },
  35214. set: function (val) {
  35215. if (this._localMatrix) {
  35216. this._localMatrix.copyFrom(val);
  35217. }
  35218. else {
  35219. this._localMatrix = val;
  35220. }
  35221. },
  35222. enumerable: true,
  35223. configurable: true
  35224. });
  35225. // Members
  35226. Bone.prototype.getParent = function () {
  35227. return this._parent;
  35228. };
  35229. Bone.prototype.getLocalMatrix = function () {
  35230. return this._localMatrix;
  35231. };
  35232. Bone.prototype.getBaseMatrix = function () {
  35233. return this._baseMatrix;
  35234. };
  35235. Bone.prototype.getRestPose = function () {
  35236. return this._restPose;
  35237. };
  35238. Bone.prototype.returnToRest = function () {
  35239. this.updateMatrix(this._restPose.clone());
  35240. };
  35241. Bone.prototype.getWorldMatrix = function () {
  35242. return this._worldTransform;
  35243. };
  35244. Bone.prototype.getInvertedAbsoluteTransform = function () {
  35245. return this._invertedAbsoluteTransform;
  35246. };
  35247. Bone.prototype.getAbsoluteTransform = function () {
  35248. return this._absoluteTransform;
  35249. };
  35250. // Methods
  35251. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  35252. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  35253. this._baseMatrix = matrix.clone();
  35254. this._localMatrix = matrix.clone();
  35255. this._skeleton._markAsDirty();
  35256. if (updateDifferenceMatrix) {
  35257. this._updateDifferenceMatrix();
  35258. }
  35259. };
  35260. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  35261. if (!rootMatrix) {
  35262. rootMatrix = this._baseMatrix;
  35263. }
  35264. if (this._parent) {
  35265. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  35266. }
  35267. else {
  35268. this._absoluteTransform.copyFrom(rootMatrix);
  35269. }
  35270. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  35271. for (var index = 0; index < this.children.length; index++) {
  35272. this.children[index]._updateDifferenceMatrix();
  35273. }
  35274. };
  35275. Bone.prototype.markAsDirty = function () {
  35276. this._currentRenderId++;
  35277. this._skeleton._markAsDirty();
  35278. };
  35279. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  35280. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  35281. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  35282. // all animation may be coming from a library skeleton, so may need to create animation
  35283. if (this.animations.length === 0) {
  35284. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  35285. this.animations[0].setKeys([]);
  35286. }
  35287. // get animation info / verify there is such a range from the source bone
  35288. var sourceRange = source.animations[0].getRange(rangeName);
  35289. if (!sourceRange) {
  35290. return false;
  35291. }
  35292. var from = sourceRange.from;
  35293. var to = sourceRange.to;
  35294. var sourceKeys = source.animations[0].getKeys();
  35295. // rescaling prep
  35296. var sourceBoneLength = source.length;
  35297. var sourceParent = source.getParent();
  35298. var parent = this.getParent();
  35299. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  35300. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  35301. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  35302. var destKeys = this.animations[0].getKeys();
  35303. // loop vars declaration
  35304. var orig;
  35305. var origTranslation;
  35306. var mat;
  35307. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  35308. orig = sourceKeys[key];
  35309. if (orig.frame >= from && orig.frame <= to) {
  35310. if (rescaleAsRequired) {
  35311. mat = orig.value.clone();
  35312. // scale based on parent ratio, when bone has parent
  35313. if (parentScalingReqd) {
  35314. origTranslation = mat.getTranslation();
  35315. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  35316. // scale based on skeleton dimension ratio when root bone, and value is passed
  35317. }
  35318. else if (dimensionsScalingReqd) {
  35319. origTranslation = mat.getTranslation();
  35320. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  35321. // use original when root bone, and no data for skelDimensionsRatio
  35322. }
  35323. else {
  35324. mat = orig.value;
  35325. }
  35326. }
  35327. else {
  35328. mat = orig.value;
  35329. }
  35330. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  35331. }
  35332. }
  35333. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  35334. return true;
  35335. };
  35336. /**
  35337. * Translate the bone in local or world space.
  35338. * @param vec The amount to translate the bone.
  35339. * @param space The space that the translation is in.
  35340. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35341. */
  35342. Bone.prototype.translate = function (vec, space, mesh) {
  35343. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35344. var lm = this.getLocalMatrix();
  35345. if (space == BABYLON.Space.LOCAL) {
  35346. lm.m[12] += vec.x;
  35347. lm.m[13] += vec.y;
  35348. lm.m[14] += vec.z;
  35349. }
  35350. else {
  35351. var wm;
  35352. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  35353. if (mesh) {
  35354. wm = mesh.getWorldMatrix();
  35355. }
  35356. this._skeleton.computeAbsoluteTransforms();
  35357. var tmat = BABYLON.Tmp.Matrix[0];
  35358. var tvec = BABYLON.Tmp.Vector3[0];
  35359. if (mesh) {
  35360. tmat.copyFrom(this._parent.getAbsoluteTransform());
  35361. tmat.multiplyToRef(wm, tmat);
  35362. }
  35363. else {
  35364. tmat.copyFrom(this._parent.getAbsoluteTransform());
  35365. }
  35366. tmat.m[12] = 0;
  35367. tmat.m[13] = 0;
  35368. tmat.m[14] = 0;
  35369. tmat.invert();
  35370. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  35371. lm.m[12] += tvec.x;
  35372. lm.m[13] += tvec.y;
  35373. lm.m[14] += tvec.z;
  35374. }
  35375. this.markAsDirty();
  35376. };
  35377. /**
  35378. * Set the postion of the bone in local or world space.
  35379. * @param position The position to set the bone.
  35380. * @param space The space that the position is in.
  35381. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35382. */
  35383. Bone.prototype.setPosition = function (position, space, mesh) {
  35384. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35385. var lm = this.getLocalMatrix();
  35386. if (space == BABYLON.Space.LOCAL) {
  35387. lm.m[12] = position.x;
  35388. lm.m[13] = position.y;
  35389. lm.m[14] = position.z;
  35390. }
  35391. else {
  35392. var wm;
  35393. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  35394. if (mesh) {
  35395. wm = mesh.getWorldMatrix();
  35396. }
  35397. this._skeleton.computeAbsoluteTransforms();
  35398. var tmat = BABYLON.Tmp.Matrix[0];
  35399. var vec = BABYLON.Tmp.Vector3[0];
  35400. if (mesh) {
  35401. tmat.copyFrom(this._parent.getAbsoluteTransform());
  35402. tmat.multiplyToRef(wm, tmat);
  35403. }
  35404. else {
  35405. tmat.copyFrom(this._parent.getAbsoluteTransform());
  35406. }
  35407. tmat.invert();
  35408. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  35409. lm.m[12] = vec.x;
  35410. lm.m[13] = vec.y;
  35411. lm.m[14] = vec.z;
  35412. }
  35413. this.markAsDirty();
  35414. };
  35415. /**
  35416. * Set the absolute postion of the bone (world space).
  35417. * @param position The position to set the bone.
  35418. * @param mesh The mesh that this bone is attached to.
  35419. */
  35420. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  35421. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  35422. };
  35423. /**
  35424. * Set the scale of the bone on the x, y and z axes.
  35425. * @param x The scale of the bone on the x axis.
  35426. * @param x The scale of the bone on the y axis.
  35427. * @param z The scale of the bone on the z axis.
  35428. * @param scaleChildren Set this to true if children of the bone should be scaled.
  35429. */
  35430. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  35431. if (scaleChildren === void 0) { scaleChildren = false; }
  35432. if (this.animations[0] && !this.animations[0].isStopped()) {
  35433. if (!scaleChildren) {
  35434. this._negateScaleChildren.x = 1 / x;
  35435. this._negateScaleChildren.y = 1 / y;
  35436. this._negateScaleChildren.z = 1 / z;
  35437. }
  35438. this._syncScaleVector();
  35439. }
  35440. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  35441. };
  35442. /**
  35443. * Scale the bone on the x, y and z axes.
  35444. * @param x The amount to scale the bone on the x axis.
  35445. * @param x The amount to scale the bone on the y axis.
  35446. * @param z The amount to scale the bone on the z axis.
  35447. * @param scaleChildren Set this to true if children of the bone should be scaled.
  35448. */
  35449. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  35450. if (scaleChildren === void 0) { scaleChildren = false; }
  35451. var locMat = this.getLocalMatrix();
  35452. var origLocMat = BABYLON.Tmp.Matrix[0];
  35453. origLocMat.copyFrom(locMat);
  35454. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  35455. origLocMatInv.copyFrom(origLocMat);
  35456. origLocMatInv.invert();
  35457. var scaleMat = BABYLON.Tmp.Matrix[2];
  35458. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  35459. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  35460. this._scaleVector.x *= x;
  35461. this._scaleVector.y *= y;
  35462. this._scaleVector.z *= z;
  35463. locMat.multiplyToRef(origLocMatInv, locMat);
  35464. locMat.multiplyToRef(scaleMat, locMat);
  35465. locMat.multiplyToRef(origLocMat, locMat);
  35466. var parent = this.getParent();
  35467. if (parent) {
  35468. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  35469. }
  35470. else {
  35471. this.getAbsoluteTransform().copyFrom(locMat);
  35472. }
  35473. var len = this.children.length;
  35474. scaleMat.invert();
  35475. for (var i = 0; i < len; i++) {
  35476. var child = this.children[i];
  35477. var cm = child.getLocalMatrix();
  35478. cm.multiplyToRef(scaleMat, cm);
  35479. var lm = child.getLocalMatrix();
  35480. lm.m[12] *= x;
  35481. lm.m[13] *= y;
  35482. lm.m[14] *= z;
  35483. }
  35484. this.computeAbsoluteTransforms();
  35485. if (scaleChildren) {
  35486. for (var i = 0; i < len; i++) {
  35487. this.children[i].scale(x, y, z, scaleChildren);
  35488. }
  35489. }
  35490. this.markAsDirty();
  35491. };
  35492. /**
  35493. * Set the yaw, pitch, and roll of the bone in local or world space.
  35494. * @param yaw The rotation of the bone on the y axis.
  35495. * @param pitch The rotation of the bone on the x axis.
  35496. * @param roll The rotation of the bone on the z axis.
  35497. * @param space The space that the axes of rotation are in.
  35498. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35499. */
  35500. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  35501. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35502. var rotMat = BABYLON.Tmp.Matrix[0];
  35503. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  35504. var rotMatInv = BABYLON.Tmp.Matrix[1];
  35505. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  35506. rotMatInv.multiplyToRef(rotMat, rotMat);
  35507. this._rotateWithMatrix(rotMat, space, mesh);
  35508. };
  35509. /**
  35510. * Rotate the bone on an axis in local or world space.
  35511. * @param axis The axis to rotate the bone on.
  35512. * @param amount The amount to rotate the bone.
  35513. * @param space The space that the axis is in.
  35514. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35515. */
  35516. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  35517. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35518. var rmat = BABYLON.Tmp.Matrix[0];
  35519. rmat.m[12] = 0;
  35520. rmat.m[13] = 0;
  35521. rmat.m[14] = 0;
  35522. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  35523. this._rotateWithMatrix(rmat, space, mesh);
  35524. };
  35525. /**
  35526. * Set the rotation of the bone to a particular axis angle in local or world space.
  35527. * @param axis The axis to rotate the bone on.
  35528. * @param angle The angle that the bone should be rotated to.
  35529. * @param space The space that the axis is in.
  35530. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35531. */
  35532. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  35533. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35534. var rotMat = BABYLON.Tmp.Matrix[0];
  35535. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  35536. var rotMatInv = BABYLON.Tmp.Matrix[1];
  35537. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  35538. rotMatInv.multiplyToRef(rotMat, rotMat);
  35539. this._rotateWithMatrix(rotMat, space, mesh);
  35540. };
  35541. /**
  35542. * Set the euler rotation of the bone in local of world space.
  35543. * @param rotation The euler rotation that the bone should be set to.
  35544. * @param space The space that the rotation is in.
  35545. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35546. */
  35547. Bone.prototype.setRotation = function (rotation, space, mesh) {
  35548. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35549. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  35550. };
  35551. /**
  35552. * Set the quaternion rotation of the bone in local of world space.
  35553. * @param quat The quaternion rotation that the bone should be set to.
  35554. * @param space The space that the rotation is in.
  35555. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35556. */
  35557. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  35558. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35559. var rotMatInv = BABYLON.Tmp.Matrix[0];
  35560. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  35561. var rotMat = BABYLON.Tmp.Matrix[1];
  35562. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  35563. rotMatInv.multiplyToRef(rotMat, rotMat);
  35564. this._rotateWithMatrix(rotMat, space, mesh);
  35565. };
  35566. /**
  35567. * Set the rotation matrix of the bone in local of world space.
  35568. * @param rotMat The rotation matrix that the bone should be set to.
  35569. * @param space The space that the rotation is in.
  35570. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35571. */
  35572. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  35573. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35574. var rotMatInv = BABYLON.Tmp.Matrix[0];
  35575. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  35576. var rotMat2 = BABYLON.Tmp.Matrix[1];
  35577. rotMat2.copyFrom(rotMat);
  35578. rotMatInv.multiplyToRef(rotMat, rotMat2);
  35579. this._rotateWithMatrix(rotMat2, space, mesh);
  35580. };
  35581. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  35582. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35583. var lmat = this.getLocalMatrix();
  35584. var lx = lmat.m[12];
  35585. var ly = lmat.m[13];
  35586. var lz = lmat.m[14];
  35587. var parent = this.getParent();
  35588. var parentScale = BABYLON.Tmp.Matrix[3];
  35589. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  35590. if (parent) {
  35591. if (space == BABYLON.Space.WORLD) {
  35592. if (mesh) {
  35593. parentScale.copyFrom(mesh.getWorldMatrix());
  35594. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  35595. }
  35596. else {
  35597. parentScale.copyFrom(parent.getAbsoluteTransform());
  35598. }
  35599. }
  35600. else {
  35601. parentScale = parent._scaleMatrix;
  35602. }
  35603. parentScaleInv.copyFrom(parentScale);
  35604. parentScaleInv.invert();
  35605. lmat.multiplyToRef(parentScale, lmat);
  35606. lmat.multiplyToRef(rmat, lmat);
  35607. lmat.multiplyToRef(parentScaleInv, lmat);
  35608. }
  35609. else {
  35610. if (space == BABYLON.Space.WORLD && mesh) {
  35611. parentScale.copyFrom(mesh.getWorldMatrix());
  35612. parentScaleInv.copyFrom(parentScale);
  35613. parentScaleInv.invert();
  35614. lmat.multiplyToRef(parentScale, lmat);
  35615. lmat.multiplyToRef(rmat, lmat);
  35616. lmat.multiplyToRef(parentScaleInv, lmat);
  35617. }
  35618. else {
  35619. lmat.multiplyToRef(rmat, lmat);
  35620. }
  35621. }
  35622. lmat.m[12] = lx;
  35623. lmat.m[13] = ly;
  35624. lmat.m[14] = lz;
  35625. this.computeAbsoluteTransforms();
  35626. this.markAsDirty();
  35627. };
  35628. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  35629. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35630. if (space == BABYLON.Space.WORLD) {
  35631. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  35632. scaleMatrix.copyFrom(this._scaleMatrix);
  35633. rotMatInv.copyFrom(this.getAbsoluteTransform());
  35634. if (mesh) {
  35635. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  35636. var meshScale = BABYLON.Tmp.Matrix[3];
  35637. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  35638. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  35639. }
  35640. rotMatInv.invert();
  35641. scaleMatrix.m[0] *= this._scalingDeterminant;
  35642. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  35643. }
  35644. else {
  35645. rotMatInv.copyFrom(this.getLocalMatrix());
  35646. rotMatInv.invert();
  35647. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  35648. scaleMatrix.copyFrom(this._scaleMatrix);
  35649. if (this._parent) {
  35650. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  35651. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  35652. pscaleMatrix.invert();
  35653. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  35654. }
  35655. else {
  35656. scaleMatrix.m[0] *= this._scalingDeterminant;
  35657. }
  35658. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  35659. }
  35660. };
  35661. /**
  35662. * Get the scale of the bone
  35663. * @returns the scale of the bone
  35664. */
  35665. Bone.prototype.getScale = function () {
  35666. return this._scaleVector.clone();
  35667. };
  35668. /**
  35669. * Copy the scale of the bone to a vector3.
  35670. * @param result The vector3 to copy the scale to
  35671. */
  35672. Bone.prototype.getScaleToRef = function (result) {
  35673. result.copyFrom(this._scaleVector);
  35674. };
  35675. /**
  35676. * Get the position of the bone in local or world space.
  35677. * @param space The space that the returned position is in.
  35678. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35679. * @returns The position of the bone
  35680. */
  35681. Bone.prototype.getPosition = function (space, mesh) {
  35682. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35683. var pos = BABYLON.Vector3.Zero();
  35684. this.getPositionToRef(space, mesh, pos);
  35685. return pos;
  35686. };
  35687. /**
  35688. * Copy the position of the bone to a vector3 in local or world space.
  35689. * @param space The space that the returned position is in.
  35690. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35691. * @param result The vector3 to copy the position to.
  35692. */
  35693. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  35694. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35695. if (space == BABYLON.Space.LOCAL) {
  35696. var lm = this.getLocalMatrix();
  35697. result.x = lm.m[12];
  35698. result.y = lm.m[13];
  35699. result.z = lm.m[14];
  35700. }
  35701. else {
  35702. var wm;
  35703. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  35704. if (mesh) {
  35705. wm = mesh.getWorldMatrix();
  35706. }
  35707. this._skeleton.computeAbsoluteTransforms();
  35708. var tmat = BABYLON.Tmp.Matrix[0];
  35709. if (mesh) {
  35710. tmat.copyFrom(this.getAbsoluteTransform());
  35711. tmat.multiplyToRef(wm, tmat);
  35712. }
  35713. else {
  35714. tmat = this.getAbsoluteTransform();
  35715. }
  35716. result.x = tmat.m[12];
  35717. result.y = tmat.m[13];
  35718. result.z = tmat.m[14];
  35719. }
  35720. };
  35721. /**
  35722. * Get the absolute position of the bone (world space).
  35723. * @param mesh The mesh that this bone is attached to.
  35724. * @returns The absolute position of the bone
  35725. */
  35726. Bone.prototype.getAbsolutePosition = function (mesh) {
  35727. var pos = BABYLON.Vector3.Zero();
  35728. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  35729. return pos;
  35730. };
  35731. /**
  35732. * Copy the absolute position of the bone (world space) to the result param.
  35733. * @param mesh The mesh that this bone is attached to.
  35734. * @param result The vector3 to copy the absolute position to.
  35735. */
  35736. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  35737. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  35738. };
  35739. /**
  35740. * Compute the absolute transforms of this bone and its children.
  35741. */
  35742. Bone.prototype.computeAbsoluteTransforms = function () {
  35743. if (this._parent) {
  35744. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  35745. }
  35746. else {
  35747. this._absoluteTransform.copyFrom(this._localMatrix);
  35748. var poseMatrix = this._skeleton.getPoseMatrix();
  35749. if (poseMatrix) {
  35750. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  35751. }
  35752. }
  35753. var children = this.children;
  35754. var len = children.length;
  35755. for (var i = 0; i < len; i++) {
  35756. children[i].computeAbsoluteTransforms();
  35757. }
  35758. };
  35759. Bone.prototype._syncScaleVector = function () {
  35760. var lm = this.getLocalMatrix();
  35761. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  35762. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  35763. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  35764. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  35765. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  35766. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  35767. this._scaleVector.x = xs * Math.sqrt(xsq);
  35768. this._scaleVector.y = ys * Math.sqrt(ysq);
  35769. this._scaleVector.z = zs * Math.sqrt(zsq);
  35770. if (this._parent) {
  35771. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  35772. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  35773. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  35774. }
  35775. 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);
  35776. };
  35777. /**
  35778. * Get the world direction from an axis that is in the local space of the bone.
  35779. * @param localAxis The local direction that is used to compute the world direction.
  35780. * @param mesh The mesh that this bone is attached to.
  35781. * @returns The world direction
  35782. */
  35783. Bone.prototype.getDirection = function (localAxis, mesh) {
  35784. var result = BABYLON.Vector3.Zero();
  35785. this.getDirectionToRef(localAxis, mesh, result);
  35786. return result;
  35787. };
  35788. /**
  35789. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  35790. * @param localAxis The local direction that is used to compute the world direction.
  35791. * @param mesh The mesh that this bone is attached to.
  35792. * @param result The vector3 that the world direction will be copied to.
  35793. */
  35794. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  35795. var wm;
  35796. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  35797. if (mesh) {
  35798. wm = mesh.getWorldMatrix();
  35799. }
  35800. this._skeleton.computeAbsoluteTransforms();
  35801. var mat = BABYLON.Tmp.Matrix[0];
  35802. mat.copyFrom(this.getAbsoluteTransform());
  35803. if (mesh) {
  35804. mat.multiplyToRef(wm, mat);
  35805. }
  35806. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  35807. result.normalize();
  35808. };
  35809. /**
  35810. * Get the euler rotation of the bone in local or world space.
  35811. * @param space The space that the rotation should be in.
  35812. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35813. * @returns The euler rotation
  35814. */
  35815. Bone.prototype.getRotation = function (space, mesh) {
  35816. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35817. var result = BABYLON.Vector3.Zero();
  35818. this.getRotationToRef(space, mesh, result);
  35819. return result;
  35820. };
  35821. /**
  35822. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  35823. * @param space The space that the rotation should be in.
  35824. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35825. * @param result The vector3 that the rotation should be copied to.
  35826. */
  35827. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  35828. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35829. var quat = BABYLON.Tmp.Quaternion[0];
  35830. this.getRotationQuaternionToRef(space, mesh, quat);
  35831. quat.toEulerAnglesToRef(result);
  35832. };
  35833. /**
  35834. * Get the quaternion rotation of the bone in either local or world space.
  35835. * @param space The space that the rotation should be in.
  35836. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35837. * @returns The quaternion rotation
  35838. */
  35839. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  35840. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35841. var result = BABYLON.Quaternion.Identity();
  35842. this.getRotationQuaternionToRef(space, mesh, result);
  35843. return result;
  35844. };
  35845. /**
  35846. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  35847. * @param space The space that the rotation should be in.
  35848. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35849. * @param result The quaternion that the rotation should be copied to.
  35850. */
  35851. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  35852. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35853. if (space == BABYLON.Space.LOCAL) {
  35854. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  35855. }
  35856. else {
  35857. var mat = BABYLON.Tmp.Matrix[0];
  35858. var amat = this.getAbsoluteTransform();
  35859. if (mesh) {
  35860. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  35861. }
  35862. else {
  35863. mat.copyFrom(amat);
  35864. }
  35865. mat.m[0] *= this._scalingDeterminant;
  35866. mat.m[1] *= this._scalingDeterminant;
  35867. mat.m[2] *= this._scalingDeterminant;
  35868. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  35869. }
  35870. };
  35871. /**
  35872. * Get the rotation matrix of the bone in local or world space.
  35873. * @param space The space that the rotation should be in.
  35874. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35875. * @returns The rotation matrix
  35876. */
  35877. Bone.prototype.getRotationMatrix = function (space, mesh) {
  35878. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35879. var result = BABYLON.Matrix.Identity();
  35880. this.getRotationMatrixToRef(space, mesh, result);
  35881. return result;
  35882. };
  35883. /**
  35884. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  35885. * @param space The space that the rotation should be in.
  35886. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35887. * @param result The quaternion that the rotation should be copied to.
  35888. */
  35889. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  35890. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35891. if (space == BABYLON.Space.LOCAL) {
  35892. this.getLocalMatrix().getRotationMatrixToRef(result);
  35893. }
  35894. else {
  35895. var mat = BABYLON.Tmp.Matrix[0];
  35896. var amat = this.getAbsoluteTransform();
  35897. if (mesh) {
  35898. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  35899. }
  35900. else {
  35901. mat.copyFrom(amat);
  35902. }
  35903. mat.m[0] *= this._scalingDeterminant;
  35904. mat.m[1] *= this._scalingDeterminant;
  35905. mat.m[2] *= this._scalingDeterminant;
  35906. mat.getRotationMatrixToRef(result);
  35907. }
  35908. };
  35909. /**
  35910. * Get the world position of a point that is in the local space of the bone.
  35911. * @param position The local position
  35912. * @param mesh The mesh that this bone is attached to.
  35913. * @returns The world position
  35914. */
  35915. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  35916. var result = BABYLON.Vector3.Zero();
  35917. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  35918. return result;
  35919. };
  35920. /**
  35921. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  35922. * @param position The local position
  35923. * @param mesh The mesh that this bone is attached to.
  35924. * @param result The vector3 that the world position should be copied to.
  35925. */
  35926. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  35927. var wm;
  35928. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  35929. if (mesh) {
  35930. wm = mesh.getWorldMatrix();
  35931. }
  35932. this._skeleton.computeAbsoluteTransforms();
  35933. var tmat = BABYLON.Tmp.Matrix[0];
  35934. if (mesh) {
  35935. tmat.copyFrom(this.getAbsoluteTransform());
  35936. tmat.multiplyToRef(wm, tmat);
  35937. }
  35938. else {
  35939. tmat = this.getAbsoluteTransform();
  35940. }
  35941. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  35942. };
  35943. /**
  35944. * Get the local position of a point that is in world space.
  35945. * @param position The world position
  35946. * @param mesh The mesh that this bone is attached to.
  35947. * @returns The local position
  35948. */
  35949. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  35950. var result = BABYLON.Vector3.Zero();
  35951. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  35952. return result;
  35953. };
  35954. /**
  35955. * Get the local position of a point that is in world space and copy it to the result param.
  35956. * @param position The world position
  35957. * @param mesh The mesh that this bone is attached to.
  35958. * @param result The vector3 that the local position should be copied to.
  35959. */
  35960. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  35961. var wm;
  35962. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  35963. if (mesh) {
  35964. wm = mesh.getWorldMatrix();
  35965. }
  35966. this._skeleton.computeAbsoluteTransforms();
  35967. var tmat = BABYLON.Tmp.Matrix[0];
  35968. tmat.copyFrom(this.getAbsoluteTransform());
  35969. if (mesh) {
  35970. tmat.multiplyToRef(wm, tmat);
  35971. }
  35972. tmat.invert();
  35973. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  35974. };
  35975. return Bone;
  35976. }(BABYLON.Node));
  35977. BABYLON.Bone = Bone;
  35978. })(BABYLON || (BABYLON = {}));
  35979. //# sourceMappingURL=babylon.bone.js.map
  35980. var BABYLON;
  35981. (function (BABYLON) {
  35982. var BoneIKController = (function () {
  35983. function BoneIKController(mesh, bone, options) {
  35984. this.targetPosition = BABYLON.Vector3.Zero();
  35985. this.poleTargetPosition = BABYLON.Vector3.Zero();
  35986. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  35987. this.poleAngle = 0;
  35988. this.slerpAmount = 1;
  35989. this._bone1Quat = BABYLON.Quaternion.Identity();
  35990. this._bone1Mat = BABYLON.Matrix.Identity();
  35991. this._bone2Ang = Math.PI;
  35992. this._maxAngle = Math.PI;
  35993. this._rightHandedSystem = false;
  35994. this._bendAxis = BABYLON.Vector3.Right();
  35995. this._slerping = false;
  35996. this._adjustRoll = 0;
  35997. this._bone2 = bone;
  35998. this._bone1 = bone.getParent();
  35999. this.mesh = mesh;
  36000. var bonePos = bone.getPosition();
  36001. if (bone.getAbsoluteTransform().determinant() > 0) {
  36002. this._rightHandedSystem = true;
  36003. this._bendAxis.x = 0;
  36004. this._bendAxis.y = 0;
  36005. this._bendAxis.z = -1;
  36006. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  36007. this._adjustRoll = Math.PI * .5;
  36008. this._bendAxis.z = 1;
  36009. }
  36010. }
  36011. if (this._bone1.length) {
  36012. var boneScale1 = this._bone1.getScale();
  36013. var boneScale2 = this._bone2.getScale();
  36014. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  36015. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  36016. }
  36017. else if (this._bone1.children[0]) {
  36018. mesh.computeWorldMatrix(true);
  36019. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  36020. var pos2 = this._bone2.getAbsolutePosition(mesh);
  36021. var pos3 = this._bone1.getAbsolutePosition(mesh);
  36022. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  36023. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  36024. }
  36025. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  36026. this.maxAngle = Math.PI;
  36027. if (options) {
  36028. if (options.targetMesh) {
  36029. this.targetMesh = options.targetMesh;
  36030. this.targetMesh.computeWorldMatrix(true);
  36031. }
  36032. if (options.poleTargetMesh) {
  36033. this.poleTargetMesh = options.poleTargetMesh;
  36034. this.poleTargetMesh.computeWorldMatrix(true);
  36035. }
  36036. else if (options.poleTargetBone) {
  36037. this.poleTargetBone = options.poleTargetBone;
  36038. }
  36039. else if (this._bone1.getParent()) {
  36040. this.poleTargetBone = this._bone1.getParent();
  36041. }
  36042. if (options.poleTargetLocalOffset) {
  36043. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  36044. }
  36045. if (options.poleAngle) {
  36046. this.poleAngle = options.poleAngle;
  36047. }
  36048. if (options.bendAxis) {
  36049. this._bendAxis.copyFrom(options.bendAxis);
  36050. }
  36051. if (options.maxAngle) {
  36052. this.maxAngle = options.maxAngle;
  36053. }
  36054. if (options.slerpAmount) {
  36055. this.slerpAmount = options.slerpAmount;
  36056. }
  36057. }
  36058. }
  36059. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  36060. get: function () {
  36061. return this._maxAngle;
  36062. },
  36063. set: function (value) {
  36064. this._setMaxAngle(value);
  36065. },
  36066. enumerable: true,
  36067. configurable: true
  36068. });
  36069. BoneIKController.prototype._setMaxAngle = function (ang) {
  36070. if (ang < 0) {
  36071. ang = 0;
  36072. }
  36073. if (ang > Math.PI || ang == undefined) {
  36074. ang = Math.PI;
  36075. }
  36076. this._maxAngle = ang;
  36077. var a = this._bone1Length;
  36078. var b = this._bone2Length;
  36079. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  36080. };
  36081. BoneIKController.prototype.update = function () {
  36082. var bone1 = this._bone1;
  36083. var target = this.targetPosition;
  36084. var poleTarget = this.poleTargetPosition;
  36085. var mat1 = BoneIKController._tmpMats[0];
  36086. var mat2 = BoneIKController._tmpMats[1];
  36087. if (this.targetMesh) {
  36088. target.copyFrom(this.targetMesh.getAbsolutePosition());
  36089. }
  36090. if (this.poleTargetBone) {
  36091. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  36092. }
  36093. else if (this.poleTargetMesh) {
  36094. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  36095. }
  36096. var bonePos = BoneIKController._tmpVecs[0];
  36097. var zaxis = BoneIKController._tmpVecs[1];
  36098. var xaxis = BoneIKController._tmpVecs[2];
  36099. var yaxis = BoneIKController._tmpVecs[3];
  36100. var upAxis = BoneIKController._tmpVecs[4];
  36101. var _tmpQuat = BoneIKController._tmpQuat;
  36102. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  36103. poleTarget.subtractToRef(bonePos, upAxis);
  36104. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  36105. upAxis.y = 1;
  36106. }
  36107. else {
  36108. upAxis.normalize();
  36109. }
  36110. target.subtractToRef(bonePos, yaxis);
  36111. yaxis.normalize();
  36112. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  36113. zaxis.normalize();
  36114. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  36115. xaxis.normalize();
  36116. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  36117. var a = this._bone1Length;
  36118. var b = this._bone2Length;
  36119. var c = BABYLON.Vector3.Distance(bonePos, target);
  36120. if (this._maxReach > 0) {
  36121. c = Math.min(this._maxReach, c);
  36122. }
  36123. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  36124. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  36125. if (acosa > 1) {
  36126. acosa = 1;
  36127. }
  36128. if (acosb > 1) {
  36129. acosb = 1;
  36130. }
  36131. if (acosa < -1) {
  36132. acosa = -1;
  36133. }
  36134. if (acosb < -1) {
  36135. acosb = -1;
  36136. }
  36137. var angA = Math.acos(acosa);
  36138. var angB = Math.acos(acosb);
  36139. var angC = -angA - angB;
  36140. if (this._rightHandedSystem) {
  36141. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  36142. mat2.multiplyToRef(mat1, mat1);
  36143. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  36144. mat2.multiplyToRef(mat1, mat1);
  36145. }
  36146. else {
  36147. var _tmpVec = BoneIKController._tmpVecs[5];
  36148. _tmpVec.copyFrom(this._bendAxis);
  36149. _tmpVec.x *= -1;
  36150. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  36151. mat2.multiplyToRef(mat1, mat1);
  36152. }
  36153. if (this.poleAngle) {
  36154. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  36155. mat1.multiplyToRef(mat2, mat1);
  36156. }
  36157. if (this.slerpAmount < 1) {
  36158. if (!this._slerping) {
  36159. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  36160. }
  36161. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  36162. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  36163. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  36164. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  36165. this._slerping = true;
  36166. }
  36167. else {
  36168. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  36169. this._bone1Mat.copyFrom(mat1);
  36170. this._slerping = false;
  36171. }
  36172. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  36173. this._bone2Ang = angC;
  36174. };
  36175. return BoneIKController;
  36176. }());
  36177. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  36178. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  36179. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  36180. BABYLON.BoneIKController = BoneIKController;
  36181. })(BABYLON || (BABYLON = {}));
  36182. //# sourceMappingURL=babylon.boneIKController.js.map
  36183. var BABYLON;
  36184. (function (BABYLON) {
  36185. var BoneLookController = (function () {
  36186. /**
  36187. * Create a BoneLookController
  36188. * @param mesh the mesh that the bone belongs to
  36189. * @param bone the bone that will be looking to the target
  36190. * @param target the target Vector3 to look at
  36191. * @param settings optional settings:
  36192. * - maxYaw: the maximum angle the bone will yaw to
  36193. * - minYaw: the minimum angle the bone will yaw to
  36194. * - maxPitch: the maximum angle the bone will pitch to
  36195. * - minPitch: the minimum angle the bone will yaw to
  36196. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  36197. * - upAxis: the up axis of the coordinate system
  36198. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  36199. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  36200. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  36201. * - adjustYaw: used to make an adjustment to the yaw of the bone
  36202. * - adjustPitch: used to make an adjustment to the pitch of the bone
  36203. * - adjustRoll: used to make an adjustment to the roll of the bone
  36204. **/
  36205. function BoneLookController(mesh, bone, target, options) {
  36206. /**
  36207. * The up axis of the coordinate system that is used when the bone is rotated.
  36208. */
  36209. this.upAxis = BABYLON.Vector3.Up();
  36210. /**
  36211. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  36212. */
  36213. this.upAxisSpace = BABYLON.Space.LOCAL;
  36214. /**
  36215. * Used to make an adjustment to the yaw of the bone.
  36216. */
  36217. this.adjustYaw = 0;
  36218. /**
  36219. * Used to make an adjustment to the pitch of the bone.
  36220. */
  36221. this.adjustPitch = 0;
  36222. /**
  36223. * Used to make an adjustment to the roll of the bone.
  36224. */
  36225. this.adjustRoll = 0;
  36226. /**
  36227. * 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).
  36228. */
  36229. this.slerpAmount = 1;
  36230. this._boneQuat = BABYLON.Quaternion.Identity();
  36231. this._slerping = false;
  36232. this._firstFrameSkipped = false;
  36233. this._fowardAxis = BABYLON.Vector3.Forward();
  36234. this.mesh = mesh;
  36235. this.bone = bone;
  36236. this.target = target;
  36237. if (options) {
  36238. if (options.adjustYaw) {
  36239. this.adjustYaw = options.adjustYaw;
  36240. }
  36241. if (options.adjustPitch) {
  36242. this.adjustPitch = options.adjustPitch;
  36243. }
  36244. if (options.adjustRoll) {
  36245. this.adjustRoll = options.adjustRoll;
  36246. }
  36247. if (options.maxYaw != null) {
  36248. this.maxYaw = options.maxYaw;
  36249. }
  36250. else {
  36251. this.maxYaw = Math.PI;
  36252. }
  36253. if (options.minYaw != null) {
  36254. this.minYaw = options.minYaw;
  36255. }
  36256. else {
  36257. this.minYaw = -Math.PI;
  36258. }
  36259. if (options.maxPitch != null) {
  36260. this.maxPitch = options.maxPitch;
  36261. }
  36262. else {
  36263. this.maxPitch = Math.PI;
  36264. }
  36265. if (options.minPitch != null) {
  36266. this.minPitch = options.minPitch;
  36267. }
  36268. else {
  36269. this.minPitch = -Math.PI;
  36270. }
  36271. if (options.slerpAmount != null) {
  36272. this.slerpAmount = options.slerpAmount;
  36273. }
  36274. if (options.upAxis != null) {
  36275. this.upAxis = options.upAxis;
  36276. }
  36277. if (options.upAxisSpace != null) {
  36278. this.upAxisSpace = options.upAxisSpace;
  36279. }
  36280. if (options.yawAxis != null || options.pitchAxis != null) {
  36281. var newYawAxis = BABYLON.Axis.Y;
  36282. var newPitchAxis = BABYLON.Axis.X;
  36283. if (options.yawAxis != null) {
  36284. newYawAxis = options.yawAxis.clone();
  36285. newYawAxis.normalize();
  36286. }
  36287. if (options.pitchAxis != null) {
  36288. newPitchAxis = options.pitchAxis.clone();
  36289. newPitchAxis.normalize();
  36290. }
  36291. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  36292. this._transformYawPitch = BABYLON.Matrix.Identity();
  36293. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  36294. this._transformYawPitchInv = this._transformYawPitch.clone();
  36295. this._transformYawPitch.invert();
  36296. }
  36297. }
  36298. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  36299. this.upAxisSpace = BABYLON.Space.LOCAL;
  36300. }
  36301. }
  36302. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  36303. /**
  36304. * Get/set the minimum yaw angle that the bone can look to.
  36305. */
  36306. get: function () {
  36307. return this._minYaw;
  36308. },
  36309. set: function (value) {
  36310. this._minYaw = value;
  36311. this._minYawSin = Math.sin(value);
  36312. this._minYawCos = Math.cos(value);
  36313. if (this._maxYaw != null) {
  36314. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  36315. this._yawRange = this._maxYaw - this._minYaw;
  36316. }
  36317. },
  36318. enumerable: true,
  36319. configurable: true
  36320. });
  36321. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  36322. /**
  36323. * Get/set the maximum yaw angle that the bone can look to.
  36324. */
  36325. get: function () {
  36326. return this._maxYaw;
  36327. },
  36328. set: function (value) {
  36329. this._maxYaw = value;
  36330. this._maxYawSin = Math.sin(value);
  36331. this._maxYawCos = Math.cos(value);
  36332. if (this._minYaw != null) {
  36333. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  36334. this._yawRange = this._maxYaw - this._minYaw;
  36335. }
  36336. },
  36337. enumerable: true,
  36338. configurable: true
  36339. });
  36340. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  36341. /**
  36342. * Get/set the minimum pitch angle that the bone can look to.
  36343. */
  36344. get: function () {
  36345. return this._minPitch;
  36346. },
  36347. set: function (value) {
  36348. this._minPitch = value;
  36349. this._minPitchTan = Math.tan(value);
  36350. },
  36351. enumerable: true,
  36352. configurable: true
  36353. });
  36354. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  36355. /**
  36356. * Get/set the maximum pitch angle that the bone can look to.
  36357. */
  36358. get: function () {
  36359. return this._maxPitch;
  36360. },
  36361. set: function (value) {
  36362. this._maxPitch = value;
  36363. this._maxPitchTan = Math.tan(value);
  36364. },
  36365. enumerable: true,
  36366. configurable: true
  36367. });
  36368. /**
  36369. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  36370. */
  36371. BoneLookController.prototype.update = function () {
  36372. //skip the first frame when slerping so that the mesh rotation is correct
  36373. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  36374. this._firstFrameSkipped = true;
  36375. return;
  36376. }
  36377. var bone = this.bone;
  36378. var bonePos = BoneLookController._tmpVecs[0];
  36379. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  36380. var target = this.target;
  36381. var _tmpMat1 = BoneLookController._tmpMats[0];
  36382. var _tmpMat2 = BoneLookController._tmpMats[1];
  36383. var mesh = this.mesh;
  36384. var parentBone = bone.getParent();
  36385. var upAxis = BoneLookController._tmpVecs[1];
  36386. upAxis.copyFrom(this.upAxis);
  36387. if (this.upAxisSpace == BABYLON.Space.BONE) {
  36388. if (this._transformYawPitch) {
  36389. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  36390. }
  36391. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  36392. }
  36393. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  36394. mesh.getDirectionToRef(upAxis, upAxis);
  36395. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  36396. upAxis.normalize();
  36397. }
  36398. }
  36399. var checkYaw = false;
  36400. var checkPitch = false;
  36401. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  36402. checkYaw = true;
  36403. }
  36404. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  36405. checkPitch = true;
  36406. }
  36407. if (checkYaw || checkPitch) {
  36408. var spaceMat = BoneLookController._tmpMats[2];
  36409. var spaceMatInv = BoneLookController._tmpMats[3];
  36410. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  36411. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  36412. }
  36413. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  36414. spaceMat.copyFrom(mesh.getWorldMatrix());
  36415. }
  36416. else {
  36417. var forwardAxis = BoneLookController._tmpVecs[2];
  36418. forwardAxis.copyFrom(this._fowardAxis);
  36419. if (this._transformYawPitch) {
  36420. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  36421. }
  36422. if (parentBone) {
  36423. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  36424. }
  36425. else {
  36426. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  36427. }
  36428. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  36429. rightAxis.normalize();
  36430. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  36431. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  36432. }
  36433. spaceMat.invertToRef(spaceMatInv);
  36434. var xzlen;
  36435. if (checkPitch) {
  36436. var localTarget = BoneLookController._tmpVecs[3];
  36437. target.subtractToRef(bonePos, localTarget);
  36438. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  36439. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  36440. var pitch = Math.atan2(localTarget.y, xzlen);
  36441. var newPitch = pitch;
  36442. if (pitch > this._maxPitch) {
  36443. localTarget.y = this._maxPitchTan * xzlen;
  36444. newPitch = this._maxPitch;
  36445. }
  36446. else if (pitch < this._minPitch) {
  36447. localTarget.y = this._minPitchTan * xzlen;
  36448. newPitch = this._minPitch;
  36449. }
  36450. if (pitch != newPitch) {
  36451. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  36452. localTarget.addInPlace(bonePos);
  36453. target = localTarget;
  36454. }
  36455. }
  36456. if (checkYaw) {
  36457. var localTarget = BoneLookController._tmpVecs[4];
  36458. target.subtractToRef(bonePos, localTarget);
  36459. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  36460. var yaw = Math.atan2(localTarget.x, localTarget.z);
  36461. var newYaw = yaw;
  36462. if (yaw > this._maxYaw || yaw < this._minYaw) {
  36463. if (xzlen == null) {
  36464. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  36465. }
  36466. if (this._yawRange > Math.PI) {
  36467. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  36468. localTarget.z = this._maxYawCos * xzlen;
  36469. localTarget.x = this._maxYawSin * xzlen;
  36470. newYaw = this._maxYaw;
  36471. }
  36472. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  36473. localTarget.z = this._minYawCos * xzlen;
  36474. localTarget.x = this._minYawSin * xzlen;
  36475. newYaw = this._minYaw;
  36476. }
  36477. }
  36478. else {
  36479. if (yaw > this._maxYaw) {
  36480. localTarget.z = this._maxYawCos * xzlen;
  36481. localTarget.x = this._maxYawSin * xzlen;
  36482. newYaw = this._maxYaw;
  36483. }
  36484. else if (yaw < this._minYaw) {
  36485. localTarget.z = this._minYawCos * xzlen;
  36486. localTarget.x = this._minYawSin * xzlen;
  36487. newYaw = this._minYaw;
  36488. }
  36489. }
  36490. }
  36491. if (this._slerping && this._yawRange > Math.PI) {
  36492. //are we going to be crossing into the min/max region?
  36493. var boneFwd = BoneLookController._tmpVecs[8];
  36494. boneFwd.copyFrom(BABYLON.Axis.Z);
  36495. if (this._transformYawPitch) {
  36496. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  36497. }
  36498. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  36499. this._boneQuat.toRotationMatrix(boneRotMat);
  36500. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  36501. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  36502. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  36503. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  36504. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  36505. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  36506. if (angBtwTar > angBtwMidYaw) {
  36507. if (xzlen == null) {
  36508. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  36509. }
  36510. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  36511. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  36512. if (angBtwMin < angBtwMax) {
  36513. newYaw = boneYaw + Math.PI * .75;
  36514. localTarget.z = Math.cos(newYaw) * xzlen;
  36515. localTarget.x = Math.sin(newYaw) * xzlen;
  36516. }
  36517. else {
  36518. newYaw = boneYaw - Math.PI * .75;
  36519. localTarget.z = Math.cos(newYaw) * xzlen;
  36520. localTarget.x = Math.sin(newYaw) * xzlen;
  36521. }
  36522. }
  36523. }
  36524. if (yaw != newYaw) {
  36525. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  36526. localTarget.addInPlace(bonePos);
  36527. target = localTarget;
  36528. }
  36529. }
  36530. }
  36531. var zaxis = BoneLookController._tmpVecs[5];
  36532. var xaxis = BoneLookController._tmpVecs[6];
  36533. var yaxis = BoneLookController._tmpVecs[7];
  36534. var _tmpQuat = BoneLookController._tmpQuat;
  36535. target.subtractToRef(bonePos, zaxis);
  36536. zaxis.normalize();
  36537. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  36538. xaxis.normalize();
  36539. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  36540. yaxis.normalize();
  36541. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  36542. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  36543. return;
  36544. }
  36545. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  36546. return;
  36547. }
  36548. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  36549. return;
  36550. }
  36551. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  36552. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  36553. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  36554. }
  36555. if (this.slerpAmount < 1) {
  36556. if (!this._slerping) {
  36557. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  36558. }
  36559. if (this._transformYawPitch) {
  36560. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  36561. }
  36562. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  36563. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  36564. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  36565. this._slerping = true;
  36566. }
  36567. else {
  36568. if (this._transformYawPitch) {
  36569. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  36570. }
  36571. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  36572. this._slerping = false;
  36573. }
  36574. };
  36575. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  36576. var angDiff = ang2 - ang1;
  36577. angDiff %= Math.PI * 2;
  36578. if (angDiff > Math.PI) {
  36579. angDiff -= Math.PI * 2;
  36580. }
  36581. else if (angDiff < -Math.PI) {
  36582. angDiff += Math.PI * 2;
  36583. }
  36584. return angDiff;
  36585. };
  36586. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  36587. ang1 %= (2 * Math.PI);
  36588. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  36589. ang2 %= (2 * Math.PI);
  36590. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  36591. var ab = 0;
  36592. if (ang1 < ang2) {
  36593. ab = ang2 - ang1;
  36594. }
  36595. else {
  36596. ab = ang1 - ang2;
  36597. }
  36598. if (ab > Math.PI) {
  36599. ab = Math.PI * 2 - ab;
  36600. }
  36601. return ab;
  36602. };
  36603. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  36604. ang %= (2 * Math.PI);
  36605. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  36606. ang1 %= (2 * Math.PI);
  36607. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  36608. ang2 %= (2 * Math.PI);
  36609. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  36610. if (ang1 < ang2) {
  36611. if (ang > ang1 && ang < ang2) {
  36612. return true;
  36613. }
  36614. }
  36615. else {
  36616. if (ang > ang2 && ang < ang1) {
  36617. return true;
  36618. }
  36619. }
  36620. return false;
  36621. };
  36622. return BoneLookController;
  36623. }());
  36624. 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()];
  36625. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  36626. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  36627. BABYLON.BoneLookController = BoneLookController;
  36628. })(BABYLON || (BABYLON = {}));
  36629. //# sourceMappingURL=babylon.boneLookController.js.map
  36630. var BABYLON;
  36631. (function (BABYLON) {
  36632. var Skeleton = (function () {
  36633. function Skeleton(name, id, scene) {
  36634. this.name = name;
  36635. this.id = id;
  36636. this.bones = new Array();
  36637. this.needInitialSkinMatrix = false;
  36638. this._isDirty = true;
  36639. this._meshesWithPoseMatrix = new Array();
  36640. this._identity = BABYLON.Matrix.Identity();
  36641. this._ranges = {};
  36642. this._lastAbsoluteTransformsUpdateId = -1;
  36643. // Events
  36644. /**
  36645. * An event triggered before computing the skeleton's matrices
  36646. * @type {BABYLON.Observable}
  36647. */
  36648. this.onBeforeComputeObservable = new BABYLON.Observable();
  36649. this.bones = [];
  36650. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36651. scene.skeletons.push(this);
  36652. //make sure it will recalculate the matrix next time prepare is called.
  36653. this._isDirty = true;
  36654. }
  36655. // Members
  36656. Skeleton.prototype.getTransformMatrices = function (mesh) {
  36657. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  36658. return mesh._bonesTransformMatrices;
  36659. }
  36660. if (!this._transformMatrices) {
  36661. this.prepare();
  36662. }
  36663. return this._transformMatrices;
  36664. };
  36665. Skeleton.prototype.getScene = function () {
  36666. return this._scene;
  36667. };
  36668. // Methods
  36669. /**
  36670. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  36671. */
  36672. Skeleton.prototype.toString = function (fullDetails) {
  36673. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  36674. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  36675. if (fullDetails) {
  36676. ret += ", Ranges: {";
  36677. var first = true;
  36678. for (var name_1 in this._ranges) {
  36679. if (first) {
  36680. ret += ", ";
  36681. first = false;
  36682. }
  36683. ret += name_1;
  36684. }
  36685. ret += "}";
  36686. }
  36687. return ret;
  36688. };
  36689. /**
  36690. * Get bone's index searching by name
  36691. * @param {string} name is bone's name to search for
  36692. * @return {number} Indice of the bone. Returns -1 if not found
  36693. */
  36694. Skeleton.prototype.getBoneIndexByName = function (name) {
  36695. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  36696. if (this.bones[boneIndex].name === name) {
  36697. return boneIndex;
  36698. }
  36699. }
  36700. return -1;
  36701. };
  36702. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  36703. // check name not already in use
  36704. if (!this._ranges[name]) {
  36705. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  36706. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  36707. if (this.bones[i].animations[0]) {
  36708. this.bones[i].animations[0].createRange(name, from, to);
  36709. }
  36710. }
  36711. }
  36712. };
  36713. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  36714. if (deleteFrames === void 0) { deleteFrames = true; }
  36715. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  36716. if (this.bones[i].animations[0]) {
  36717. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  36718. }
  36719. }
  36720. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  36721. };
  36722. Skeleton.prototype.getAnimationRange = function (name) {
  36723. return this._ranges[name];
  36724. };
  36725. /**
  36726. * Returns as an Array, all AnimationRanges defined on this skeleton
  36727. */
  36728. Skeleton.prototype.getAnimationRanges = function () {
  36729. var animationRanges = [];
  36730. var name;
  36731. var i = 0;
  36732. for (name in this._ranges) {
  36733. animationRanges[i] = this._ranges[name];
  36734. i++;
  36735. }
  36736. return animationRanges;
  36737. };
  36738. /**
  36739. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  36740. */
  36741. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  36742. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  36743. if (this._ranges[name] || !source.getAnimationRange(name)) {
  36744. return false;
  36745. }
  36746. var ret = true;
  36747. var frameOffset = this._getHighestAnimationFrame() + 1;
  36748. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  36749. var boneDict = {};
  36750. var sourceBones = source.bones;
  36751. var nBones;
  36752. var i;
  36753. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  36754. boneDict[sourceBones[i].name] = sourceBones[i];
  36755. }
  36756. if (this.bones.length !== sourceBones.length) {
  36757. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  36758. ret = false;
  36759. }
  36760. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  36761. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  36762. var boneName = this.bones[i].name;
  36763. var sourceBone = boneDict[boneName];
  36764. if (sourceBone) {
  36765. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  36766. }
  36767. else {
  36768. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  36769. ret = false;
  36770. }
  36771. }
  36772. // do not call createAnimationRange(), since it also is done to bones, which was already done
  36773. var range = source.getAnimationRange(name);
  36774. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  36775. return ret;
  36776. };
  36777. Skeleton.prototype.returnToRest = function () {
  36778. for (var index = 0; index < this.bones.length; index++) {
  36779. this.bones[index].returnToRest();
  36780. }
  36781. };
  36782. Skeleton.prototype._getHighestAnimationFrame = function () {
  36783. var ret = 0;
  36784. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  36785. if (this.bones[i].animations[0]) {
  36786. var highest = this.bones[i].animations[0].getHighestFrame();
  36787. if (ret < highest) {
  36788. ret = highest;
  36789. }
  36790. }
  36791. }
  36792. return ret;
  36793. };
  36794. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  36795. var range = this.getAnimationRange(name);
  36796. if (!range) {
  36797. return null;
  36798. }
  36799. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  36800. };
  36801. Skeleton.prototype._markAsDirty = function () {
  36802. this._isDirty = true;
  36803. };
  36804. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  36805. this._meshesWithPoseMatrix.push(mesh);
  36806. };
  36807. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  36808. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  36809. if (index > -1) {
  36810. this._meshesWithPoseMatrix.splice(index, 1);
  36811. }
  36812. };
  36813. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  36814. this.onBeforeComputeObservable.notifyObservers(this);
  36815. for (var index = 0; index < this.bones.length; index++) {
  36816. var bone = this.bones[index];
  36817. var parentBone = bone.getParent();
  36818. if (parentBone) {
  36819. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  36820. }
  36821. else {
  36822. if (initialSkinMatrix) {
  36823. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  36824. }
  36825. else {
  36826. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  36827. }
  36828. }
  36829. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  36830. }
  36831. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  36832. };
  36833. Skeleton.prototype.prepare = function () {
  36834. if (!this._isDirty) {
  36835. return;
  36836. }
  36837. if (this.needInitialSkinMatrix) {
  36838. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  36839. var mesh = this._meshesWithPoseMatrix[index];
  36840. var poseMatrix = mesh.getPoseMatrix();
  36841. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  36842. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  36843. }
  36844. if (this._synchronizedWithMesh !== mesh) {
  36845. this._synchronizedWithMesh = mesh;
  36846. // Prepare bones
  36847. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  36848. var bone = this.bones[boneIndex];
  36849. if (!bone.getParent()) {
  36850. var matrix = bone.getBaseMatrix();
  36851. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  36852. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  36853. }
  36854. }
  36855. }
  36856. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  36857. }
  36858. }
  36859. else {
  36860. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  36861. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  36862. }
  36863. this._computeTransformMatrices(this._transformMatrices, null);
  36864. }
  36865. this._isDirty = false;
  36866. this._scene._activeBones.addCount(this.bones.length, false);
  36867. };
  36868. Skeleton.prototype.getAnimatables = function () {
  36869. if (!this._animatables || this._animatables.length !== this.bones.length) {
  36870. this._animatables = [];
  36871. for (var index = 0; index < this.bones.length; index++) {
  36872. this._animatables.push(this.bones[index]);
  36873. }
  36874. }
  36875. return this._animatables;
  36876. };
  36877. Skeleton.prototype.clone = function (name, id) {
  36878. var result = new Skeleton(name, id || name, this._scene);
  36879. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  36880. for (var index = 0; index < this.bones.length; index++) {
  36881. var source = this.bones[index];
  36882. var parentBone = null;
  36883. if (source.getParent()) {
  36884. var parentIndex = this.bones.indexOf(source.getParent());
  36885. parentBone = result.bones[parentIndex];
  36886. }
  36887. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  36888. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  36889. }
  36890. if (this._ranges) {
  36891. result._ranges = {};
  36892. for (var rangeName in this._ranges) {
  36893. result._ranges[rangeName] = this._ranges[rangeName].clone();
  36894. }
  36895. }
  36896. this._isDirty = true;
  36897. return result;
  36898. };
  36899. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  36900. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  36901. this.bones.forEach(function (bone) {
  36902. bone.animations.forEach(function (animation) {
  36903. animation.enableBlending = true;
  36904. animation.blendingSpeed = blendingSpeed;
  36905. });
  36906. });
  36907. };
  36908. Skeleton.prototype.dispose = function () {
  36909. this._meshesWithPoseMatrix = [];
  36910. // Animations
  36911. this.getScene().stopAnimation(this);
  36912. // Remove from scene
  36913. this.getScene().removeSkeleton(this);
  36914. };
  36915. Skeleton.prototype.serialize = function () {
  36916. var serializationObject = {};
  36917. serializationObject.name = this.name;
  36918. serializationObject.id = this.id;
  36919. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  36920. serializationObject.bones = [];
  36921. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  36922. for (var index = 0; index < this.bones.length; index++) {
  36923. var bone = this.bones[index];
  36924. var serializedBone = {
  36925. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  36926. name: bone.name,
  36927. matrix: bone.getBaseMatrix().toArray(),
  36928. rest: bone.getRestPose().toArray()
  36929. };
  36930. serializationObject.bones.push(serializedBone);
  36931. if (bone.length) {
  36932. serializedBone.length = bone.length;
  36933. }
  36934. if (bone.animations && bone.animations.length > 0) {
  36935. serializedBone.animation = bone.animations[0].serialize();
  36936. }
  36937. serializationObject.ranges = [];
  36938. for (var name in this._ranges) {
  36939. var range = {};
  36940. range.name = name;
  36941. range.from = this._ranges[name].from;
  36942. range.to = this._ranges[name].to;
  36943. serializationObject.ranges.push(range);
  36944. }
  36945. }
  36946. return serializationObject;
  36947. };
  36948. Skeleton.Parse = function (parsedSkeleton, scene) {
  36949. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  36950. if (parsedSkeleton.dimensionsAtRest) {
  36951. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  36952. }
  36953. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  36954. var index;
  36955. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  36956. var parsedBone = parsedSkeleton.bones[index];
  36957. var parentBone = null;
  36958. if (parsedBone.parentBoneIndex > -1) {
  36959. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  36960. }
  36961. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  36962. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  36963. if (parsedBone.length) {
  36964. bone.length = parsedBone.length;
  36965. }
  36966. if (parsedBone.animation) {
  36967. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  36968. }
  36969. }
  36970. // placed after bones, so createAnimationRange can cascade down
  36971. if (parsedSkeleton.ranges) {
  36972. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  36973. var data = parsedSkeleton.ranges[index];
  36974. skeleton.createAnimationRange(data.name, data.from, data.to);
  36975. }
  36976. }
  36977. return skeleton;
  36978. };
  36979. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  36980. if (forceUpdate === void 0) { forceUpdate = false; }
  36981. var renderId = this._scene.getRenderId();
  36982. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  36983. this.bones[0].computeAbsoluteTransforms();
  36984. this._lastAbsoluteTransformsUpdateId = renderId;
  36985. }
  36986. };
  36987. Skeleton.prototype.getPoseMatrix = function () {
  36988. var poseMatrix;
  36989. if (this._meshesWithPoseMatrix.length > 0) {
  36990. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  36991. }
  36992. return poseMatrix;
  36993. };
  36994. return Skeleton;
  36995. }());
  36996. BABYLON.Skeleton = Skeleton;
  36997. })(BABYLON || (BABYLON = {}));
  36998. //# sourceMappingURL=babylon.skeleton.js.map
  36999. var BABYLON;
  37000. (function (BABYLON) {
  37001. var PostProcess = (function () {
  37002. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  37003. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  37004. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  37005. this.name = name;
  37006. this.width = -1;
  37007. this.height = -1;
  37008. /*
  37009. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  37010. Can only be used on a single postprocess or on the last one of a chain.
  37011. */
  37012. this.enablePixelPerfectMode = false;
  37013. this.samples = 1;
  37014. this._reusable = false;
  37015. this._textures = new BABYLON.SmartArray(2);
  37016. this._currentRenderTextureInd = 0;
  37017. this._scaleRatio = new BABYLON.Vector2(1, 1);
  37018. // Events
  37019. /**
  37020. * An event triggered when the postprocess is activated.
  37021. * @type {BABYLON.Observable}
  37022. */
  37023. this.onActivateObservable = new BABYLON.Observable();
  37024. /**
  37025. * An event triggered when the postprocess changes its size.
  37026. * @type {BABYLON.Observable}
  37027. */
  37028. this.onSizeChangedObservable = new BABYLON.Observable();
  37029. /**
  37030. * An event triggered when the postprocess applies its effect.
  37031. * @type {BABYLON.Observable}
  37032. */
  37033. this.onApplyObservable = new BABYLON.Observable();
  37034. /**
  37035. * An event triggered before rendering the postprocess
  37036. * @type {BABYLON.Observable}
  37037. */
  37038. this.onBeforeRenderObservable = new BABYLON.Observable();
  37039. /**
  37040. * An event triggered after rendering the postprocess
  37041. * @type {BABYLON.Observable}
  37042. */
  37043. this.onAfterRenderObservable = new BABYLON.Observable();
  37044. if (camera != null) {
  37045. this._camera = camera;
  37046. this._scene = camera.getScene();
  37047. camera.attachPostProcess(this);
  37048. this._engine = this._scene.getEngine();
  37049. }
  37050. else {
  37051. this._engine = engine;
  37052. }
  37053. this._options = options;
  37054. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  37055. this._reusable = reusable || false;
  37056. this._textureType = textureType;
  37057. this._samplers = samplers || [];
  37058. this._samplers.push("textureSampler");
  37059. this._fragmentUrl = fragmentUrl;
  37060. this._parameters = parameters || [];
  37061. this._parameters.push("scale");
  37062. this.updateEffect(defines);
  37063. }
  37064. Object.defineProperty(PostProcess.prototype, "onActivate", {
  37065. set: function (callback) {
  37066. if (this._onActivateObserver) {
  37067. this.onActivateObservable.remove(this._onActivateObserver);
  37068. }
  37069. this._onActivateObserver = this.onActivateObservable.add(callback);
  37070. },
  37071. enumerable: true,
  37072. configurable: true
  37073. });
  37074. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  37075. set: function (callback) {
  37076. if (this._onSizeChangedObserver) {
  37077. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  37078. }
  37079. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  37080. },
  37081. enumerable: true,
  37082. configurable: true
  37083. });
  37084. Object.defineProperty(PostProcess.prototype, "onApply", {
  37085. set: function (callback) {
  37086. if (this._onApplyObserver) {
  37087. this.onApplyObservable.remove(this._onApplyObserver);
  37088. }
  37089. this._onApplyObserver = this.onApplyObservable.add(callback);
  37090. },
  37091. enumerable: true,
  37092. configurable: true
  37093. });
  37094. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  37095. set: function (callback) {
  37096. if (this._onBeforeRenderObserver) {
  37097. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  37098. }
  37099. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  37100. },
  37101. enumerable: true,
  37102. configurable: true
  37103. });
  37104. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  37105. set: function (callback) {
  37106. if (this._onAfterRenderObserver) {
  37107. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  37108. }
  37109. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  37110. },
  37111. enumerable: true,
  37112. configurable: true
  37113. });
  37114. PostProcess.prototype.updateEffect = function (defines) {
  37115. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  37116. };
  37117. PostProcess.prototype.isReusable = function () {
  37118. return this._reusable;
  37119. };
  37120. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  37121. PostProcess.prototype.markTextureDirty = function () {
  37122. this.width = -1;
  37123. };
  37124. PostProcess.prototype.activate = function (camera, sourceTexture) {
  37125. var _this = this;
  37126. camera = camera || this._camera;
  37127. var scene = camera.getScene();
  37128. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  37129. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  37130. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  37131. var desiredWidth = this._options.width || requiredWidth;
  37132. var desiredHeight = this._options.height || requiredHeight;
  37133. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  37134. if (!this._options.width) {
  37135. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  37136. }
  37137. if (!this._options.height) {
  37138. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  37139. }
  37140. }
  37141. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  37142. if (this._textures.length > 0) {
  37143. for (var i = 0; i < this._textures.length; i++) {
  37144. this._engine._releaseTexture(this._textures.data[i]);
  37145. }
  37146. this._textures.reset();
  37147. }
  37148. this.width = desiredWidth;
  37149. this.height = desiredHeight;
  37150. var textureSize = { width: this.width, height: this.height };
  37151. var textureOptions = {
  37152. generateMipMaps: false,
  37153. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  37154. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  37155. samplingMode: this.renderTargetSamplingMode,
  37156. type: this._textureType
  37157. };
  37158. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  37159. if (this._reusable) {
  37160. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  37161. }
  37162. this.onSizeChangedObservable.notifyObservers(this);
  37163. }
  37164. this._textures.forEach(function (texture) {
  37165. if (texture.samples !== _this.samples) {
  37166. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  37167. }
  37168. });
  37169. if (this.enablePixelPerfectMode) {
  37170. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  37171. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  37172. }
  37173. else {
  37174. this._scaleRatio.copyFromFloats(1, 1);
  37175. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  37176. }
  37177. this.onActivateObservable.notifyObservers(camera);
  37178. // Clear
  37179. if (this.clearColor) {
  37180. this._engine.clear(this.clearColor, true, true, true);
  37181. }
  37182. else {
  37183. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  37184. }
  37185. if (this._reusable) {
  37186. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  37187. }
  37188. };
  37189. Object.defineProperty(PostProcess.prototype, "isSupported", {
  37190. get: function () {
  37191. return this._effect.isSupported;
  37192. },
  37193. enumerable: true,
  37194. configurable: true
  37195. });
  37196. PostProcess.prototype.apply = function () {
  37197. // Check
  37198. if (!this._effect.isReady())
  37199. return null;
  37200. // States
  37201. this._engine.enableEffect(this._effect);
  37202. this._engine.setState(false);
  37203. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37204. this._engine.setDepthBuffer(false);
  37205. this._engine.setDepthWrite(false);
  37206. // Texture
  37207. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  37208. // Parameters
  37209. this._effect.setVector2("scale", this._scaleRatio);
  37210. this.onApplyObservable.notifyObservers(this._effect);
  37211. return this._effect;
  37212. };
  37213. PostProcess.prototype.dispose = function (camera) {
  37214. camera = camera || this._camera;
  37215. if (this._textures.length > 0) {
  37216. for (var i = 0; i < this._textures.length; i++) {
  37217. this._engine._releaseTexture(this._textures.data[i]);
  37218. }
  37219. }
  37220. this._textures.dispose();
  37221. if (!camera) {
  37222. return;
  37223. }
  37224. camera.detachPostProcess(this);
  37225. var index = camera._postProcesses.indexOf(this);
  37226. if (index === 0 && camera._postProcesses.length > 0) {
  37227. this._camera._postProcesses[0].markTextureDirty();
  37228. }
  37229. this.onActivateObservable.clear();
  37230. this.onAfterRenderObservable.clear();
  37231. this.onApplyObservable.clear();
  37232. this.onBeforeRenderObservable.clear();
  37233. this.onSizeChangedObservable.clear();
  37234. };
  37235. return PostProcess;
  37236. }());
  37237. BABYLON.PostProcess = PostProcess;
  37238. })(BABYLON || (BABYLON = {}));
  37239. //# sourceMappingURL=babylon.postProcess.js.map
  37240. var BABYLON;
  37241. (function (BABYLON) {
  37242. var PostProcessManager = (function () {
  37243. function PostProcessManager(scene) {
  37244. this._vertexBuffers = {};
  37245. this._scene = scene;
  37246. }
  37247. PostProcessManager.prototype._prepareBuffers = function () {
  37248. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37249. return;
  37250. }
  37251. // VBO
  37252. var vertices = [];
  37253. vertices.push(1, 1);
  37254. vertices.push(-1, 1);
  37255. vertices.push(-1, -1);
  37256. vertices.push(1, -1);
  37257. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37258. // Indices
  37259. var indices = [];
  37260. indices.push(0);
  37261. indices.push(1);
  37262. indices.push(2);
  37263. indices.push(0);
  37264. indices.push(2);
  37265. indices.push(3);
  37266. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37267. };
  37268. // Methods
  37269. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  37270. var postProcesses = this._scene.activeCamera._postProcesses;
  37271. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37272. return false;
  37273. }
  37274. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  37275. return true;
  37276. };
  37277. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  37278. var engine = this._scene.getEngine();
  37279. for (var index = 0; index < postProcesses.length; index++) {
  37280. if (index < postProcesses.length - 1) {
  37281. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37282. }
  37283. else {
  37284. if (targetTexture) {
  37285. engine.bindFramebuffer(targetTexture);
  37286. }
  37287. else {
  37288. engine.restoreDefaultFramebuffer();
  37289. }
  37290. }
  37291. var pp = postProcesses[index];
  37292. var effect = pp.apply();
  37293. if (effect) {
  37294. pp.onBeforeRenderObservable.notifyObservers(effect);
  37295. // VBOs
  37296. this._prepareBuffers();
  37297. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37298. // Draw order
  37299. engine.draw(true, 0, 6);
  37300. pp.onAfterRenderObservable.notifyObservers(effect);
  37301. }
  37302. }
  37303. // Restore depth buffer
  37304. engine.setDepthBuffer(true);
  37305. engine.setDepthWrite(true);
  37306. };
  37307. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  37308. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  37309. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37310. return;
  37311. }
  37312. var engine = this._scene.getEngine();
  37313. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37314. if (index < len - 1) {
  37315. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37316. }
  37317. else {
  37318. if (targetTexture) {
  37319. engine.bindFramebuffer(targetTexture, faceIndex);
  37320. }
  37321. else {
  37322. engine.restoreDefaultFramebuffer();
  37323. }
  37324. }
  37325. if (doNotPresent) {
  37326. break;
  37327. }
  37328. var pp = postProcesses[index];
  37329. var effect = pp.apply();
  37330. if (effect) {
  37331. pp.onBeforeRenderObservable.notifyObservers(effect);
  37332. // VBOs
  37333. this._prepareBuffers();
  37334. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37335. // Draw order
  37336. engine.draw(true, 0, 6);
  37337. pp.onAfterRenderObservable.notifyObservers(effect);
  37338. }
  37339. }
  37340. // Restore depth buffer
  37341. engine.setDepthBuffer(true);
  37342. engine.setDepthWrite(true);
  37343. };
  37344. PostProcessManager.prototype.dispose = function () {
  37345. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37346. if (buffer) {
  37347. buffer.dispose();
  37348. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37349. }
  37350. if (this._indexBuffer) {
  37351. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37352. this._indexBuffer = null;
  37353. }
  37354. };
  37355. return PostProcessManager;
  37356. }());
  37357. BABYLON.PostProcessManager = PostProcessManager;
  37358. })(BABYLON || (BABYLON = {}));
  37359. //# sourceMappingURL=babylon.postProcessManager.js.map
  37360. var BABYLON;
  37361. (function (BABYLON) {
  37362. var PassPostProcess = (function (_super) {
  37363. __extends(PassPostProcess, _super);
  37364. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  37365. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  37366. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  37367. }
  37368. return PassPostProcess;
  37369. }(BABYLON.PostProcess));
  37370. BABYLON.PassPostProcess = PassPostProcess;
  37371. })(BABYLON || (BABYLON = {}));
  37372. //# sourceMappingURL=babylon.passPostProcess.js.map
  37373. var BABYLON;
  37374. (function (BABYLON) {
  37375. /**
  37376. * This is a holder class for the physics joint created by the physics plugin.
  37377. * It holds a set of functions to control the underlying joint.
  37378. */
  37379. var PhysicsJoint = (function () {
  37380. function PhysicsJoint(type, jointData) {
  37381. this.type = type;
  37382. this.jointData = jointData;
  37383. jointData.nativeParams = jointData.nativeParams || {};
  37384. }
  37385. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  37386. get: function () {
  37387. return this._physicsJoint;
  37388. },
  37389. set: function (newJoint) {
  37390. if (this._physicsJoint) {
  37391. //remove from the wolrd
  37392. }
  37393. this._physicsJoint = newJoint;
  37394. },
  37395. enumerable: true,
  37396. configurable: true
  37397. });
  37398. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  37399. set: function (physicsPlugin) {
  37400. this._physicsPlugin = physicsPlugin;
  37401. },
  37402. enumerable: true,
  37403. configurable: true
  37404. });
  37405. /**
  37406. * Execute a function that is physics-plugin specific.
  37407. * @param {Function} func the function that will be executed.
  37408. * It accepts two parameters: the physics world and the physics joint.
  37409. */
  37410. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  37411. func(this._physicsPlugin.world, this._physicsJoint);
  37412. };
  37413. return PhysicsJoint;
  37414. }());
  37415. //TODO check if the native joints are the same
  37416. //Joint Types
  37417. PhysicsJoint.DistanceJoint = 0;
  37418. PhysicsJoint.HingeJoint = 1;
  37419. PhysicsJoint.BallAndSocketJoint = 2;
  37420. PhysicsJoint.WheelJoint = 3;
  37421. PhysicsJoint.SliderJoint = 4;
  37422. //OIMO
  37423. PhysicsJoint.PrismaticJoint = 5;
  37424. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  37425. PhysicsJoint.UniversalJoint = 6;
  37426. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  37427. //Cannon
  37428. //Similar to a Ball-Joint. Different in params
  37429. PhysicsJoint.PointToPointJoint = 8;
  37430. //Cannon only at the moment
  37431. PhysicsJoint.SpringJoint = 9;
  37432. PhysicsJoint.LockJoint = 10;
  37433. BABYLON.PhysicsJoint = PhysicsJoint;
  37434. /**
  37435. * A class representing a physics distance joint.
  37436. */
  37437. var DistanceJoint = (function (_super) {
  37438. __extends(DistanceJoint, _super);
  37439. function DistanceJoint(jointData) {
  37440. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  37441. }
  37442. /**
  37443. * Update the predefined distance.
  37444. */
  37445. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  37446. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  37447. };
  37448. return DistanceJoint;
  37449. }(PhysicsJoint));
  37450. BABYLON.DistanceJoint = DistanceJoint;
  37451. var MotorEnabledJoint = (function (_super) {
  37452. __extends(MotorEnabledJoint, _super);
  37453. function MotorEnabledJoint(type, jointData) {
  37454. return _super.call(this, type, jointData) || this;
  37455. }
  37456. /**
  37457. * Set the motor values.
  37458. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37459. * @param {number} force the force to apply
  37460. * @param {number} maxForce max force for this motor.
  37461. */
  37462. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  37463. this._physicsPlugin.setMotor(this, force, maxForce);
  37464. };
  37465. /**
  37466. * Set the motor's limits.
  37467. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37468. */
  37469. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  37470. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  37471. };
  37472. return MotorEnabledJoint;
  37473. }(PhysicsJoint));
  37474. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  37475. /**
  37476. * This class represents a single hinge physics joint
  37477. */
  37478. var HingeJoint = (function (_super) {
  37479. __extends(HingeJoint, _super);
  37480. function HingeJoint(jointData) {
  37481. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  37482. }
  37483. /**
  37484. * Set the motor values.
  37485. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37486. * @param {number} force the force to apply
  37487. * @param {number} maxForce max force for this motor.
  37488. */
  37489. HingeJoint.prototype.setMotor = function (force, maxForce) {
  37490. this._physicsPlugin.setMotor(this, force, maxForce);
  37491. };
  37492. /**
  37493. * Set the motor's limits.
  37494. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37495. */
  37496. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  37497. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  37498. };
  37499. return HingeJoint;
  37500. }(MotorEnabledJoint));
  37501. BABYLON.HingeJoint = HingeJoint;
  37502. /**
  37503. * This class represents a dual hinge physics joint (same as wheel joint)
  37504. */
  37505. var Hinge2Joint = (function (_super) {
  37506. __extends(Hinge2Joint, _super);
  37507. function Hinge2Joint(jointData) {
  37508. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  37509. }
  37510. /**
  37511. * Set the motor values.
  37512. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37513. * @param {number} force the force to apply
  37514. * @param {number} maxForce max force for this motor.
  37515. * @param {motorIndex} the motor's index, 0 or 1.
  37516. */
  37517. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  37518. if (motorIndex === void 0) { motorIndex = 0; }
  37519. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  37520. };
  37521. /**
  37522. * Set the motor limits.
  37523. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37524. * @param {number} upperLimit the upper limit
  37525. * @param {number} lowerLimit lower limit
  37526. * @param {motorIndex} the motor's index, 0 or 1.
  37527. */
  37528. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  37529. if (motorIndex === void 0) { motorIndex = 0; }
  37530. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  37531. };
  37532. return Hinge2Joint;
  37533. }(MotorEnabledJoint));
  37534. BABYLON.Hinge2Joint = Hinge2Joint;
  37535. })(BABYLON || (BABYLON = {}));
  37536. //# sourceMappingURL=babylon.physicsJoint.js.map
  37537. var BABYLON;
  37538. (function (BABYLON) {
  37539. var PhysicsImpostor = (function () {
  37540. function PhysicsImpostor(object, type, _options, _scene) {
  37541. if (_options === void 0) { _options = { mass: 0 }; }
  37542. var _this = this;
  37543. this.object = object;
  37544. this.type = type;
  37545. this._options = _options;
  37546. this._scene = _scene;
  37547. this._bodyUpdateRequired = false;
  37548. this._onBeforePhysicsStepCallbacks = new Array();
  37549. this._onAfterPhysicsStepCallbacks = new Array();
  37550. this._onPhysicsCollideCallbacks = [];
  37551. this._deltaPosition = BABYLON.Vector3.Zero();
  37552. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  37553. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  37554. /**
  37555. * this function is executed by the physics engine.
  37556. */
  37557. this.beforeStep = function () {
  37558. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  37559. //conjugate deltaRotation
  37560. if (_this._deltaRotationConjugated) {
  37561. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  37562. }
  37563. else {
  37564. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  37565. }
  37566. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  37567. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  37568. func(_this);
  37569. });
  37570. };
  37571. /**
  37572. * this function is executed by the physics engine.
  37573. */
  37574. this.afterStep = function () {
  37575. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  37576. func(_this);
  37577. });
  37578. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  37579. _this.object.position.addInPlace(_this._deltaPosition);
  37580. if (_this._deltaRotation) {
  37581. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  37582. }
  37583. };
  37584. /**
  37585. * Legacy collision detection event support
  37586. */
  37587. this.onCollideEvent = null;
  37588. //event and body object due to cannon's event-based architecture.
  37589. this.onCollide = function (e) {
  37590. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  37591. return;
  37592. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  37593. if (otherImpostor) {
  37594. // Legacy collision detection event support
  37595. if (_this.onCollideEvent) {
  37596. _this.onCollideEvent(_this, otherImpostor);
  37597. }
  37598. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  37599. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  37600. }).forEach(function (obj) {
  37601. obj.callback(_this, otherImpostor);
  37602. });
  37603. }
  37604. };
  37605. //sanity check!
  37606. if (!this.object) {
  37607. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  37608. return;
  37609. }
  37610. //legacy support for old syntax.
  37611. if (!this._scene && object.getScene) {
  37612. this._scene = object.getScene();
  37613. }
  37614. this._physicsEngine = this._scene.getPhysicsEngine();
  37615. if (!this._physicsEngine) {
  37616. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  37617. }
  37618. else {
  37619. //set the object's quaternion, if not set
  37620. if (!this.object.rotationQuaternion) {
  37621. if (this.object.rotation) {
  37622. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  37623. }
  37624. else {
  37625. this.object.rotationQuaternion = new BABYLON.Quaternion();
  37626. }
  37627. }
  37628. //default options params
  37629. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  37630. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  37631. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  37632. this._joints = [];
  37633. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  37634. if (!this.object.parent) {
  37635. this._init();
  37636. }
  37637. }
  37638. }
  37639. /**
  37640. * This function will completly initialize this impostor.
  37641. * It will create a new body - but only if this mesh has no parent.
  37642. * If it has, this impostor will not be used other than to define the impostor
  37643. * of the child mesh.
  37644. */
  37645. PhysicsImpostor.prototype._init = function () {
  37646. this._physicsEngine.removeImpostor(this);
  37647. this.physicsBody = null;
  37648. this._parent = this._parent || this._getPhysicsParent();
  37649. if (!this.parent) {
  37650. this._physicsEngine.addImpostor(this);
  37651. }
  37652. };
  37653. PhysicsImpostor.prototype._getPhysicsParent = function () {
  37654. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  37655. var parentMesh = this.object.parent;
  37656. return parentMesh.physicsImpostor;
  37657. }
  37658. return;
  37659. };
  37660. /**
  37661. * Should a new body be generated.
  37662. */
  37663. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  37664. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  37665. };
  37666. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  37667. this.forceUpdate();
  37668. };
  37669. /**
  37670. * Force a regeneration of this or the parent's impostor's body.
  37671. * Use under cautious - This will remove all joints already implemented.
  37672. */
  37673. PhysicsImpostor.prototype.forceUpdate = function () {
  37674. this._init();
  37675. if (this.parent) {
  37676. this.parent.forceUpdate();
  37677. }
  37678. };
  37679. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  37680. /*public get mesh(): AbstractMesh {
  37681. return this._mesh;
  37682. }*/
  37683. /**
  37684. * Gets the body that holds this impostor. Either its own, or its parent.
  37685. */
  37686. get: function () {
  37687. return this._parent ? this._parent.physicsBody : this._physicsBody;
  37688. },
  37689. /**
  37690. * Set the physics body. Used mainly by the physics engine/plugin
  37691. */
  37692. set: function (physicsBody) {
  37693. if (this._physicsBody) {
  37694. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  37695. }
  37696. this._physicsBody = physicsBody;
  37697. this.resetUpdateFlags();
  37698. },
  37699. enumerable: true,
  37700. configurable: true
  37701. });
  37702. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  37703. get: function () {
  37704. return this._parent;
  37705. },
  37706. set: function (value) {
  37707. this._parent = value;
  37708. },
  37709. enumerable: true,
  37710. configurable: true
  37711. });
  37712. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  37713. this._bodyUpdateRequired = false;
  37714. };
  37715. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  37716. if (this.object.getBoundingInfo) {
  37717. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  37718. return this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2).multiply(this.object.scaling);
  37719. }
  37720. else {
  37721. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  37722. }
  37723. };
  37724. PhysicsImpostor.prototype.getObjectCenter = function () {
  37725. if (this.object.getBoundingInfo) {
  37726. return this.object.getBoundingInfo().boundingBox.centerWorld;
  37727. }
  37728. else {
  37729. return this.object.position;
  37730. }
  37731. };
  37732. /**
  37733. * Get a specific parametes from the options parameter.
  37734. */
  37735. PhysicsImpostor.prototype.getParam = function (paramName) {
  37736. return this._options[paramName];
  37737. };
  37738. /**
  37739. * Sets a specific parameter in the options given to the physics plugin
  37740. */
  37741. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  37742. this._options[paramName] = value;
  37743. this._bodyUpdateRequired = true;
  37744. };
  37745. /**
  37746. * Specifically change the body's mass option. Won't recreate the physics body object
  37747. */
  37748. PhysicsImpostor.prototype.setMass = function (mass) {
  37749. if (this.getParam("mass") !== mass) {
  37750. this.setParam("mass", mass);
  37751. }
  37752. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  37753. };
  37754. PhysicsImpostor.prototype.getLinearVelocity = function () {
  37755. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  37756. };
  37757. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  37758. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  37759. };
  37760. PhysicsImpostor.prototype.getAngularVelocity = function () {
  37761. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  37762. };
  37763. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  37764. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  37765. };
  37766. /**
  37767. * Execute a function with the physics plugin native code.
  37768. * Provide a function the will have two variables - the world object and the physics body object.
  37769. */
  37770. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  37771. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  37772. };
  37773. /**
  37774. * Register a function that will be executed before the physics world is stepping forward.
  37775. */
  37776. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  37777. this._onBeforePhysicsStepCallbacks.push(func);
  37778. };
  37779. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  37780. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  37781. if (index > -1) {
  37782. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  37783. }
  37784. else {
  37785. BABYLON.Tools.Warn("Function to remove was not found");
  37786. }
  37787. };
  37788. /**
  37789. * Register a function that will be executed after the physics step
  37790. */
  37791. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  37792. this._onAfterPhysicsStepCallbacks.push(func);
  37793. };
  37794. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  37795. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  37796. if (index > -1) {
  37797. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  37798. }
  37799. else {
  37800. BABYLON.Tools.Warn("Function to remove was not found");
  37801. }
  37802. };
  37803. /**
  37804. * register a function that will be executed when this impostor collides against a different body.
  37805. */
  37806. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  37807. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  37808. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  37809. };
  37810. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  37811. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  37812. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  37813. if (index > -1) {
  37814. this._onPhysicsCollideCallbacks.splice(index, 1);
  37815. }
  37816. else {
  37817. BABYLON.Tools.Warn("Function to remove was not found");
  37818. }
  37819. };
  37820. /**
  37821. * Apply a force
  37822. */
  37823. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  37824. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  37825. };
  37826. /**
  37827. * Apply an impulse
  37828. */
  37829. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  37830. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  37831. };
  37832. /**
  37833. * A help function to create a joint.
  37834. */
  37835. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  37836. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  37837. this.addJoint(otherImpostor, joint);
  37838. };
  37839. /**
  37840. * Add a joint to this impostor with a different impostor.
  37841. */
  37842. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  37843. this._joints.push({
  37844. otherImpostor: otherImpostor,
  37845. joint: joint
  37846. });
  37847. this._physicsEngine.addJoint(this, otherImpostor, joint);
  37848. };
  37849. /**
  37850. * Will keep this body still, in a sleep mode.
  37851. */
  37852. PhysicsImpostor.prototype.sleep = function () {
  37853. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  37854. };
  37855. /**
  37856. * Wake the body up.
  37857. */
  37858. PhysicsImpostor.prototype.wakeUp = function () {
  37859. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  37860. };
  37861. PhysicsImpostor.prototype.clone = function (newObject) {
  37862. if (!newObject)
  37863. return null;
  37864. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  37865. };
  37866. PhysicsImpostor.prototype.dispose = function () {
  37867. var _this = this;
  37868. //no dispose if no physics engine is available.
  37869. if (!this._physicsEngine) {
  37870. return;
  37871. }
  37872. this._joints.forEach(function (j) {
  37873. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  37874. });
  37875. //dispose the physics body
  37876. this._physicsEngine.removeImpostor(this);
  37877. if (this.parent) {
  37878. this.parent.forceUpdate();
  37879. }
  37880. else {
  37881. /*this._object.getChildMeshes().forEach(function(mesh) {
  37882. if (mesh.physicsImpostor) {
  37883. if (disposeChildren) {
  37884. mesh.physicsImpostor.dispose();
  37885. mesh.physicsImpostor = null;
  37886. }
  37887. }
  37888. })*/
  37889. }
  37890. };
  37891. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  37892. this._deltaPosition.copyFrom(position);
  37893. };
  37894. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  37895. if (!this._deltaRotation) {
  37896. this._deltaRotation = new BABYLON.Quaternion();
  37897. }
  37898. this._deltaRotation.copyFrom(rotation);
  37899. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  37900. };
  37901. return PhysicsImpostor;
  37902. }());
  37903. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  37904. //Impostor types
  37905. PhysicsImpostor.NoImpostor = 0;
  37906. PhysicsImpostor.SphereImpostor = 1;
  37907. PhysicsImpostor.BoxImpostor = 2;
  37908. PhysicsImpostor.PlaneImpostor = 3;
  37909. PhysicsImpostor.MeshImpostor = 4;
  37910. PhysicsImpostor.CylinderImpostor = 7;
  37911. PhysicsImpostor.ParticleImpostor = 8;
  37912. PhysicsImpostor.HeightmapImpostor = 9;
  37913. BABYLON.PhysicsImpostor = PhysicsImpostor;
  37914. })(BABYLON || (BABYLON = {}));
  37915. //# sourceMappingURL=babylon.physicsImpostor.js.map
  37916. var BABYLON;
  37917. (function (BABYLON) {
  37918. var PhysicsEngine = (function () {
  37919. function PhysicsEngine(gravity, _physicsPlugin) {
  37920. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  37921. this._physicsPlugin = _physicsPlugin;
  37922. //new methods and parameters
  37923. this._impostors = [];
  37924. this._joints = [];
  37925. if (!this._physicsPlugin.isSupported()) {
  37926. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  37927. + "Please make sure it is included.");
  37928. }
  37929. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  37930. this.setGravity(gravity);
  37931. this.setTimeStep();
  37932. }
  37933. PhysicsEngine.prototype.setGravity = function (gravity) {
  37934. this.gravity = gravity;
  37935. this._physicsPlugin.setGravity(this.gravity);
  37936. };
  37937. /**
  37938. * Set the time step of the physics engine.
  37939. * default is 1/60.
  37940. * To slow it down, enter 1/600 for example.
  37941. * To speed it up, 1/30
  37942. * @param {number} newTimeStep the new timestep to apply to this world.
  37943. */
  37944. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  37945. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  37946. this._physicsPlugin.setTimeStep(newTimeStep);
  37947. };
  37948. PhysicsEngine.prototype.dispose = function () {
  37949. this._impostors.forEach(function (impostor) {
  37950. impostor.dispose();
  37951. });
  37952. this._physicsPlugin.dispose();
  37953. };
  37954. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  37955. return this._physicsPlugin.name;
  37956. };
  37957. /**
  37958. * Adding a new impostor for the impostor tracking.
  37959. * This will be done by the impostor itself.
  37960. * @param {PhysicsImpostor} impostor the impostor to add
  37961. */
  37962. PhysicsEngine.prototype.addImpostor = function (impostor) {
  37963. impostor.uniqueId = this._impostors.push(impostor);
  37964. //if no parent, generate the body
  37965. if (!impostor.parent) {
  37966. this._physicsPlugin.generatePhysicsBody(impostor);
  37967. }
  37968. };
  37969. /**
  37970. * Remove an impostor from the engine.
  37971. * This impostor and its mesh will not longer be updated by the physics engine.
  37972. * @param {PhysicsImpostor} impostor the impostor to remove
  37973. */
  37974. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  37975. var index = this._impostors.indexOf(impostor);
  37976. if (index > -1) {
  37977. var removed = this._impostors.splice(index, 1);
  37978. //Is it needed?
  37979. if (removed.length) {
  37980. //this will also remove it from the world.
  37981. removed[0].physicsBody = null;
  37982. }
  37983. }
  37984. };
  37985. /**
  37986. * Add a joint to the physics engine
  37987. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  37988. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  37989. * @param {PhysicsJoint} the joint that will connect both impostors.
  37990. */
  37991. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  37992. var impostorJoint = {
  37993. mainImpostor: mainImpostor,
  37994. connectedImpostor: connectedImpostor,
  37995. joint: joint
  37996. };
  37997. joint.physicsPlugin = this._physicsPlugin;
  37998. this._joints.push(impostorJoint);
  37999. this._physicsPlugin.generateJoint(impostorJoint);
  38000. };
  38001. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  38002. var matchingJoints = this._joints.filter(function (impostorJoint) {
  38003. return (impostorJoint.connectedImpostor === connectedImpostor
  38004. && impostorJoint.joint === joint
  38005. && impostorJoint.mainImpostor === mainImpostor);
  38006. });
  38007. if (matchingJoints.length) {
  38008. this._physicsPlugin.removeJoint(matchingJoints[0]);
  38009. //TODO remove it from the list as well
  38010. }
  38011. };
  38012. /**
  38013. * Called by the scene. no need to call it.
  38014. */
  38015. PhysicsEngine.prototype._step = function (delta) {
  38016. var _this = this;
  38017. //check if any mesh has no body / requires an update
  38018. this._impostors.forEach(function (impostor) {
  38019. if (impostor.isBodyInitRequired()) {
  38020. _this._physicsPlugin.generatePhysicsBody(impostor);
  38021. }
  38022. });
  38023. if (delta > 0.1) {
  38024. delta = 0.1;
  38025. }
  38026. else if (delta <= 0) {
  38027. delta = 1.0 / 60.0;
  38028. }
  38029. this._physicsPlugin.executeStep(delta, this._impostors);
  38030. };
  38031. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  38032. return this._physicsPlugin;
  38033. };
  38034. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  38035. for (var i = 0; i < this._impostors.length; ++i) {
  38036. if (this._impostors[i].object === object) {
  38037. return this._impostors[i];
  38038. }
  38039. }
  38040. };
  38041. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  38042. for (var i = 0; i < this._impostors.length; ++i) {
  38043. if (this._impostors[i].physicsBody === body) {
  38044. return this._impostors[i];
  38045. }
  38046. }
  38047. };
  38048. return PhysicsEngine;
  38049. }());
  38050. // Statics
  38051. PhysicsEngine.Epsilon = 0.001;
  38052. BABYLON.PhysicsEngine = PhysicsEngine;
  38053. })(BABYLON || (BABYLON = {}));
  38054. //# sourceMappingURL=babylon.physicsEngine.js.map
  38055. var BABYLON;
  38056. (function (BABYLON) {
  38057. var VertexData = (function () {
  38058. function VertexData() {
  38059. }
  38060. VertexData.prototype.set = function (data, kind) {
  38061. switch (kind) {
  38062. case BABYLON.VertexBuffer.PositionKind:
  38063. this.positions = data;
  38064. break;
  38065. case BABYLON.VertexBuffer.NormalKind:
  38066. this.normals = data;
  38067. break;
  38068. case BABYLON.VertexBuffer.TangentKind:
  38069. this.tangents = data;
  38070. break;
  38071. case BABYLON.VertexBuffer.UVKind:
  38072. this.uvs = data;
  38073. break;
  38074. case BABYLON.VertexBuffer.UV2Kind:
  38075. this.uvs2 = data;
  38076. break;
  38077. case BABYLON.VertexBuffer.UV3Kind:
  38078. this.uvs3 = data;
  38079. break;
  38080. case BABYLON.VertexBuffer.UV4Kind:
  38081. this.uvs4 = data;
  38082. break;
  38083. case BABYLON.VertexBuffer.UV5Kind:
  38084. this.uvs5 = data;
  38085. break;
  38086. case BABYLON.VertexBuffer.UV6Kind:
  38087. this.uvs6 = data;
  38088. break;
  38089. case BABYLON.VertexBuffer.ColorKind:
  38090. this.colors = data;
  38091. break;
  38092. case BABYLON.VertexBuffer.MatricesIndicesKind:
  38093. this.matricesIndices = data;
  38094. break;
  38095. case BABYLON.VertexBuffer.MatricesWeightsKind:
  38096. this.matricesWeights = data;
  38097. break;
  38098. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  38099. this.matricesIndicesExtra = data;
  38100. break;
  38101. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  38102. this.matricesWeightsExtra = data;
  38103. break;
  38104. }
  38105. };
  38106. /**
  38107. * Associates the vertexData to the passed Mesh.
  38108. * Sets it as updatable or not (default `false`).
  38109. * Returns the VertexData.
  38110. */
  38111. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  38112. this._applyTo(mesh, updatable);
  38113. return this;
  38114. };
  38115. /**
  38116. * Associates the vertexData to the passed Geometry.
  38117. * Sets it as updatable or not (default `false`).
  38118. * Returns the VertexData.
  38119. */
  38120. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  38121. this._applyTo(geometry, updatable);
  38122. return this;
  38123. };
  38124. /**
  38125. * Updates the associated mesh.
  38126. * Returns the VertexData.
  38127. */
  38128. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  38129. this._update(mesh);
  38130. return this;
  38131. };
  38132. /**
  38133. * Updates the associated geometry.
  38134. * Returns the VertexData.
  38135. */
  38136. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  38137. this._update(geometry);
  38138. return this;
  38139. };
  38140. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  38141. if (this.positions) {
  38142. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  38143. }
  38144. if (this.normals) {
  38145. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  38146. }
  38147. if (this.tangents) {
  38148. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  38149. }
  38150. if (this.uvs) {
  38151. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  38152. }
  38153. if (this.uvs2) {
  38154. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  38155. }
  38156. if (this.uvs3) {
  38157. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  38158. }
  38159. if (this.uvs4) {
  38160. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  38161. }
  38162. if (this.uvs5) {
  38163. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  38164. }
  38165. if (this.uvs6) {
  38166. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  38167. }
  38168. if (this.colors) {
  38169. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  38170. }
  38171. if (this.matricesIndices) {
  38172. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  38173. }
  38174. if (this.matricesWeights) {
  38175. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  38176. }
  38177. if (this.matricesIndicesExtra) {
  38178. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  38179. }
  38180. if (this.matricesWeightsExtra) {
  38181. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  38182. }
  38183. if (this.indices) {
  38184. meshOrGeometry.setIndices(this.indices);
  38185. }
  38186. return this;
  38187. };
  38188. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  38189. if (this.positions) {
  38190. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  38191. }
  38192. if (this.normals) {
  38193. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  38194. }
  38195. if (this.tangents) {
  38196. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  38197. }
  38198. if (this.uvs) {
  38199. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  38200. }
  38201. if (this.uvs2) {
  38202. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  38203. }
  38204. if (this.uvs3) {
  38205. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  38206. }
  38207. if (this.uvs4) {
  38208. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  38209. }
  38210. if (this.uvs5) {
  38211. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  38212. }
  38213. if (this.uvs6) {
  38214. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  38215. }
  38216. if (this.colors) {
  38217. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  38218. }
  38219. if (this.matricesIndices) {
  38220. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  38221. }
  38222. if (this.matricesWeights) {
  38223. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  38224. }
  38225. if (this.matricesIndicesExtra) {
  38226. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  38227. }
  38228. if (this.matricesWeightsExtra) {
  38229. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  38230. }
  38231. if (this.indices) {
  38232. meshOrGeometry.setIndices(this.indices);
  38233. }
  38234. return this;
  38235. };
  38236. /**
  38237. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  38238. * Returns the VertexData.
  38239. */
  38240. VertexData.prototype.transform = function (matrix) {
  38241. var transformed = BABYLON.Vector3.Zero();
  38242. var index;
  38243. if (this.positions) {
  38244. var position = BABYLON.Vector3.Zero();
  38245. for (index = 0; index < this.positions.length; index += 3) {
  38246. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  38247. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  38248. this.positions[index] = transformed.x;
  38249. this.positions[index + 1] = transformed.y;
  38250. this.positions[index + 2] = transformed.z;
  38251. }
  38252. }
  38253. if (this.normals) {
  38254. var normal = BABYLON.Vector3.Zero();
  38255. for (index = 0; index < this.normals.length; index += 3) {
  38256. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  38257. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  38258. this.normals[index] = transformed.x;
  38259. this.normals[index + 1] = transformed.y;
  38260. this.normals[index + 2] = transformed.z;
  38261. }
  38262. }
  38263. if (this.tangents) {
  38264. var tangent = BABYLON.Vector4.Zero();
  38265. var tangentTransformed = BABYLON.Vector4.Zero();
  38266. for (index = 0; index < this.tangents.length; index += 4) {
  38267. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  38268. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  38269. this.tangents[index] = tangentTransformed.x;
  38270. this.tangents[index + 1] = tangentTransformed.y;
  38271. this.tangents[index + 2] = tangentTransformed.z;
  38272. this.tangents[index + 3] = tangentTransformed.w;
  38273. }
  38274. }
  38275. return this;
  38276. };
  38277. /**
  38278. * Merges the passed VertexData into the current one.
  38279. * Returns the modified VertexData.
  38280. */
  38281. VertexData.prototype.merge = function (other) {
  38282. if (other.indices) {
  38283. if (!this.indices) {
  38284. this.indices = [];
  38285. }
  38286. var offset = this.positions ? this.positions.length / 3 : 0;
  38287. for (var index = 0; index < other.indices.length; index++) {
  38288. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  38289. this.indices.push(other.indices[index] + offset);
  38290. }
  38291. }
  38292. this.positions = this._mergeElement(this.positions, other.positions);
  38293. this.normals = this._mergeElement(this.normals, other.normals);
  38294. this.tangents = this._mergeElement(this.tangents, other.tangents);
  38295. this.uvs = this._mergeElement(this.uvs, other.uvs);
  38296. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  38297. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  38298. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  38299. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  38300. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  38301. this.colors = this._mergeElement(this.colors, other.colors);
  38302. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  38303. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  38304. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  38305. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  38306. return this;
  38307. };
  38308. VertexData.prototype._mergeElement = function (source, other) {
  38309. if (!other)
  38310. return source;
  38311. if (!source)
  38312. return other;
  38313. var len = other.length + source.length;
  38314. var isSrcTypedArray = source instanceof Float32Array;
  38315. var isOthTypedArray = other instanceof Float32Array;
  38316. // use non-loop method when the source is Float32Array
  38317. if (isSrcTypedArray) {
  38318. var ret32 = new Float32Array(len);
  38319. ret32.set(source);
  38320. ret32.set(other, source.length);
  38321. return ret32;
  38322. // source is number[], when other is also use concat
  38323. }
  38324. else if (!isOthTypedArray) {
  38325. return source.concat(other);
  38326. // source is a number[], but other is a Float32Array, loop required
  38327. }
  38328. else {
  38329. var ret = source.slice(0); // copy source to a separate array
  38330. for (var i = 0, len = other.length; i < len; i++) {
  38331. ret.push(other[i]);
  38332. }
  38333. return ret;
  38334. }
  38335. };
  38336. /**
  38337. * Serializes the VertexData.
  38338. * Returns a serialized object.
  38339. */
  38340. VertexData.prototype.serialize = function () {
  38341. var serializationObject = this.serialize();
  38342. if (this.positions) {
  38343. serializationObject.positions = this.positions;
  38344. }
  38345. if (this.normals) {
  38346. serializationObject.normals = this.normals;
  38347. }
  38348. if (this.tangents) {
  38349. serializationObject.tangents = this.tangents;
  38350. }
  38351. if (this.uvs) {
  38352. serializationObject.uvs = this.uvs;
  38353. }
  38354. if (this.uvs2) {
  38355. serializationObject.uvs2 = this.uvs2;
  38356. }
  38357. if (this.uvs3) {
  38358. serializationObject.uvs3 = this.uvs3;
  38359. }
  38360. if (this.uvs4) {
  38361. serializationObject.uvs4 = this.uvs4;
  38362. }
  38363. if (this.uvs5) {
  38364. serializationObject.uvs5 = this.uvs5;
  38365. }
  38366. if (this.uvs6) {
  38367. serializationObject.uvs6 = this.uvs6;
  38368. }
  38369. if (this.colors) {
  38370. serializationObject.colors = this.colors;
  38371. }
  38372. if (this.matricesIndices) {
  38373. serializationObject.matricesIndices = this.matricesIndices;
  38374. serializationObject.matricesIndices._isExpanded = true;
  38375. }
  38376. if (this.matricesWeights) {
  38377. serializationObject.matricesWeights = this.matricesWeights;
  38378. }
  38379. if (this.matricesIndicesExtra) {
  38380. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  38381. serializationObject.matricesIndicesExtra._isExpanded = true;
  38382. }
  38383. if (this.matricesWeightsExtra) {
  38384. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  38385. }
  38386. serializationObject.indices = this.indices;
  38387. return serializationObject;
  38388. };
  38389. // Statics
  38390. /**
  38391. * Returns the object VertexData associated to the passed mesh.
  38392. */
  38393. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  38394. return VertexData._ExtractFrom(mesh, copyWhenShared);
  38395. };
  38396. /**
  38397. * Returns the object VertexData associated to the passed geometry.
  38398. */
  38399. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  38400. return VertexData._ExtractFrom(geometry, copyWhenShared);
  38401. };
  38402. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  38403. var result = new VertexData();
  38404. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38405. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  38406. }
  38407. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38408. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  38409. }
  38410. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38411. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared);
  38412. }
  38413. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38414. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  38415. }
  38416. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38417. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  38418. }
  38419. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38420. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  38421. }
  38422. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38423. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  38424. }
  38425. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38426. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  38427. }
  38428. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38429. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  38430. }
  38431. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38432. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  38433. }
  38434. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38435. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  38436. }
  38437. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38438. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  38439. }
  38440. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  38441. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  38442. }
  38443. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  38444. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  38445. }
  38446. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  38447. return result;
  38448. };
  38449. /**
  38450. * Creates the vertexData of the Ribbon.
  38451. */
  38452. VertexData.CreateRibbon = function (options) {
  38453. var pathArray = options.pathArray;
  38454. var closeArray = options.closeArray || false;
  38455. var closePath = options.closePath || false;
  38456. var invertUV = options.invertUV || false;
  38457. var defaultOffset = Math.floor(pathArray[0].length / 2);
  38458. var offset = options.offset || defaultOffset;
  38459. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  38460. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38461. var customUV = options.uvs;
  38462. var customColors = options.colors;
  38463. var positions = [];
  38464. var indices = [];
  38465. var normals = [];
  38466. var uvs = [];
  38467. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  38468. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  38469. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  38470. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  38471. var minlg; // minimal length among all paths from pathArray
  38472. var lg = []; // array of path lengths : nb of vertex per path
  38473. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  38474. var p; // path iterator
  38475. var i; // point iterator
  38476. var j; // point iterator
  38477. // if single path in pathArray
  38478. if (pathArray.length < 2) {
  38479. var ar1 = [];
  38480. var ar2 = [];
  38481. for (i = 0; i < pathArray[0].length - offset; i++) {
  38482. ar1.push(pathArray[0][i]);
  38483. ar2.push(pathArray[0][i + offset]);
  38484. }
  38485. pathArray = [ar1, ar2];
  38486. }
  38487. // positions and horizontal distances (u)
  38488. var idc = 0;
  38489. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  38490. var path;
  38491. var l;
  38492. minlg = pathArray[0].length;
  38493. var vectlg;
  38494. var dist;
  38495. for (p = 0; p < pathArray.length; p++) {
  38496. uTotalDistance[p] = 0;
  38497. us[p] = [0];
  38498. path = pathArray[p];
  38499. l = path.length;
  38500. minlg = (minlg < l) ? minlg : l;
  38501. j = 0;
  38502. while (j < l) {
  38503. positions.push(path[j].x, path[j].y, path[j].z);
  38504. if (j > 0) {
  38505. vectlg = path[j].subtract(path[j - 1]).length();
  38506. dist = vectlg + uTotalDistance[p];
  38507. us[p].push(dist);
  38508. uTotalDistance[p] = dist;
  38509. }
  38510. j++;
  38511. }
  38512. if (closePath) {
  38513. j--;
  38514. positions.push(path[0].x, path[0].y, path[0].z);
  38515. vectlg = path[j].subtract(path[0]).length();
  38516. dist = vectlg + uTotalDistance[p];
  38517. us[p].push(dist);
  38518. uTotalDistance[p] = dist;
  38519. }
  38520. lg[p] = l + closePathCorr;
  38521. idx[p] = idc;
  38522. idc += (l + closePathCorr);
  38523. }
  38524. // vertical distances (v)
  38525. var path1;
  38526. var path2;
  38527. var vertex1;
  38528. var vertex2;
  38529. for (i = 0; i < minlg + closePathCorr; i++) {
  38530. vTotalDistance[i] = 0;
  38531. vs[i] = [0];
  38532. for (p = 0; p < pathArray.length - 1; p++) {
  38533. path1 = pathArray[p];
  38534. path2 = pathArray[p + 1];
  38535. if (i === minlg) {
  38536. vertex1 = path1[0];
  38537. vertex2 = path2[0];
  38538. }
  38539. else {
  38540. vertex1 = path1[i];
  38541. vertex2 = path2[i];
  38542. }
  38543. vectlg = vertex2.subtract(vertex1).length();
  38544. dist = vectlg + vTotalDistance[i];
  38545. vs[i].push(dist);
  38546. vTotalDistance[i] = dist;
  38547. }
  38548. if (closeArray) {
  38549. path1 = pathArray[p];
  38550. path2 = pathArray[0];
  38551. if (i === minlg) {
  38552. vertex2 = path2[0];
  38553. }
  38554. vectlg = vertex2.subtract(vertex1).length();
  38555. dist = vectlg + vTotalDistance[i];
  38556. vTotalDistance[i] = dist;
  38557. }
  38558. }
  38559. // uvs
  38560. var u;
  38561. var v;
  38562. if (customUV) {
  38563. for (p = 0; p < customUV.length; p++) {
  38564. uvs.push(customUV[p].x, customUV[p].y);
  38565. }
  38566. }
  38567. else {
  38568. for (p = 0; p < pathArray.length; p++) {
  38569. for (i = 0; i < minlg + closePathCorr; i++) {
  38570. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  38571. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  38572. if (invertUV) {
  38573. uvs.push(v, u);
  38574. }
  38575. else {
  38576. uvs.push(u, v);
  38577. }
  38578. }
  38579. }
  38580. }
  38581. // indices
  38582. p = 0; // path index
  38583. var pi = 0; // positions array index
  38584. var l1 = lg[p] - 1; // path1 length
  38585. var l2 = lg[p + 1] - 1; // path2 length
  38586. var min = (l1 < l2) ? l1 : l2; // current path stop index
  38587. var shft = idx[1] - idx[0]; // shift
  38588. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  38589. while (pi <= min && p < path1nb) {
  38590. // 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
  38591. indices.push(pi, pi + shft, pi + 1);
  38592. indices.push(pi + shft + 1, pi + 1, pi + shft);
  38593. pi += 1;
  38594. if (pi === min) {
  38595. p++;
  38596. if (p === lg.length - 1) {
  38597. shft = idx[0] - idx[p];
  38598. l1 = lg[p] - 1;
  38599. l2 = lg[0] - 1;
  38600. }
  38601. else {
  38602. shft = idx[p + 1] - idx[p];
  38603. l1 = lg[p] - 1;
  38604. l2 = lg[p + 1] - 1;
  38605. }
  38606. pi = idx[p];
  38607. min = (l1 < l2) ? l1 + pi : l2 + pi;
  38608. }
  38609. }
  38610. // normals
  38611. VertexData.ComputeNormals(positions, indices, normals);
  38612. if (closePath) {
  38613. var indexFirst = 0;
  38614. var indexLast = 0;
  38615. for (p = 0; p < pathArray.length; p++) {
  38616. indexFirst = idx[p] * 3;
  38617. if (p + 1 < pathArray.length) {
  38618. indexLast = (idx[p + 1] - 1) * 3;
  38619. }
  38620. else {
  38621. indexLast = normals.length - 3;
  38622. }
  38623. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38624. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38625. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38626. normals[indexLast] = normals[indexFirst];
  38627. normals[indexLast + 1] = normals[indexFirst + 1];
  38628. normals[indexLast + 2] = normals[indexFirst + 2];
  38629. }
  38630. }
  38631. // sides
  38632. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38633. // Colors
  38634. if (customColors) {
  38635. var colors = new Float32Array(customColors.length * 4);
  38636. for (var c = 0; c < customColors.length; c++) {
  38637. colors[c * 4] = customColors[c].r;
  38638. colors[c * 4 + 1] = customColors[c].g;
  38639. colors[c * 4 + 2] = customColors[c].b;
  38640. colors[c * 4 + 3] = customColors[c].a;
  38641. }
  38642. }
  38643. // Result
  38644. var vertexData = new VertexData();
  38645. var positions32 = new Float32Array(positions);
  38646. var normals32 = new Float32Array(normals);
  38647. var uvs32 = new Float32Array(uvs);
  38648. vertexData.indices = indices;
  38649. vertexData.positions = positions32;
  38650. vertexData.normals = normals32;
  38651. vertexData.uvs = uvs32;
  38652. if (customColors) {
  38653. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  38654. }
  38655. if (closePath) {
  38656. vertexData._idx = idx;
  38657. }
  38658. return vertexData;
  38659. };
  38660. /**
  38661. * Creates the VertexData of the Box.
  38662. */
  38663. VertexData.CreateBox = function (options) {
  38664. var normalsSource = [
  38665. new BABYLON.Vector3(0, 0, 1),
  38666. new BABYLON.Vector3(0, 0, -1),
  38667. new BABYLON.Vector3(1, 0, 0),
  38668. new BABYLON.Vector3(-1, 0, 0),
  38669. new BABYLON.Vector3(0, 1, 0),
  38670. new BABYLON.Vector3(0, -1, 0)
  38671. ];
  38672. var indices = [];
  38673. var positions = [];
  38674. var normals = [];
  38675. var uvs = [];
  38676. var width = options.width || options.size || 1;
  38677. var height = options.height || options.size || 1;
  38678. var depth = options.depth || options.size || 1;
  38679. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38680. var faceUV = options.faceUV || new Array(6);
  38681. var faceColors = options.faceColors;
  38682. var colors = [];
  38683. // default face colors and UV if undefined
  38684. for (var f = 0; f < 6; f++) {
  38685. if (faceUV[f] === undefined) {
  38686. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38687. }
  38688. if (faceColors && faceColors[f] === undefined) {
  38689. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38690. }
  38691. }
  38692. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  38693. // Create each face in turn.
  38694. for (var index = 0; index < normalsSource.length; index++) {
  38695. var normal = normalsSource[index];
  38696. // Get two vectors perpendicular to the face normal and to each other.
  38697. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  38698. var side2 = BABYLON.Vector3.Cross(normal, side1);
  38699. // Six indices (two triangles) per face.
  38700. var verticesLength = positions.length / 3;
  38701. indices.push(verticesLength);
  38702. indices.push(verticesLength + 1);
  38703. indices.push(verticesLength + 2);
  38704. indices.push(verticesLength);
  38705. indices.push(verticesLength + 2);
  38706. indices.push(verticesLength + 3);
  38707. // Four vertices per face.
  38708. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  38709. positions.push(vertex.x, vertex.y, vertex.z);
  38710. normals.push(normal.x, normal.y, normal.z);
  38711. uvs.push(faceUV[index].z, faceUV[index].w);
  38712. if (faceColors) {
  38713. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38714. }
  38715. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  38716. positions.push(vertex.x, vertex.y, vertex.z);
  38717. normals.push(normal.x, normal.y, normal.z);
  38718. uvs.push(faceUV[index].x, faceUV[index].w);
  38719. if (faceColors) {
  38720. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38721. }
  38722. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  38723. positions.push(vertex.x, vertex.y, vertex.z);
  38724. normals.push(normal.x, normal.y, normal.z);
  38725. uvs.push(faceUV[index].x, faceUV[index].y);
  38726. if (faceColors) {
  38727. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38728. }
  38729. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  38730. positions.push(vertex.x, vertex.y, vertex.z);
  38731. normals.push(normal.x, normal.y, normal.z);
  38732. uvs.push(faceUV[index].z, faceUV[index].y);
  38733. if (faceColors) {
  38734. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38735. }
  38736. }
  38737. // sides
  38738. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38739. // Result
  38740. var vertexData = new VertexData();
  38741. vertexData.indices = indices;
  38742. vertexData.positions = positions;
  38743. vertexData.normals = normals;
  38744. vertexData.uvs = uvs;
  38745. if (faceColors) {
  38746. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38747. vertexData.colors = totalColors;
  38748. }
  38749. return vertexData;
  38750. };
  38751. /**
  38752. * Creates the VertexData of the Sphere.
  38753. */
  38754. VertexData.CreateSphere = function (options) {
  38755. var segments = options.segments || 32;
  38756. var diameterX = options.diameterX || options.diameter || 1;
  38757. var diameterY = options.diameterY || options.diameter || 1;
  38758. var diameterZ = options.diameterZ || options.diameter || 1;
  38759. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38760. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  38761. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38762. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  38763. var totalZRotationSteps = 2 + segments;
  38764. var totalYRotationSteps = 2 * totalZRotationSteps;
  38765. var indices = [];
  38766. var positions = [];
  38767. var normals = [];
  38768. var uvs = [];
  38769. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  38770. var normalizedZ = zRotationStep / totalZRotationSteps;
  38771. var angleZ = normalizedZ * Math.PI * slice;
  38772. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  38773. var normalizedY = yRotationStep / totalYRotationSteps;
  38774. var angleY = normalizedY * Math.PI * 2 * arc;
  38775. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  38776. var rotationY = BABYLON.Matrix.RotationY(angleY);
  38777. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  38778. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  38779. var vertex = complete.multiply(radius);
  38780. var normal = complete.divide(radius).normalize();
  38781. positions.push(vertex.x, vertex.y, vertex.z);
  38782. normals.push(normal.x, normal.y, normal.z);
  38783. uvs.push(normalizedY, normalizedZ);
  38784. }
  38785. if (zRotationStep > 0) {
  38786. var verticesCount = positions.length / 3;
  38787. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  38788. indices.push((firstIndex));
  38789. indices.push((firstIndex + 1));
  38790. indices.push(firstIndex + totalYRotationSteps + 1);
  38791. indices.push((firstIndex + totalYRotationSteps + 1));
  38792. indices.push((firstIndex + 1));
  38793. indices.push((firstIndex + totalYRotationSteps + 2));
  38794. }
  38795. }
  38796. }
  38797. // Sides
  38798. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38799. // Result
  38800. var vertexData = new VertexData();
  38801. vertexData.indices = indices;
  38802. vertexData.positions = positions;
  38803. vertexData.normals = normals;
  38804. vertexData.uvs = uvs;
  38805. return vertexData;
  38806. };
  38807. /**
  38808. * Creates the VertexData of the Cylinder or Cone.
  38809. */
  38810. VertexData.CreateCylinder = function (options) {
  38811. var height = options.height || 2;
  38812. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38813. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38814. var tessellation = options.tessellation || 24;
  38815. var subdivisions = options.subdivisions || 1;
  38816. var hasRings = options.hasRings;
  38817. var enclose = options.enclose;
  38818. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38819. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38820. var faceUV = options.faceUV || new Array(3);
  38821. var faceColors = options.faceColors;
  38822. // default face colors and UV if undefined
  38823. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38824. var ringNb = (hasRings) ? subdivisions : 1;
  38825. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38826. var f;
  38827. for (f = 0; f < surfaceNb; f++) {
  38828. if (faceColors && faceColors[f] === undefined) {
  38829. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38830. }
  38831. }
  38832. for (f = 0; f < surfaceNb; f++) {
  38833. if (faceUV && faceUV[f] === undefined) {
  38834. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38835. }
  38836. }
  38837. var indices = [];
  38838. var positions = [];
  38839. var normals = [];
  38840. var uvs = [];
  38841. var colors = [];
  38842. var angle_step = Math.PI * 2 * arc / tessellation;
  38843. var angle;
  38844. var h;
  38845. var radius;
  38846. var tan = (diameterBottom - diameterTop) / 2 / height;
  38847. var ringVertex = BABYLON.Vector3.Zero();
  38848. var ringNormal = BABYLON.Vector3.Zero();
  38849. var ringFirstVertex = BABYLON.Vector3.Zero();
  38850. var ringFirstNormal = BABYLON.Vector3.Zero();
  38851. var quadNormal = BABYLON.Vector3.Zero();
  38852. var Y = BABYLON.Axis.Y;
  38853. // positions, normals, uvs
  38854. var i;
  38855. var j;
  38856. var r;
  38857. var ringIdx = 1;
  38858. var s = 1; // surface index
  38859. var cs = 0;
  38860. var v = 0;
  38861. for (i = 0; i <= subdivisions; i++) {
  38862. h = i / subdivisions;
  38863. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38864. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38865. for (r = 0; r < ringIdx; r++) {
  38866. if (hasRings) {
  38867. s += r;
  38868. }
  38869. if (enclose) {
  38870. s += 2 * r;
  38871. }
  38872. for (j = 0; j <= tessellation; j++) {
  38873. angle = j * angle_step;
  38874. // position
  38875. ringVertex.x = Math.cos(-angle) * radius;
  38876. ringVertex.y = -height / 2 + h * height;
  38877. ringVertex.z = Math.sin(-angle) * radius;
  38878. // normal
  38879. if (diameterTop === 0 && i === subdivisions) {
  38880. // if no top cap, reuse former normals
  38881. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  38882. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  38883. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  38884. }
  38885. else {
  38886. ringNormal.x = ringVertex.x;
  38887. ringNormal.z = ringVertex.z;
  38888. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  38889. ringNormal.normalize();
  38890. }
  38891. // keep first ring vertex values for enclose
  38892. if (j === 0) {
  38893. ringFirstVertex.copyFrom(ringVertex);
  38894. ringFirstNormal.copyFrom(ringNormal);
  38895. }
  38896. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38897. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  38898. if (hasRings) {
  38899. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  38900. }
  38901. else {
  38902. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  38903. }
  38904. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  38905. if (faceColors) {
  38906. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  38907. }
  38908. }
  38909. // if enclose, add four vertices and their dedicated normals
  38910. if (arc !== 1 && enclose) {
  38911. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38912. positions.push(0, ringVertex.y, 0);
  38913. positions.push(0, ringVertex.y, 0);
  38914. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  38915. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  38916. quadNormal.normalize();
  38917. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38918. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  38919. quadNormal.normalize();
  38920. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38921. if (hasRings) {
  38922. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  38923. }
  38924. else {
  38925. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  38926. }
  38927. uvs.push(faceUV[s + 1].x, v);
  38928. uvs.push(faceUV[s + 1].z, v);
  38929. if (hasRings) {
  38930. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  38931. }
  38932. else {
  38933. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  38934. }
  38935. uvs.push(faceUV[s + 2].x, v);
  38936. uvs.push(faceUV[s + 2].z, v);
  38937. if (faceColors) {
  38938. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38939. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38940. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38941. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38942. }
  38943. }
  38944. if (cs !== s) {
  38945. cs = s;
  38946. }
  38947. }
  38948. }
  38949. // indices
  38950. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  38951. var s;
  38952. i = 0;
  38953. for (s = 0; s < subdivisions; s++) {
  38954. for (j = 0; j < tessellation; j++) {
  38955. var i0 = i * (e + 1) + j;
  38956. var i1 = (i + 1) * (e + 1) + j;
  38957. var i2 = i * (e + 1) + (j + 1);
  38958. var i3 = (i + 1) * (e + 1) + (j + 1);
  38959. indices.push(i0, i1, i2);
  38960. indices.push(i3, i2, i1);
  38961. }
  38962. if (arc !== 1 && enclose) {
  38963. indices.push(i0 + 2, i1 + 2, i2 + 2);
  38964. indices.push(i3 + 2, i2 + 2, i1 + 2);
  38965. indices.push(i0 + 4, i1 + 4, i2 + 4);
  38966. indices.push(i3 + 4, i2 + 4, i1 + 4);
  38967. }
  38968. i = (hasRings) ? (i + 2) : (i + 1);
  38969. }
  38970. // Caps
  38971. var createCylinderCap = function (isTop) {
  38972. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  38973. if (radius === 0) {
  38974. return;
  38975. }
  38976. // Cap positions, normals & uvs
  38977. var angle;
  38978. var circleVector;
  38979. var i;
  38980. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  38981. var c;
  38982. if (faceColors) {
  38983. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  38984. }
  38985. // cap center
  38986. var vbase = positions.length / 3;
  38987. var offset = isTop ? height / 2 : -height / 2;
  38988. var center = new BABYLON.Vector3(0, offset, 0);
  38989. positions.push(center.x, center.y, center.z);
  38990. normals.push(0, isTop ? 1 : -1, 0);
  38991. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  38992. if (faceColors) {
  38993. colors.push(c.r, c.g, c.b, c.a);
  38994. }
  38995. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  38996. for (i = 0; i <= tessellation; i++) {
  38997. angle = Math.PI * 2 * i * arc / tessellation;
  38998. var cos = Math.cos(-angle);
  38999. var sin = Math.sin(-angle);
  39000. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  39001. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  39002. positions.push(circleVector.x, circleVector.y, circleVector.z);
  39003. normals.push(0, isTop ? 1 : -1, 0);
  39004. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  39005. if (faceColors) {
  39006. colors.push(c.r, c.g, c.b, c.a);
  39007. }
  39008. }
  39009. // Cap indices
  39010. for (i = 0; i < tessellation; i++) {
  39011. if (!isTop) {
  39012. indices.push(vbase);
  39013. indices.push(vbase + (i + 1));
  39014. indices.push(vbase + (i + 2));
  39015. }
  39016. else {
  39017. indices.push(vbase);
  39018. indices.push(vbase + (i + 2));
  39019. indices.push(vbase + (i + 1));
  39020. }
  39021. }
  39022. };
  39023. // add caps to geometry
  39024. createCylinderCap(false);
  39025. createCylinderCap(true);
  39026. // Sides
  39027. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39028. var vertexData = new VertexData();
  39029. vertexData.indices = indices;
  39030. vertexData.positions = positions;
  39031. vertexData.normals = normals;
  39032. vertexData.uvs = uvs;
  39033. if (faceColors) {
  39034. vertexData.colors = colors;
  39035. }
  39036. return vertexData;
  39037. };
  39038. /**
  39039. * Creates the VertexData of the Torus.
  39040. */
  39041. VertexData.CreateTorus = function (options) {
  39042. var indices = [];
  39043. var positions = [];
  39044. var normals = [];
  39045. var uvs = [];
  39046. var diameter = options.diameter || 1;
  39047. var thickness = options.thickness || 0.5;
  39048. var tessellation = options.tessellation || 16;
  39049. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39050. var stride = tessellation + 1;
  39051. for (var i = 0; i <= tessellation; i++) {
  39052. var u = i / tessellation;
  39053. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  39054. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  39055. for (var j = 0; j <= tessellation; j++) {
  39056. var v = 1 - j / tessellation;
  39057. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  39058. var dx = Math.cos(innerAngle);
  39059. var dy = Math.sin(innerAngle);
  39060. // Create a vertex.
  39061. var normal = new BABYLON.Vector3(dx, dy, 0);
  39062. var position = normal.scale(thickness / 2);
  39063. var textureCoordinate = new BABYLON.Vector2(u, v);
  39064. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  39065. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  39066. positions.push(position.x, position.y, position.z);
  39067. normals.push(normal.x, normal.y, normal.z);
  39068. uvs.push(textureCoordinate.x, textureCoordinate.y);
  39069. // And create indices for two triangles.
  39070. var nextI = (i + 1) % stride;
  39071. var nextJ = (j + 1) % stride;
  39072. indices.push(i * stride + j);
  39073. indices.push(i * stride + nextJ);
  39074. indices.push(nextI * stride + j);
  39075. indices.push(i * stride + nextJ);
  39076. indices.push(nextI * stride + nextJ);
  39077. indices.push(nextI * stride + j);
  39078. }
  39079. }
  39080. // Sides
  39081. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39082. // Result
  39083. var vertexData = new VertexData();
  39084. vertexData.indices = indices;
  39085. vertexData.positions = positions;
  39086. vertexData.normals = normals;
  39087. vertexData.uvs = uvs;
  39088. return vertexData;
  39089. };
  39090. /**
  39091. * Creates the VertexData of the LineSystem.
  39092. */
  39093. VertexData.CreateLineSystem = function (options) {
  39094. var indices = [];
  39095. var positions = [];
  39096. var lines = options.lines;
  39097. var idx = 0;
  39098. for (var l = 0; l < lines.length; l++) {
  39099. var points = lines[l];
  39100. for (var index = 0; index < points.length; index++) {
  39101. positions.push(points[index].x, points[index].y, points[index].z);
  39102. if (index > 0) {
  39103. indices.push(idx - 1);
  39104. indices.push(idx);
  39105. }
  39106. idx++;
  39107. }
  39108. }
  39109. var vertexData = new VertexData();
  39110. vertexData.indices = indices;
  39111. vertexData.positions = positions;
  39112. return vertexData;
  39113. };
  39114. /**
  39115. * Create the VertexData of the DashedLines.
  39116. */
  39117. VertexData.CreateDashedLines = function (options) {
  39118. var dashSize = options.dashSize || 3;
  39119. var gapSize = options.gapSize || 1;
  39120. var dashNb = options.dashNb || 200;
  39121. var points = options.points;
  39122. var positions = new Array();
  39123. var indices = new Array();
  39124. var curvect = BABYLON.Vector3.Zero();
  39125. var lg = 0;
  39126. var nb = 0;
  39127. var shft = 0;
  39128. var dashshft = 0;
  39129. var curshft = 0;
  39130. var idx = 0;
  39131. var i = 0;
  39132. for (i = 0; i < points.length - 1; i++) {
  39133. points[i + 1].subtractToRef(points[i], curvect);
  39134. lg += curvect.length();
  39135. }
  39136. shft = lg / dashNb;
  39137. dashshft = dashSize * shft / (dashSize + gapSize);
  39138. for (i = 0; i < points.length - 1; i++) {
  39139. points[i + 1].subtractToRef(points[i], curvect);
  39140. nb = Math.floor(curvect.length() / shft);
  39141. curvect.normalize();
  39142. for (var j = 0; j < nb; j++) {
  39143. curshft = shft * j;
  39144. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  39145. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  39146. indices.push(idx, idx + 1);
  39147. idx += 2;
  39148. }
  39149. }
  39150. // Result
  39151. var vertexData = new VertexData();
  39152. vertexData.positions = positions;
  39153. vertexData.indices = indices;
  39154. return vertexData;
  39155. };
  39156. /**
  39157. * Creates the VertexData of the Ground.
  39158. */
  39159. VertexData.CreateGround = function (options) {
  39160. var indices = [];
  39161. var positions = [];
  39162. var normals = [];
  39163. var uvs = [];
  39164. var row, col;
  39165. var width = options.width || 1;
  39166. var height = options.height || 1;
  39167. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39168. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39169. for (row = 0; row <= subdivisionsY; row++) {
  39170. for (col = 0; col <= subdivisionsX; col++) {
  39171. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  39172. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39173. positions.push(position.x, position.y, position.z);
  39174. normals.push(normal.x, normal.y, normal.z);
  39175. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  39176. }
  39177. }
  39178. for (row = 0; row < subdivisionsY; row++) {
  39179. for (col = 0; col < subdivisionsX; col++) {
  39180. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39181. indices.push(col + 1 + row * (subdivisionsX + 1));
  39182. indices.push(col + row * (subdivisionsX + 1));
  39183. indices.push(col + (row + 1) * (subdivisionsX + 1));
  39184. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39185. indices.push(col + row * (subdivisionsX + 1));
  39186. }
  39187. }
  39188. // Result
  39189. var vertexData = new VertexData();
  39190. vertexData.indices = indices;
  39191. vertexData.positions = positions;
  39192. vertexData.normals = normals;
  39193. vertexData.uvs = uvs;
  39194. return vertexData;
  39195. };
  39196. /**
  39197. * Creates the VertexData of the TiledGround.
  39198. */
  39199. VertexData.CreateTiledGround = function (options) {
  39200. var xmin = options.xmin || -1.0;
  39201. var zmin = options.zmin || -1.0;
  39202. var xmax = options.xmax || 1.0;
  39203. var zmax = options.zmax || 1.0;
  39204. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  39205. var precision = options.precision || { w: 1, h: 1 };
  39206. var indices = [];
  39207. var positions = [];
  39208. var normals = [];
  39209. var uvs = [];
  39210. var row, col, tileRow, tileCol;
  39211. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  39212. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  39213. precision.w = (precision.w < 1) ? 1 : precision.w;
  39214. precision.h = (precision.h < 1) ? 1 : precision.h;
  39215. var tileSize = {
  39216. 'w': (xmax - xmin) / subdivisions.w,
  39217. 'h': (zmax - zmin) / subdivisions.h
  39218. };
  39219. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  39220. // Indices
  39221. var base = positions.length / 3;
  39222. var rowLength = precision.w + 1;
  39223. for (row = 0; row < precision.h; row++) {
  39224. for (col = 0; col < precision.w; col++) {
  39225. var square = [
  39226. base + col + row * rowLength,
  39227. base + (col + 1) + row * rowLength,
  39228. base + (col + 1) + (row + 1) * rowLength,
  39229. base + col + (row + 1) * rowLength
  39230. ];
  39231. indices.push(square[1]);
  39232. indices.push(square[2]);
  39233. indices.push(square[3]);
  39234. indices.push(square[0]);
  39235. indices.push(square[1]);
  39236. indices.push(square[3]);
  39237. }
  39238. }
  39239. // Position, normals and uvs
  39240. var position = BABYLON.Vector3.Zero();
  39241. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39242. for (row = 0; row <= precision.h; row++) {
  39243. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  39244. for (col = 0; col <= precision.w; col++) {
  39245. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  39246. position.y = 0;
  39247. positions.push(position.x, position.y, position.z);
  39248. normals.push(normal.x, normal.y, normal.z);
  39249. uvs.push(col / precision.w, row / precision.h);
  39250. }
  39251. }
  39252. }
  39253. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  39254. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  39255. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  39256. }
  39257. }
  39258. // Result
  39259. var vertexData = new VertexData();
  39260. vertexData.indices = indices;
  39261. vertexData.positions = positions;
  39262. vertexData.normals = normals;
  39263. vertexData.uvs = uvs;
  39264. return vertexData;
  39265. };
  39266. /**
  39267. * Creates the VertexData of the Ground designed from a heightmap.
  39268. */
  39269. VertexData.CreateGroundFromHeightMap = function (options) {
  39270. var indices = [];
  39271. var positions = [];
  39272. var normals = [];
  39273. var uvs = [];
  39274. var row, col;
  39275. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39276. // Vertices
  39277. for (row = 0; row <= options.subdivisions; row++) {
  39278. for (col = 0; col <= options.subdivisions; col++) {
  39279. 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));
  39280. // Compute height
  39281. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  39282. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  39283. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  39284. var r = options.buffer[pos] / 255.0;
  39285. var g = options.buffer[pos + 1] / 255.0;
  39286. var b = options.buffer[pos + 2] / 255.0;
  39287. var gradient = r * filter.r + g * filter.g + b * filter.b;
  39288. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  39289. // Add vertex
  39290. positions.push(position.x, position.y, position.z);
  39291. normals.push(0, 0, 0);
  39292. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  39293. }
  39294. }
  39295. // Indices
  39296. for (row = 0; row < options.subdivisions; row++) {
  39297. for (col = 0; col < options.subdivisions; col++) {
  39298. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  39299. indices.push(col + 1 + row * (options.subdivisions + 1));
  39300. indices.push(col + row * (options.subdivisions + 1));
  39301. indices.push(col + (row + 1) * (options.subdivisions + 1));
  39302. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  39303. indices.push(col + row * (options.subdivisions + 1));
  39304. }
  39305. }
  39306. // Normals
  39307. VertexData.ComputeNormals(positions, indices, normals);
  39308. // Result
  39309. var vertexData = new VertexData();
  39310. vertexData.indices = indices;
  39311. vertexData.positions = positions;
  39312. vertexData.normals = normals;
  39313. vertexData.uvs = uvs;
  39314. return vertexData;
  39315. };
  39316. /**
  39317. * Creates the VertexData of the Plane.
  39318. */
  39319. VertexData.CreatePlane = function (options) {
  39320. var indices = [];
  39321. var positions = [];
  39322. var normals = [];
  39323. var uvs = [];
  39324. var width = options.width || options.size || 1;
  39325. var height = options.height || options.size || 1;
  39326. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39327. // Vertices
  39328. var halfWidth = width / 2.0;
  39329. var halfHeight = height / 2.0;
  39330. positions.push(-halfWidth, -halfHeight, 0);
  39331. normals.push(0, 0, -1.0);
  39332. uvs.push(0.0, 0.0);
  39333. positions.push(halfWidth, -halfHeight, 0);
  39334. normals.push(0, 0, -1.0);
  39335. uvs.push(1.0, 0.0);
  39336. positions.push(halfWidth, halfHeight, 0);
  39337. normals.push(0, 0, -1.0);
  39338. uvs.push(1.0, 1.0);
  39339. positions.push(-halfWidth, halfHeight, 0);
  39340. normals.push(0, 0, -1.0);
  39341. uvs.push(0.0, 1.0);
  39342. // Indices
  39343. indices.push(0);
  39344. indices.push(1);
  39345. indices.push(2);
  39346. indices.push(0);
  39347. indices.push(2);
  39348. indices.push(3);
  39349. // Sides
  39350. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39351. // Result
  39352. var vertexData = new VertexData();
  39353. vertexData.indices = indices;
  39354. vertexData.positions = positions;
  39355. vertexData.normals = normals;
  39356. vertexData.uvs = uvs;
  39357. return vertexData;
  39358. };
  39359. /**
  39360. * Creates the VertexData of the Disc or regular Polygon.
  39361. */
  39362. VertexData.CreateDisc = function (options) {
  39363. var positions = [];
  39364. var indices = [];
  39365. var normals = [];
  39366. var uvs = [];
  39367. var radius = options.radius || 0.5;
  39368. var tessellation = options.tessellation || 64;
  39369. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39370. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39371. // positions and uvs
  39372. positions.push(0, 0, 0); // disc center first
  39373. uvs.push(0.5, 0.5);
  39374. var theta = Math.PI * 2 * arc;
  39375. var step = theta / tessellation;
  39376. for (var a = 0; a < theta; a += step) {
  39377. var x = Math.cos(a);
  39378. var y = Math.sin(a);
  39379. var u = (x + 1) / 2;
  39380. var v = (1 - y) / 2;
  39381. positions.push(radius * x, radius * y, 0);
  39382. uvs.push(u, v);
  39383. }
  39384. if (arc === 1) {
  39385. positions.push(positions[3], positions[4], positions[5]); // close the circle
  39386. uvs.push(uvs[2], uvs[3]);
  39387. }
  39388. //indices
  39389. var vertexNb = positions.length / 3;
  39390. for (var i = 1; i < vertexNb - 1; i++) {
  39391. indices.push(i + 1, 0, i);
  39392. }
  39393. // result
  39394. VertexData.ComputeNormals(positions, indices, normals);
  39395. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39396. var vertexData = new VertexData();
  39397. vertexData.indices = indices;
  39398. vertexData.positions = positions;
  39399. vertexData.normals = normals;
  39400. vertexData.uvs = uvs;
  39401. return vertexData;
  39402. };
  39403. /**
  39404. * Creates the VertexData of the IcoSphere.
  39405. */
  39406. VertexData.CreateIcoSphere = function (options) {
  39407. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39408. var radius = options.radius || 1;
  39409. var flat = (options.flat === undefined) ? true : options.flat;
  39410. var subdivisions = options.subdivisions || 4;
  39411. var radiusX = options.radiusX || radius;
  39412. var radiusY = options.radiusY || radius;
  39413. var radiusZ = options.radiusZ || radius;
  39414. var t = (1 + Math.sqrt(5)) / 2;
  39415. // 12 vertex x,y,z
  39416. var ico_vertices = [
  39417. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  39418. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  39419. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  39420. ];
  39421. // index of 3 vertex makes a face of icopshere
  39422. var ico_indices = [
  39423. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  39424. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  39425. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  39426. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  39427. ];
  39428. // vertex for uv have aliased position, not for UV
  39429. var vertices_unalias_id = [
  39430. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  39431. // vertex alias
  39432. 0,
  39433. 2,
  39434. 3,
  39435. 3,
  39436. 3,
  39437. 4,
  39438. 7,
  39439. 8,
  39440. 9,
  39441. 9,
  39442. 10,
  39443. 11 // 23: B + 12
  39444. ];
  39445. // uv as integer step (not pixels !)
  39446. var ico_vertexuv = [
  39447. 5, 1, 3, 1, 6, 4, 0, 0,
  39448. 5, 3, 4, 2, 2, 2, 4, 0,
  39449. 2, 0, 1, 1, 6, 0, 6, 2,
  39450. // vertex alias (for same vertex on different faces)
  39451. 0, 4,
  39452. 3, 3,
  39453. 4, 4,
  39454. 3, 1,
  39455. 4, 2,
  39456. 4, 4,
  39457. 0, 2,
  39458. 1, 1,
  39459. 2, 2,
  39460. 3, 3,
  39461. 1, 3,
  39462. 2, 4 // 23: B + 12
  39463. ];
  39464. // Vertices[0, 1, ...9, A, B] : position on UV plane
  39465. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  39466. // First island of uv mapping
  39467. // v = 4h 3+ 2
  39468. // v = 3h 9+ 4
  39469. // v = 2h 9+ 5 B
  39470. // v = 1h 9 1 0
  39471. // v = 0h 3 8 7 A
  39472. // u = 0 1 2 3 4 5 6 *a
  39473. // Second island of uv mapping
  39474. // v = 4h 0+ B+ 4+
  39475. // v = 3h A+ 2+
  39476. // v = 2h 7+ 6 3+
  39477. // v = 1h 8+ 3+
  39478. // v = 0h
  39479. // u = 0 1 2 3 4 5 6 *a
  39480. // Face layout on texture UV mapping
  39481. // ============
  39482. // \ 4 /\ 16 / ======
  39483. // \ / \ / /\ 11 /
  39484. // \/ 7 \/ / \ /
  39485. // ======= / 10 \/
  39486. // /\ 17 /\ =======
  39487. // / \ / \ \ 15 /\
  39488. // / 8 \/ 12 \ \ / \
  39489. // ============ \/ 6 \
  39490. // \ 18 /\ ============
  39491. // \ / \ \ 5 /\ 0 /
  39492. // \/ 13 \ \ / \ /
  39493. // ======= \/ 1 \/
  39494. // =============
  39495. // /\ 19 /\ 2 /\
  39496. // / \ / \ / \
  39497. // / 14 \/ 9 \/ 3 \
  39498. // ===================
  39499. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  39500. var ustep = 138 / 1024;
  39501. var vstep = 239 / 1024;
  39502. var uoffset = 60 / 1024;
  39503. var voffset = 26 / 1024;
  39504. // Second island should have margin, not to touch the first island
  39505. // avoid any borderline artefact in pixel rounding
  39506. var island_u_offset = -40 / 1024;
  39507. var island_v_offset = +20 / 1024;
  39508. // face is either island 0 or 1 :
  39509. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  39510. var island = [
  39511. 0, 0, 0, 0, 1,
  39512. 0, 0, 1, 1, 0,
  39513. 0, 0, 1, 1, 0,
  39514. 0, 1, 1, 1, 0 // 15 - 19
  39515. ];
  39516. var indices = [];
  39517. var positions = [];
  39518. var normals = [];
  39519. var uvs = [];
  39520. var current_indice = 0;
  39521. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  39522. var face_vertex_pos = new Array(3);
  39523. var face_vertex_uv = new Array(3);
  39524. var v012;
  39525. for (v012 = 0; v012 < 3; v012++) {
  39526. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  39527. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  39528. }
  39529. // create all with normals
  39530. for (var face = 0; face < 20; face++) {
  39531. // 3 vertex per face
  39532. for (v012 = 0; v012 < 3; v012++) {
  39533. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  39534. var v_id = ico_indices[3 * face + v012];
  39535. // vertex have 3D position (x,y,z)
  39536. 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]);
  39537. // Normalize to get normal, then scale to radius
  39538. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  39539. // uv Coordinates from vertex ID
  39540. 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);
  39541. }
  39542. // Subdivide the face (interpolate pos, norm, uv)
  39543. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  39544. // - norm is linear interpolation of vertex corner normal
  39545. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  39546. // - uv is linear interpolation
  39547. //
  39548. // Topology is as below for sub-divide by 2
  39549. // vertex shown as v0,v1,v2
  39550. // interp index is i1 to progress in range [v0,v1[
  39551. // interp index is i2 to progress in range [v0,v2[
  39552. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  39553. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39554. //
  39555. //
  39556. // i2 v2
  39557. // ^ ^
  39558. // / / \
  39559. // / / \
  39560. // / / \
  39561. // / / (0,1) \
  39562. // / #---------\
  39563. // / / \ (0,0)'/ \
  39564. // / / \ / \
  39565. // / / \ / \
  39566. // / / (0,0) \ / (1,0) \
  39567. // / #---------#---------\
  39568. // v0 v1
  39569. //
  39570. // --------------------> i1
  39571. //
  39572. // interp of (i1,i2):
  39573. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  39574. // along i1 : lerp(x0,x1, i1/(S-i2))
  39575. //
  39576. // centroid of triangle is needed to get help normal computation
  39577. // (c1,c2) are used for centroid location
  39578. var interp_vertex = function (i1, i2, c1, c2) {
  39579. // vertex is interpolated from
  39580. // - face_vertex_pos[0..2]
  39581. // - face_vertex_uv[0..2]
  39582. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  39583. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  39584. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  39585. pos_interp.normalize();
  39586. var vertex_normal;
  39587. if (flat) {
  39588. // in flat mode, recalculate normal as face centroid normal
  39589. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  39590. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  39591. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  39592. }
  39593. else {
  39594. // in smooth mode, recalculate normal from each single vertex position
  39595. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  39596. }
  39597. // Vertex normal need correction due to X,Y,Z radius scaling
  39598. vertex_normal.x /= radiusX;
  39599. vertex_normal.y /= radiusY;
  39600. vertex_normal.z /= radiusZ;
  39601. vertex_normal.normalize();
  39602. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  39603. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  39604. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  39605. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  39606. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  39607. uvs.push(uv_interp.x, uv_interp.y);
  39608. // push each vertex has member of a face
  39609. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  39610. indices.push(current_indice);
  39611. current_indice++;
  39612. };
  39613. for (var i2 = 0; i2 < subdivisions; i2++) {
  39614. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  39615. // face : (i1,i2) for /\ :
  39616. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  39617. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39618. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39619. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39620. if (i1 + i2 + 1 < subdivisions) {
  39621. // face : (i1,i2)' for \/ :
  39622. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39623. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39624. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39625. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39626. }
  39627. }
  39628. }
  39629. }
  39630. // Sides
  39631. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39632. // Result
  39633. var vertexData = new VertexData();
  39634. vertexData.indices = indices;
  39635. vertexData.positions = positions;
  39636. vertexData.normals = normals;
  39637. vertexData.uvs = uvs;
  39638. return vertexData;
  39639. };
  39640. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39641. /**
  39642. * Creates the VertexData of the Polyhedron.
  39643. */
  39644. VertexData.CreatePolyhedron = function (options) {
  39645. // provided polyhedron types :
  39646. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39647. // 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)
  39648. var polyhedra = [];
  39649. 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]] };
  39650. 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]] };
  39651. polyhedra[2] = {
  39652. 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]],
  39653. 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]]
  39654. };
  39655. polyhedra[3] = {
  39656. 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]],
  39657. 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]]
  39658. };
  39659. polyhedra[4] = {
  39660. 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]],
  39661. 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]]
  39662. };
  39663. 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]] };
  39664. 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]] };
  39665. 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]] };
  39666. 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]] };
  39667. 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]] };
  39668. 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]] };
  39669. 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]] };
  39670. 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]] };
  39671. 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]] };
  39672. polyhedra[14] = {
  39673. 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]],
  39674. 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]]
  39675. };
  39676. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39677. var size = options.size;
  39678. var sizeX = options.sizeX || size || 1;
  39679. var sizeY = options.sizeY || size || 1;
  39680. var sizeZ = options.sizeZ || size || 1;
  39681. var data = options.custom || polyhedra[type];
  39682. var nbfaces = data.face.length;
  39683. var faceUV = options.faceUV || new Array(nbfaces);
  39684. var faceColors = options.faceColors;
  39685. var flat = (options.flat === undefined) ? true : options.flat;
  39686. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39687. var positions = [];
  39688. var indices = [];
  39689. var normals = [];
  39690. var uvs = [];
  39691. var colors = [];
  39692. var index = 0;
  39693. var faceIdx = 0; // face cursor in the array "indexes"
  39694. var indexes = [];
  39695. var i = 0;
  39696. var f = 0;
  39697. var u, v, ang, x, y, tmp;
  39698. // default face colors and UV if undefined
  39699. if (flat) {
  39700. for (f = 0; f < nbfaces; f++) {
  39701. if (faceColors && faceColors[f] === undefined) {
  39702. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39703. }
  39704. if (faceUV && faceUV[f] === undefined) {
  39705. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39706. }
  39707. }
  39708. }
  39709. if (!flat) {
  39710. for (i = 0; i < data.vertex.length; i++) {
  39711. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  39712. uvs.push(0, 0);
  39713. }
  39714. for (f = 0; f < nbfaces; f++) {
  39715. for (i = 0; i < data.face[f].length - 2; i++) {
  39716. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  39717. }
  39718. }
  39719. }
  39720. else {
  39721. for (f = 0; f < nbfaces; f++) {
  39722. var fl = data.face[f].length; // number of vertices of the current face
  39723. ang = 2 * Math.PI / fl;
  39724. x = 0.5 * Math.tan(ang / 2);
  39725. y = 0.5;
  39726. // positions, uvs, colors
  39727. for (i = 0; i < fl; i++) {
  39728. // positions
  39729. 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);
  39730. indexes.push(index);
  39731. index++;
  39732. // uvs
  39733. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  39734. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  39735. uvs.push(u, v);
  39736. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  39737. y = x * Math.sin(ang) + y * Math.cos(ang);
  39738. x = tmp;
  39739. // colors
  39740. if (faceColors) {
  39741. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  39742. }
  39743. }
  39744. // indices from indexes
  39745. for (i = 0; i < fl - 2; i++) {
  39746. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  39747. }
  39748. faceIdx += fl;
  39749. }
  39750. }
  39751. VertexData.ComputeNormals(positions, indices, normals);
  39752. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39753. var vertexData = new VertexData();
  39754. vertexData.positions = positions;
  39755. vertexData.indices = indices;
  39756. vertexData.normals = normals;
  39757. vertexData.uvs = uvs;
  39758. if (faceColors && flat) {
  39759. vertexData.colors = colors;
  39760. }
  39761. return vertexData;
  39762. };
  39763. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  39764. /**
  39765. * Creates the VertexData of the Torus Knot.
  39766. */
  39767. VertexData.CreateTorusKnot = function (options) {
  39768. var indices = [];
  39769. var positions = [];
  39770. var normals = [];
  39771. var uvs = [];
  39772. var radius = options.radius || 2;
  39773. var tube = options.tube || 0.5;
  39774. var radialSegments = options.radialSegments || 32;
  39775. var tubularSegments = options.tubularSegments || 32;
  39776. var p = options.p || 2;
  39777. var q = options.q || 3;
  39778. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39779. // Helper
  39780. var getPos = function (angle) {
  39781. var cu = Math.cos(angle);
  39782. var su = Math.sin(angle);
  39783. var quOverP = q / p * angle;
  39784. var cs = Math.cos(quOverP);
  39785. var tx = radius * (2 + cs) * 0.5 * cu;
  39786. var ty = radius * (2 + cs) * su * 0.5;
  39787. var tz = radius * Math.sin(quOverP) * 0.5;
  39788. return new BABYLON.Vector3(tx, ty, tz);
  39789. };
  39790. // Vertices
  39791. var i;
  39792. var j;
  39793. for (i = 0; i <= radialSegments; i++) {
  39794. var modI = i % radialSegments;
  39795. var u = modI / radialSegments * 2 * p * Math.PI;
  39796. var p1 = getPos(u);
  39797. var p2 = getPos(u + 0.01);
  39798. var tang = p2.subtract(p1);
  39799. var n = p2.add(p1);
  39800. var bitan = BABYLON.Vector3.Cross(tang, n);
  39801. n = BABYLON.Vector3.Cross(bitan, tang);
  39802. bitan.normalize();
  39803. n.normalize();
  39804. for (j = 0; j < tubularSegments; j++) {
  39805. var modJ = j % tubularSegments;
  39806. var v = modJ / tubularSegments * 2 * Math.PI;
  39807. var cx = -tube * Math.cos(v);
  39808. var cy = tube * Math.sin(v);
  39809. positions.push(p1.x + cx * n.x + cy * bitan.x);
  39810. positions.push(p1.y + cx * n.y + cy * bitan.y);
  39811. positions.push(p1.z + cx * n.z + cy * bitan.z);
  39812. uvs.push(i / radialSegments);
  39813. uvs.push(j / tubularSegments);
  39814. }
  39815. }
  39816. for (i = 0; i < radialSegments; i++) {
  39817. for (j = 0; j < tubularSegments; j++) {
  39818. var jNext = (j + 1) % tubularSegments;
  39819. var a = i * tubularSegments + j;
  39820. var b = (i + 1) * tubularSegments + j;
  39821. var c = (i + 1) * tubularSegments + jNext;
  39822. var d = i * tubularSegments + jNext;
  39823. indices.push(d);
  39824. indices.push(b);
  39825. indices.push(a);
  39826. indices.push(d);
  39827. indices.push(c);
  39828. indices.push(b);
  39829. }
  39830. }
  39831. // Normals
  39832. VertexData.ComputeNormals(positions, indices, normals);
  39833. // Sides
  39834. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39835. // Result
  39836. var vertexData = new VertexData();
  39837. vertexData.indices = indices;
  39838. vertexData.positions = positions;
  39839. vertexData.normals = normals;
  39840. vertexData.uvs = uvs;
  39841. return vertexData;
  39842. };
  39843. // Tools
  39844. /**
  39845. * @param {any} - positions (number[] or Float32Array)
  39846. * @param {any} - indices (number[] or Uint16Array)
  39847. * @param {any} - normals (number[] or Float32Array)
  39848. * options (optional) :
  39849. * facetPositions : optional array of facet positions (vector3)
  39850. * facetNormals : optional array of facet normals (vector3)
  39851. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  39852. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  39853. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  39854. * bbSize : optional bounding box size data, required for facetPartitioning computation
  39855. * bInfo : optional bounding info, required for facetPartitioning computation
  39856. */
  39857. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  39858. // temporary scalar variables
  39859. var index = 0; // facet index
  39860. var p1p2x = 0.0; // p1p2 vector x coordinate
  39861. var p1p2y = 0.0; // p1p2 vector y coordinate
  39862. var p1p2z = 0.0; // p1p2 vector z coordinate
  39863. var p3p2x = 0.0; // p3p2 vector x coordinate
  39864. var p3p2y = 0.0; // p3p2 vector y coordinate
  39865. var p3p2z = 0.0; // p3p2 vector z coordinate
  39866. var faceNormalx = 0.0; // facet normal x coordinate
  39867. var faceNormaly = 0.0; // facet normal y coordinate
  39868. var faceNormalz = 0.0; // facet normal z coordinate
  39869. var length = 0.0; // facet normal length before normalization
  39870. var v1x = 0; // vector1 x index in the positions array
  39871. var v1y = 0; // vector1 y index in the positions array
  39872. var v1z = 0; // vector1 z index in the positions array
  39873. var v2x = 0; // vector2 x index in the positions array
  39874. var v2y = 0; // vector2 y index in the positions array
  39875. var v2z = 0; // vector2 z index in the positions array
  39876. var v3x = 0; // vector3 x index in the positions array
  39877. var v3y = 0; // vector3 y index in the positions array
  39878. var v3z = 0; // vector3 z index in the positions array
  39879. var computeFacetNormals = false;
  39880. var computeFacetPositions = false;
  39881. var computeFacetPartitioning = false;
  39882. if (options) {
  39883. computeFacetNormals = (options.facetNormals) ? true : false;
  39884. computeFacetPositions = (options.facetPositions) ? true : false;
  39885. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  39886. }
  39887. // facetPartitioning reinit if needed
  39888. if (computeFacetPartitioning) {
  39889. var ox = 0; // X partitioning index for facet position
  39890. var oy = 0; // Y partinioning index for facet position
  39891. var oz = 0; // Z partinioning index for facet position
  39892. var b1x = 0; // X partitioning index for facet v1 vertex
  39893. var b1y = 0; // Y partitioning index for facet v1 vertex
  39894. var b1z = 0; // z partitioning index for facet v1 vertex
  39895. var b2x = 0; // X partitioning index for facet v2 vertex
  39896. var b2y = 0; // Y partitioning index for facet v2 vertex
  39897. var b2z = 0; // Z partitioning index for facet v2 vertex
  39898. var b3x = 0; // X partitioning index for facet v3 vertex
  39899. var b3y = 0; // Y partitioning index for facet v3 vertex
  39900. var b3z = 0; // Z partitioning index for facet v3 vertex
  39901. var block_idx_o = 0; // facet barycenter block index
  39902. var block_idx_v1 = 0; // v1 vertex block index
  39903. var block_idx_v2 = 0; // v2 vertex block index
  39904. var block_idx_v3 = 0; // v3 vertex block index
  39905. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  39906. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  39907. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  39908. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  39909. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  39910. var subSq = options.subDiv.max * options.subDiv.max;
  39911. options.facetPartitioning.length = 0;
  39912. }
  39913. // reset the normals
  39914. for (index = 0; index < positions.length; index++) {
  39915. normals[index] = 0.0;
  39916. }
  39917. // Loop : 1 indice triplet = 1 facet
  39918. var nbFaces = indices.length / 3;
  39919. for (index = 0; index < nbFaces; index++) {
  39920. // get the indexes of the coordinates of each vertex of the facet
  39921. v1x = indices[index * 3] * 3;
  39922. v1y = v1x + 1;
  39923. v1z = v1x + 2;
  39924. v2x = indices[index * 3 + 1] * 3;
  39925. v2y = v2x + 1;
  39926. v2z = v2x + 2;
  39927. v3x = indices[index * 3 + 2] * 3;
  39928. v3y = v3x + 1;
  39929. v3z = v3x + 2;
  39930. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  39931. p1p2y = positions[v1y] - positions[v2y];
  39932. p1p2z = positions[v1z] - positions[v2z];
  39933. p3p2x = positions[v3x] - positions[v2x];
  39934. p3p2y = positions[v3y] - positions[v2y];
  39935. p3p2z = positions[v3z] - positions[v2z];
  39936. // compute the face normal with the cross product
  39937. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  39938. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  39939. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  39940. // normalize this normal and store it in the array facetData
  39941. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39942. length = (length === 0) ? 1.0 : length;
  39943. faceNormalx /= length;
  39944. faceNormaly /= length;
  39945. faceNormalz /= length;
  39946. if (computeFacetNormals) {
  39947. options.facetNormals[index].x = faceNormalx;
  39948. options.facetNormals[index].y = faceNormaly;
  39949. options.facetNormals[index].z = faceNormalz;
  39950. }
  39951. if (computeFacetPositions) {
  39952. // compute and the facet barycenter coordinates in the array facetPositions
  39953. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  39954. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  39955. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  39956. }
  39957. if (computeFacetPartitioning) {
  39958. // store the facet indexes in arrays in the main facetPartitioning array :
  39959. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  39960. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  39961. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  39962. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  39963. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  39964. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  39965. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  39966. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  39967. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  39968. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  39969. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  39970. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  39971. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  39972. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  39973. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  39974. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  39975. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  39976. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  39977. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  39978. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  39979. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  39980. // push each facet index in each block containing the vertex
  39981. options.facetPartitioning[block_idx_v1].push(index);
  39982. if (block_idx_v2 != block_idx_v1) {
  39983. options.facetPartitioning[block_idx_v2].push(index);
  39984. }
  39985. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  39986. options.facetPartitioning[block_idx_v3].push(index);
  39987. }
  39988. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  39989. options.facetPartitioning[block_idx_o].push(index);
  39990. }
  39991. }
  39992. // compute the normals anyway
  39993. normals[v1x] += faceNormalx; // accumulate all the normals per face
  39994. normals[v1y] += faceNormaly;
  39995. normals[v1z] += faceNormalz;
  39996. normals[v2x] += faceNormalx;
  39997. normals[v2y] += faceNormaly;
  39998. normals[v2z] += faceNormalz;
  39999. normals[v3x] += faceNormalx;
  40000. normals[v3y] += faceNormaly;
  40001. normals[v3z] += faceNormalz;
  40002. }
  40003. // last normalization of each normal
  40004. for (index = 0; index < normals.length / 3; index++) {
  40005. faceNormalx = normals[index * 3];
  40006. faceNormaly = normals[index * 3 + 1];
  40007. faceNormalz = normals[index * 3 + 2];
  40008. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40009. length = (length === 0) ? 1.0 : length;
  40010. faceNormalx /= length;
  40011. faceNormaly /= length;
  40012. faceNormalz /= length;
  40013. normals[index * 3] = faceNormalx;
  40014. normals[index * 3 + 1] = faceNormaly;
  40015. normals[index * 3 + 2] = faceNormalz;
  40016. }
  40017. };
  40018. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  40019. var li = indices.length;
  40020. var ln = normals.length;
  40021. var i;
  40022. var n;
  40023. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40024. switch (sideOrientation) {
  40025. case BABYLON.Mesh.FRONTSIDE:
  40026. // nothing changed
  40027. break;
  40028. case BABYLON.Mesh.BACKSIDE:
  40029. var tmp;
  40030. // indices
  40031. for (i = 0; i < li; i += 3) {
  40032. tmp = indices[i];
  40033. indices[i] = indices[i + 2];
  40034. indices[i + 2] = tmp;
  40035. }
  40036. // normals
  40037. for (n = 0; n < ln; n++) {
  40038. normals[n] = -normals[n];
  40039. }
  40040. break;
  40041. case BABYLON.Mesh.DOUBLESIDE:
  40042. // positions
  40043. var lp = positions.length;
  40044. var l = lp / 3;
  40045. for (var p = 0; p < lp; p++) {
  40046. positions[lp + p] = positions[p];
  40047. }
  40048. // indices
  40049. for (i = 0; i < li; i += 3) {
  40050. indices[i + li] = indices[i + 2] + l;
  40051. indices[i + 1 + li] = indices[i + 1] + l;
  40052. indices[i + 2 + li] = indices[i] + l;
  40053. }
  40054. // normals
  40055. for (n = 0; n < ln; n++) {
  40056. normals[ln + n] = -normals[n];
  40057. }
  40058. // uvs
  40059. var lu = uvs.length;
  40060. for (var u = 0; u < lu; u++) {
  40061. uvs[u + lu] = uvs[u];
  40062. }
  40063. break;
  40064. }
  40065. };
  40066. /**
  40067. * Creates a new VertexData from the imported parameters.
  40068. */
  40069. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  40070. var vertexData = new VertexData();
  40071. // positions
  40072. var positions = parsedVertexData.positions;
  40073. if (positions) {
  40074. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  40075. }
  40076. // normals
  40077. var normals = parsedVertexData.normals;
  40078. if (normals) {
  40079. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  40080. }
  40081. // tangents
  40082. var tangents = parsedVertexData.tangents;
  40083. if (tangents) {
  40084. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  40085. }
  40086. // uvs
  40087. var uvs = parsedVertexData.uvs;
  40088. if (uvs) {
  40089. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  40090. }
  40091. // uv2s
  40092. var uv2s = parsedVertexData.uv2s;
  40093. if (uv2s) {
  40094. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  40095. }
  40096. // uv3s
  40097. var uv3s = parsedVertexData.uv3s;
  40098. if (uv3s) {
  40099. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  40100. }
  40101. // uv4s
  40102. var uv4s = parsedVertexData.uv4s;
  40103. if (uv4s) {
  40104. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  40105. }
  40106. // uv5s
  40107. var uv5s = parsedVertexData.uv5s;
  40108. if (uv5s) {
  40109. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  40110. }
  40111. // uv6s
  40112. var uv6s = parsedVertexData.uv6s;
  40113. if (uv6s) {
  40114. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  40115. }
  40116. // colors
  40117. var colors = parsedVertexData.colors;
  40118. if (colors) {
  40119. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  40120. }
  40121. // matricesIndices
  40122. var matricesIndices = parsedVertexData.matricesIndices;
  40123. if (matricesIndices) {
  40124. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  40125. }
  40126. // matricesWeights
  40127. var matricesWeights = parsedVertexData.matricesWeights;
  40128. if (matricesWeights) {
  40129. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  40130. }
  40131. // indices
  40132. var indices = parsedVertexData.indices;
  40133. if (indices) {
  40134. vertexData.indices = indices;
  40135. }
  40136. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  40137. };
  40138. return VertexData;
  40139. }());
  40140. BABYLON.VertexData = VertexData;
  40141. })(BABYLON || (BABYLON = {}));
  40142. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  40143. var BABYLON;
  40144. (function (BABYLON) {
  40145. var Tags = (function () {
  40146. function Tags() {
  40147. }
  40148. Tags.EnableFor = function (obj) {
  40149. obj._tags = obj._tags || {};
  40150. obj.hasTags = function () {
  40151. return Tags.HasTags(obj);
  40152. };
  40153. obj.addTags = function (tagsString) {
  40154. return Tags.AddTagsTo(obj, tagsString);
  40155. };
  40156. obj.removeTags = function (tagsString) {
  40157. return Tags.RemoveTagsFrom(obj, tagsString);
  40158. };
  40159. obj.matchesTagsQuery = function (tagsQuery) {
  40160. return Tags.MatchesQuery(obj, tagsQuery);
  40161. };
  40162. };
  40163. Tags.DisableFor = function (obj) {
  40164. delete obj._tags;
  40165. delete obj.hasTags;
  40166. delete obj.addTags;
  40167. delete obj.removeTags;
  40168. delete obj.matchesTagsQuery;
  40169. };
  40170. Tags.HasTags = function (obj) {
  40171. if (!obj._tags) {
  40172. return false;
  40173. }
  40174. return !BABYLON.Tools.IsEmpty(obj._tags);
  40175. };
  40176. Tags.GetTags = function (obj, asString) {
  40177. if (asString === void 0) { asString = true; }
  40178. if (!obj._tags) {
  40179. return null;
  40180. }
  40181. if (asString) {
  40182. var tagsArray = [];
  40183. for (var tag in obj._tags) {
  40184. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  40185. tagsArray.push(tag);
  40186. }
  40187. }
  40188. return tagsArray.join(" ");
  40189. }
  40190. else {
  40191. return obj._tags;
  40192. }
  40193. };
  40194. // the tags 'true' and 'false' are reserved and cannot be used as tags
  40195. // a tag cannot start with '||', '&&', and '!'
  40196. // it cannot contain whitespaces
  40197. Tags.AddTagsTo = function (obj, tagsString) {
  40198. if (!tagsString) {
  40199. return;
  40200. }
  40201. if (typeof tagsString !== "string") {
  40202. return;
  40203. }
  40204. var tags = tagsString.split(" ");
  40205. tags.forEach(function (tag, index, array) {
  40206. Tags._AddTagTo(obj, tag);
  40207. });
  40208. };
  40209. Tags._AddTagTo = function (obj, tag) {
  40210. tag = tag.trim();
  40211. if (tag === "" || tag === "true" || tag === "false") {
  40212. return;
  40213. }
  40214. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  40215. return;
  40216. }
  40217. Tags.EnableFor(obj);
  40218. obj._tags[tag] = true;
  40219. };
  40220. Tags.RemoveTagsFrom = function (obj, tagsString) {
  40221. if (!Tags.HasTags(obj)) {
  40222. return;
  40223. }
  40224. var tags = tagsString.split(" ");
  40225. for (var t in tags) {
  40226. Tags._RemoveTagFrom(obj, tags[t]);
  40227. }
  40228. };
  40229. Tags._RemoveTagFrom = function (obj, tag) {
  40230. delete obj._tags[tag];
  40231. };
  40232. Tags.MatchesQuery = function (obj, tagsQuery) {
  40233. if (tagsQuery === undefined) {
  40234. return true;
  40235. }
  40236. if (tagsQuery === "") {
  40237. return Tags.HasTags(obj);
  40238. }
  40239. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  40240. };
  40241. return Tags;
  40242. }());
  40243. BABYLON.Tags = Tags;
  40244. })(BABYLON || (BABYLON = {}));
  40245. //# sourceMappingURL=babylon.tags.js.map
  40246. var BABYLON;
  40247. (function (BABYLON) {
  40248. var Internals;
  40249. (function (Internals) {
  40250. var AndOrNotEvaluator = (function () {
  40251. function AndOrNotEvaluator() {
  40252. }
  40253. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  40254. if (!query.match(/\([^\(\)]*\)/g)) {
  40255. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  40256. }
  40257. else {
  40258. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  40259. // remove parenthesis
  40260. r = r.slice(1, r.length - 1);
  40261. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  40262. });
  40263. }
  40264. if (query === "true") {
  40265. return true;
  40266. }
  40267. if (query === "false") {
  40268. return false;
  40269. }
  40270. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  40271. };
  40272. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  40273. evaluateCallback = evaluateCallback || (function (r) {
  40274. return r === "true" ? true : false;
  40275. });
  40276. var result;
  40277. var or = parenthesisContent.split("||");
  40278. for (var i in or) {
  40279. if (or.hasOwnProperty(i)) {
  40280. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  40281. var and = ori.split("&&");
  40282. if (and.length > 1) {
  40283. for (var j = 0; j < and.length; ++j) {
  40284. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  40285. if (andj !== "true" && andj !== "false") {
  40286. if (andj[0] === "!") {
  40287. result = !evaluateCallback(andj.substring(1));
  40288. }
  40289. else {
  40290. result = evaluateCallback(andj);
  40291. }
  40292. }
  40293. else {
  40294. result = andj === "true" ? true : false;
  40295. }
  40296. if (!result) {
  40297. ori = "false";
  40298. break;
  40299. }
  40300. }
  40301. }
  40302. if (result || ori === "true") {
  40303. result = true;
  40304. break;
  40305. }
  40306. // result equals false (or undefined)
  40307. if (ori !== "true" && ori !== "false") {
  40308. if (ori[0] === "!") {
  40309. result = !evaluateCallback(ori.substring(1));
  40310. }
  40311. else {
  40312. result = evaluateCallback(ori);
  40313. }
  40314. }
  40315. else {
  40316. result = ori === "true" ? true : false;
  40317. }
  40318. }
  40319. }
  40320. // the whole parenthesis scope is replaced by 'true' or 'false'
  40321. return result ? "true" : "false";
  40322. };
  40323. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  40324. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  40325. // remove whitespaces
  40326. r = r.replace(/[\s]/g, function () { return ""; });
  40327. return r.length % 2 ? "!" : "";
  40328. });
  40329. booleanString = booleanString.trim();
  40330. if (booleanString === "!true") {
  40331. booleanString = "false";
  40332. }
  40333. else if (booleanString === "!false") {
  40334. booleanString = "true";
  40335. }
  40336. return booleanString;
  40337. };
  40338. return AndOrNotEvaluator;
  40339. }());
  40340. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  40341. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40342. })(BABYLON || (BABYLON = {}));
  40343. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  40344. var BABYLON;
  40345. (function (BABYLON) {
  40346. var PostProcessRenderPass = (function () {
  40347. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  40348. this._enabled = true;
  40349. this._refCount = 0;
  40350. this._name = name;
  40351. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  40352. this.setRenderList(renderList);
  40353. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  40354. this._renderTexture.onAfterRenderObservable.add(afterRender);
  40355. this._scene = scene;
  40356. this._renderList = renderList;
  40357. }
  40358. // private
  40359. PostProcessRenderPass.prototype._incRefCount = function () {
  40360. if (this._refCount === 0) {
  40361. this._scene.customRenderTargets.push(this._renderTexture);
  40362. }
  40363. return ++this._refCount;
  40364. };
  40365. PostProcessRenderPass.prototype._decRefCount = function () {
  40366. this._refCount--;
  40367. if (this._refCount <= 0) {
  40368. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  40369. }
  40370. return this._refCount;
  40371. };
  40372. PostProcessRenderPass.prototype._update = function () {
  40373. this.setRenderList(this._renderList);
  40374. };
  40375. // public
  40376. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  40377. this._renderTexture.renderList = renderList;
  40378. };
  40379. PostProcessRenderPass.prototype.getRenderTexture = function () {
  40380. return this._renderTexture;
  40381. };
  40382. return PostProcessRenderPass;
  40383. }());
  40384. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  40385. })(BABYLON || (BABYLON = {}));
  40386. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  40387. var BABYLON;
  40388. (function (BABYLON) {
  40389. var PostProcessRenderEffect = (function () {
  40390. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  40391. this._engine = engine;
  40392. this._name = name;
  40393. this._singleInstance = singleInstance || true;
  40394. this._getPostProcess = getPostProcess;
  40395. this._cameras = [];
  40396. this._indicesForCamera = [];
  40397. this._postProcesses = {};
  40398. this._renderPasses = {};
  40399. this._renderEffectAsPasses = {};
  40400. }
  40401. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  40402. get: function () {
  40403. for (var index in this._postProcesses) {
  40404. if (!this._postProcesses[index].isSupported) {
  40405. return false;
  40406. }
  40407. }
  40408. return true;
  40409. },
  40410. enumerable: true,
  40411. configurable: true
  40412. });
  40413. PostProcessRenderEffect.prototype._update = function () {
  40414. for (var renderPassName in this._renderPasses) {
  40415. this._renderPasses[renderPassName]._update();
  40416. }
  40417. };
  40418. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  40419. this._renderPasses[renderPass._name] = renderPass;
  40420. this._linkParameters();
  40421. };
  40422. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  40423. delete this._renderPasses[renderPass._name];
  40424. this._linkParameters();
  40425. };
  40426. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  40427. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  40428. this._linkParameters();
  40429. };
  40430. PostProcessRenderEffect.prototype.getPass = function (passName) {
  40431. for (var renderPassName in this._renderPasses) {
  40432. if (renderPassName === passName) {
  40433. return this._renderPasses[passName];
  40434. }
  40435. }
  40436. };
  40437. PostProcessRenderEffect.prototype.emptyPasses = function () {
  40438. this._renderPasses = {};
  40439. this._linkParameters();
  40440. };
  40441. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  40442. var cameraKey;
  40443. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40444. for (var i = 0; i < _cam.length; i++) {
  40445. var camera = _cam[i];
  40446. var cameraName = camera.name;
  40447. if (this._singleInstance) {
  40448. cameraKey = 0;
  40449. }
  40450. else {
  40451. cameraKey = cameraName;
  40452. }
  40453. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  40454. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  40455. if (!this._indicesForCamera[cameraName]) {
  40456. this._indicesForCamera[cameraName] = [];
  40457. }
  40458. this._indicesForCamera[cameraName].push(index);
  40459. if (this._cameras.indexOf(camera) === -1) {
  40460. this._cameras[cameraName] = camera;
  40461. }
  40462. for (var passName in this._renderPasses) {
  40463. this._renderPasses[passName]._incRefCount();
  40464. }
  40465. }
  40466. this._linkParameters();
  40467. };
  40468. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  40469. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40470. for (var i = 0; i < _cam.length; i++) {
  40471. var camera = _cam[i];
  40472. var cameraName = camera.name;
  40473. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  40474. var index = this._cameras.indexOf(cameraName);
  40475. this._indicesForCamera.splice(index, 1);
  40476. this._cameras.splice(index, 1);
  40477. for (var passName in this._renderPasses) {
  40478. this._renderPasses[passName]._decRefCount();
  40479. }
  40480. }
  40481. };
  40482. PostProcessRenderEffect.prototype._enable = function (cameras) {
  40483. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40484. for (var i = 0; i < _cam.length; i++) {
  40485. var camera = _cam[i];
  40486. var cameraName = camera.name;
  40487. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  40488. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  40489. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  40490. }
  40491. }
  40492. for (var passName in this._renderPasses) {
  40493. this._renderPasses[passName]._incRefCount();
  40494. }
  40495. }
  40496. };
  40497. PostProcessRenderEffect.prototype._disable = function (cameras) {
  40498. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40499. for (var i = 0; i < _cam.length; i++) {
  40500. var camera = _cam[i];
  40501. var cameraName = camera.Name;
  40502. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  40503. for (var passName in this._renderPasses) {
  40504. this._renderPasses[passName]._decRefCount();
  40505. }
  40506. }
  40507. };
  40508. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  40509. if (this._singleInstance) {
  40510. return this._postProcesses[0];
  40511. }
  40512. else {
  40513. return this._postProcesses[camera.name];
  40514. }
  40515. };
  40516. PostProcessRenderEffect.prototype._linkParameters = function () {
  40517. var _this = this;
  40518. for (var index in this._postProcesses) {
  40519. if (this.applyParameters) {
  40520. this.applyParameters(this._postProcesses[index]);
  40521. }
  40522. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  40523. _this._linkTextures(effect);
  40524. });
  40525. }
  40526. };
  40527. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  40528. for (var renderPassName in this._renderPasses) {
  40529. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  40530. }
  40531. for (var renderEffectName in this._renderEffectAsPasses) {
  40532. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  40533. }
  40534. };
  40535. return PostProcessRenderEffect;
  40536. }());
  40537. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  40538. })(BABYLON || (BABYLON = {}));
  40539. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  40540. var BABYLON;
  40541. (function (BABYLON) {
  40542. var PostProcessRenderPipeline = (function () {
  40543. function PostProcessRenderPipeline(engine, name) {
  40544. this._engine = engine;
  40545. this._name = name;
  40546. this._renderEffects = {};
  40547. this._renderEffectsForIsolatedPass = {};
  40548. this._cameras = [];
  40549. }
  40550. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  40551. get: function () {
  40552. for (var renderEffectName in this._renderEffects) {
  40553. if (!this._renderEffects[renderEffectName].isSupported) {
  40554. return false;
  40555. }
  40556. }
  40557. return true;
  40558. },
  40559. enumerable: true,
  40560. configurable: true
  40561. });
  40562. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  40563. this._renderEffects[renderEffect._name] = renderEffect;
  40564. };
  40565. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  40566. var renderEffects = this._renderEffects[renderEffectName];
  40567. if (!renderEffects) {
  40568. return;
  40569. }
  40570. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  40571. };
  40572. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  40573. var renderEffects = this._renderEffects[renderEffectName];
  40574. if (!renderEffects) {
  40575. return;
  40576. }
  40577. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  40578. };
  40579. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  40580. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40581. var indicesToDelete = [];
  40582. var i;
  40583. for (i = 0; i < _cam.length; i++) {
  40584. var camera = _cam[i];
  40585. var cameraName = camera.name;
  40586. if (this._cameras.indexOf(camera) === -1) {
  40587. this._cameras[cameraName] = camera;
  40588. }
  40589. else if (unique) {
  40590. indicesToDelete.push(i);
  40591. }
  40592. }
  40593. for (i = 0; i < indicesToDelete.length; i++) {
  40594. cameras.splice(indicesToDelete[i], 1);
  40595. }
  40596. for (var renderEffectName in this._renderEffects) {
  40597. this._renderEffects[renderEffectName]._attachCameras(_cam);
  40598. }
  40599. };
  40600. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  40601. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40602. for (var renderEffectName in this._renderEffects) {
  40603. this._renderEffects[renderEffectName]._detachCameras(_cam);
  40604. }
  40605. for (var i = 0; i < _cam.length; i++) {
  40606. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  40607. }
  40608. };
  40609. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  40610. var _this = this;
  40611. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40612. var pass = null;
  40613. var renderEffectName;
  40614. for (renderEffectName in this._renderEffects) {
  40615. pass = this._renderEffects[renderEffectName].getPass(passName);
  40616. if (pass != null) {
  40617. break;
  40618. }
  40619. }
  40620. if (pass === null) {
  40621. return;
  40622. }
  40623. for (renderEffectName in this._renderEffects) {
  40624. this._renderEffects[renderEffectName]._disable(_cam);
  40625. }
  40626. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  40627. for (var i = 0; i < _cam.length; i++) {
  40628. var camera = _cam[i];
  40629. var cameraName = camera.name;
  40630. 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); });
  40631. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  40632. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  40633. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  40634. }
  40635. };
  40636. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  40637. var _this = this;
  40638. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40639. for (var i = 0; i < _cam.length; i++) {
  40640. var camera = _cam[i];
  40641. var cameraName = camera.name;
  40642. 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); });
  40643. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  40644. }
  40645. for (var renderEffectName in this._renderEffects) {
  40646. this._renderEffects[renderEffectName]._enable(_cam);
  40647. }
  40648. };
  40649. PostProcessRenderPipeline.prototype._update = function () {
  40650. for (var renderEffectName in this._renderEffects) {
  40651. this._renderEffects[renderEffectName]._update();
  40652. }
  40653. for (var i = 0; i < this._cameras.length; i++) {
  40654. var cameraName = this._cameras[i].name;
  40655. if (this._renderEffectsForIsolatedPass[cameraName]) {
  40656. this._renderEffectsForIsolatedPass[cameraName]._update();
  40657. }
  40658. }
  40659. };
  40660. PostProcessRenderPipeline.prototype.dispose = function () {
  40661. // Must be implemented by children
  40662. };
  40663. return PostProcessRenderPipeline;
  40664. }());
  40665. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  40666. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  40667. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  40668. })(BABYLON || (BABYLON = {}));
  40669. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  40670. var BABYLON;
  40671. (function (BABYLON) {
  40672. var PostProcessRenderPipelineManager = (function () {
  40673. function PostProcessRenderPipelineManager() {
  40674. this._renderPipelines = {};
  40675. }
  40676. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  40677. this._renderPipelines[renderPipeline._name] = renderPipeline;
  40678. };
  40679. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  40680. var renderPipeline = this._renderPipelines[renderPipelineName];
  40681. if (!renderPipeline) {
  40682. return;
  40683. }
  40684. renderPipeline._attachCameras(cameras, unique);
  40685. };
  40686. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  40687. var renderPipeline = this._renderPipelines[renderPipelineName];
  40688. if (!renderPipeline) {
  40689. return;
  40690. }
  40691. renderPipeline._detachCameras(cameras);
  40692. };
  40693. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  40694. var renderPipeline = this._renderPipelines[renderPipelineName];
  40695. if (!renderPipeline) {
  40696. return;
  40697. }
  40698. renderPipeline._enableEffect(renderEffectName, cameras);
  40699. };
  40700. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  40701. var renderPipeline = this._renderPipelines[renderPipelineName];
  40702. if (!renderPipeline) {
  40703. return;
  40704. }
  40705. renderPipeline._disableEffect(renderEffectName, cameras);
  40706. };
  40707. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  40708. var renderPipeline = this._renderPipelines[renderPipelineName];
  40709. if (!renderPipeline) {
  40710. return;
  40711. }
  40712. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  40713. };
  40714. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  40715. var renderPipeline = this._renderPipelines[renderPipelineName];
  40716. if (!renderPipeline) {
  40717. return;
  40718. }
  40719. renderPipeline._disableDisplayOnlyPass(cameras);
  40720. };
  40721. PostProcessRenderPipelineManager.prototype.update = function () {
  40722. for (var renderPipelineName in this._renderPipelines) {
  40723. var pipeline = this._renderPipelines[renderPipelineName];
  40724. if (!pipeline.isSupported) {
  40725. pipeline.dispose();
  40726. delete this._renderPipelines[renderPipelineName];
  40727. }
  40728. else {
  40729. pipeline._update();
  40730. }
  40731. }
  40732. };
  40733. return PostProcessRenderPipelineManager;
  40734. }());
  40735. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  40736. })(BABYLON || (BABYLON = {}));
  40737. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  40738. var BABYLON;
  40739. (function (BABYLON) {
  40740. var BoundingBoxRenderer = (function () {
  40741. function BoundingBoxRenderer(scene) {
  40742. this.frontColor = new BABYLON.Color3(1, 1, 1);
  40743. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  40744. this.showBackLines = true;
  40745. this.renderList = new BABYLON.SmartArray(32);
  40746. this._vertexBuffers = {};
  40747. this._scene = scene;
  40748. }
  40749. BoundingBoxRenderer.prototype._prepareRessources = function () {
  40750. if (this._colorShader) {
  40751. return;
  40752. }
  40753. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  40754. attributes: [BABYLON.VertexBuffer.PositionKind],
  40755. uniforms: ["worldViewProjection", "color"]
  40756. });
  40757. var engine = this._scene.getEngine();
  40758. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  40759. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  40760. 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]);
  40761. };
  40762. BoundingBoxRenderer.prototype.reset = function () {
  40763. this.renderList.reset();
  40764. };
  40765. BoundingBoxRenderer.prototype.render = function () {
  40766. if (this.renderList.length === 0) {
  40767. return;
  40768. }
  40769. this._prepareRessources();
  40770. if (!this._colorShader.isReady()) {
  40771. return;
  40772. }
  40773. var engine = this._scene.getEngine();
  40774. engine.setDepthWrite(false);
  40775. this._colorShader._preBind();
  40776. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  40777. var boundingBox = this.renderList.data[boundingBoxIndex];
  40778. var min = boundingBox.minimum;
  40779. var max = boundingBox.maximum;
  40780. var diff = max.subtract(min);
  40781. var median = min.add(diff.scale(0.5));
  40782. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  40783. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  40784. .multiply(boundingBox.getWorldMatrix());
  40785. // VBOs
  40786. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  40787. if (this.showBackLines) {
  40788. // Back
  40789. engine.setDepthFunctionToGreaterOrEqual();
  40790. this._scene.resetCachedMaterial();
  40791. this._colorShader.setColor4("color", this.backColor.toColor4());
  40792. this._colorShader.bind(worldMatrix);
  40793. // Draw order
  40794. engine.draw(false, 0, 24);
  40795. }
  40796. // Front
  40797. engine.setDepthFunctionToLess();
  40798. this._scene.resetCachedMaterial();
  40799. this._colorShader.setColor4("color", this.frontColor.toColor4());
  40800. this._colorShader.bind(worldMatrix);
  40801. // Draw order
  40802. engine.draw(false, 0, 24);
  40803. }
  40804. this._colorShader.unbind();
  40805. engine.setDepthFunctionToLessOrEqual();
  40806. engine.setDepthWrite(true);
  40807. };
  40808. BoundingBoxRenderer.prototype.dispose = function () {
  40809. if (!this._colorShader) {
  40810. return;
  40811. }
  40812. this.renderList.dispose();
  40813. this._colorShader.dispose();
  40814. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40815. if (buffer) {
  40816. buffer.dispose();
  40817. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40818. }
  40819. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40820. };
  40821. return BoundingBoxRenderer;
  40822. }());
  40823. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  40824. })(BABYLON || (BABYLON = {}));
  40825. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  40826. var BABYLON;
  40827. (function (BABYLON) {
  40828. var Condition = (function () {
  40829. function Condition(actionManager) {
  40830. this._actionManager = actionManager;
  40831. }
  40832. Condition.prototype.isValid = function () {
  40833. return true;
  40834. };
  40835. Condition.prototype._getProperty = function (propertyPath) {
  40836. return this._actionManager._getProperty(propertyPath);
  40837. };
  40838. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  40839. return this._actionManager._getEffectiveTarget(target, propertyPath);
  40840. };
  40841. Condition.prototype.serialize = function () {
  40842. };
  40843. Condition.prototype._serialize = function (serializedCondition) {
  40844. return {
  40845. type: 2,
  40846. children: [],
  40847. name: serializedCondition.name,
  40848. properties: serializedCondition.properties
  40849. };
  40850. };
  40851. return Condition;
  40852. }());
  40853. BABYLON.Condition = Condition;
  40854. var ValueCondition = (function (_super) {
  40855. __extends(ValueCondition, _super);
  40856. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  40857. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  40858. var _this = _super.call(this, actionManager) || this;
  40859. _this.propertyPath = propertyPath;
  40860. _this.value = value;
  40861. _this.operator = operator;
  40862. _this._target = target;
  40863. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  40864. _this._property = _this._getProperty(_this.propertyPath);
  40865. return _this;
  40866. }
  40867. Object.defineProperty(ValueCondition, "IsEqual", {
  40868. get: function () {
  40869. return ValueCondition._IsEqual;
  40870. },
  40871. enumerable: true,
  40872. configurable: true
  40873. });
  40874. Object.defineProperty(ValueCondition, "IsDifferent", {
  40875. get: function () {
  40876. return ValueCondition._IsDifferent;
  40877. },
  40878. enumerable: true,
  40879. configurable: true
  40880. });
  40881. Object.defineProperty(ValueCondition, "IsGreater", {
  40882. get: function () {
  40883. return ValueCondition._IsGreater;
  40884. },
  40885. enumerable: true,
  40886. configurable: true
  40887. });
  40888. Object.defineProperty(ValueCondition, "IsLesser", {
  40889. get: function () {
  40890. return ValueCondition._IsLesser;
  40891. },
  40892. enumerable: true,
  40893. configurable: true
  40894. });
  40895. // Methods
  40896. ValueCondition.prototype.isValid = function () {
  40897. switch (this.operator) {
  40898. case ValueCondition.IsGreater:
  40899. return this._effectiveTarget[this._property] > this.value;
  40900. case ValueCondition.IsLesser:
  40901. return this._effectiveTarget[this._property] < this.value;
  40902. case ValueCondition.IsEqual:
  40903. case ValueCondition.IsDifferent:
  40904. var check;
  40905. if (this.value.equals) {
  40906. check = this.value.equals(this._effectiveTarget[this._property]);
  40907. }
  40908. else {
  40909. check = this.value === this._effectiveTarget[this._property];
  40910. }
  40911. return this.operator === ValueCondition.IsEqual ? check : !check;
  40912. }
  40913. return false;
  40914. };
  40915. ValueCondition.prototype.serialize = function () {
  40916. return this._serialize({
  40917. name: "ValueCondition",
  40918. properties: [
  40919. BABYLON.Action._GetTargetProperty(this._target),
  40920. { name: "propertyPath", value: this.propertyPath },
  40921. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  40922. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  40923. ]
  40924. });
  40925. };
  40926. ValueCondition.GetOperatorName = function (operator) {
  40927. switch (operator) {
  40928. case ValueCondition._IsEqual: return "IsEqual";
  40929. case ValueCondition._IsDifferent: return "IsDifferent";
  40930. case ValueCondition._IsGreater: return "IsGreater";
  40931. case ValueCondition._IsLesser: return "IsLesser";
  40932. default: return "";
  40933. }
  40934. };
  40935. return ValueCondition;
  40936. }(Condition));
  40937. // Statics
  40938. ValueCondition._IsEqual = 0;
  40939. ValueCondition._IsDifferent = 1;
  40940. ValueCondition._IsGreater = 2;
  40941. ValueCondition._IsLesser = 3;
  40942. BABYLON.ValueCondition = ValueCondition;
  40943. var PredicateCondition = (function (_super) {
  40944. __extends(PredicateCondition, _super);
  40945. function PredicateCondition(actionManager, predicate) {
  40946. var _this = _super.call(this, actionManager) || this;
  40947. _this.predicate = predicate;
  40948. return _this;
  40949. }
  40950. PredicateCondition.prototype.isValid = function () {
  40951. return this.predicate();
  40952. };
  40953. return PredicateCondition;
  40954. }(Condition));
  40955. BABYLON.PredicateCondition = PredicateCondition;
  40956. var StateCondition = (function (_super) {
  40957. __extends(StateCondition, _super);
  40958. function StateCondition(actionManager, target, value) {
  40959. var _this = _super.call(this, actionManager) || this;
  40960. _this.value = value;
  40961. _this._target = target;
  40962. return _this;
  40963. }
  40964. // Methods
  40965. StateCondition.prototype.isValid = function () {
  40966. return this._target.state === this.value;
  40967. };
  40968. StateCondition.prototype.serialize = function () {
  40969. return this._serialize({
  40970. name: "StateCondition",
  40971. properties: [
  40972. BABYLON.Action._GetTargetProperty(this._target),
  40973. { name: "value", value: this.value }
  40974. ]
  40975. });
  40976. };
  40977. return StateCondition;
  40978. }(Condition));
  40979. BABYLON.StateCondition = StateCondition;
  40980. })(BABYLON || (BABYLON = {}));
  40981. //# sourceMappingURL=babylon.condition.js.map
  40982. var BABYLON;
  40983. (function (BABYLON) {
  40984. var Action = (function () {
  40985. function Action(triggerOptions, condition) {
  40986. this.triggerOptions = triggerOptions;
  40987. if (triggerOptions.parameter) {
  40988. this.trigger = triggerOptions.trigger;
  40989. this._triggerParameter = triggerOptions.parameter;
  40990. }
  40991. else {
  40992. this.trigger = triggerOptions;
  40993. }
  40994. this._nextActiveAction = this;
  40995. this._condition = condition;
  40996. }
  40997. // Methods
  40998. Action.prototype._prepare = function () {
  40999. };
  41000. Action.prototype.getTriggerParameter = function () {
  41001. return this._triggerParameter;
  41002. };
  41003. Action.prototype._executeCurrent = function (evt) {
  41004. if (this._nextActiveAction._condition) {
  41005. var condition = this._nextActiveAction._condition;
  41006. var currentRenderId = this._actionManager.getScene().getRenderId();
  41007. // We cache the current evaluation for the current frame
  41008. if (condition._evaluationId === currentRenderId) {
  41009. if (!condition._currentResult) {
  41010. return;
  41011. }
  41012. }
  41013. else {
  41014. condition._evaluationId = currentRenderId;
  41015. if (!condition.isValid()) {
  41016. condition._currentResult = false;
  41017. return;
  41018. }
  41019. condition._currentResult = true;
  41020. }
  41021. }
  41022. this._nextActiveAction.execute(evt);
  41023. this.skipToNextActiveAction();
  41024. };
  41025. Action.prototype.execute = function (evt) {
  41026. };
  41027. Action.prototype.skipToNextActiveAction = function () {
  41028. if (this._nextActiveAction._child) {
  41029. if (!this._nextActiveAction._child._actionManager) {
  41030. this._nextActiveAction._child._actionManager = this._actionManager;
  41031. }
  41032. this._nextActiveAction = this._nextActiveAction._child;
  41033. }
  41034. else {
  41035. this._nextActiveAction = this;
  41036. }
  41037. };
  41038. Action.prototype.then = function (action) {
  41039. this._child = action;
  41040. action._actionManager = this._actionManager;
  41041. action._prepare();
  41042. return action;
  41043. };
  41044. Action.prototype._getProperty = function (propertyPath) {
  41045. return this._actionManager._getProperty(propertyPath);
  41046. };
  41047. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  41048. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41049. };
  41050. Action.prototype.serialize = function (parent) {
  41051. };
  41052. // Called by BABYLON.Action objects in serialize(...). Internal use
  41053. Action.prototype._serialize = function (serializedAction, parent) {
  41054. var serializationObject = {
  41055. type: 1,
  41056. children: [],
  41057. name: serializedAction.name,
  41058. properties: serializedAction.properties || []
  41059. };
  41060. // Serialize child
  41061. if (this._child) {
  41062. this._child.serialize(serializationObject);
  41063. }
  41064. // Check if "this" has a condition
  41065. if (this._condition) {
  41066. var serializedCondition = this._condition.serialize();
  41067. serializedCondition.children.push(serializationObject);
  41068. if (parent) {
  41069. parent.children.push(serializedCondition);
  41070. }
  41071. return serializedCondition;
  41072. }
  41073. if (parent) {
  41074. parent.children.push(serializationObject);
  41075. }
  41076. return serializationObject;
  41077. };
  41078. return Action;
  41079. }());
  41080. Action._SerializeValueAsString = function (value) {
  41081. if (typeof value === "number") {
  41082. return value.toString();
  41083. }
  41084. if (typeof value === "boolean") {
  41085. return value ? "true" : "false";
  41086. }
  41087. if (value instanceof BABYLON.Vector2) {
  41088. return value.x + ", " + value.y;
  41089. }
  41090. if (value instanceof BABYLON.Vector3) {
  41091. return value.x + ", " + value.y + ", " + value.z;
  41092. }
  41093. if (value instanceof BABYLON.Color3) {
  41094. return value.r + ", " + value.g + ", " + value.b;
  41095. }
  41096. if (value instanceof BABYLON.Color4) {
  41097. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  41098. }
  41099. return value; // string
  41100. };
  41101. Action._GetTargetProperty = function (target) {
  41102. return {
  41103. name: "target",
  41104. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  41105. : target instanceof BABYLON.Light ? "LightProperties"
  41106. : target instanceof BABYLON.Camera ? "CameraProperties"
  41107. : "SceneProperties",
  41108. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  41109. };
  41110. };
  41111. BABYLON.Action = Action;
  41112. })(BABYLON || (BABYLON = {}));
  41113. //# sourceMappingURL=babylon.action.js.map
  41114. var BABYLON;
  41115. (function (BABYLON) {
  41116. /**
  41117. * ActionEvent is the event beint sent when an action is triggered.
  41118. */
  41119. var ActionEvent = (function () {
  41120. /**
  41121. * @constructor
  41122. * @param source The mesh or sprite that triggered the action.
  41123. * @param pointerX The X mouse cursor position at the time of the event
  41124. * @param pointerY The Y mouse cursor position at the time of the event
  41125. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  41126. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  41127. */
  41128. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  41129. this.source = source;
  41130. this.pointerX = pointerX;
  41131. this.pointerY = pointerY;
  41132. this.meshUnderPointer = meshUnderPointer;
  41133. this.sourceEvent = sourceEvent;
  41134. this.additionalData = additionalData;
  41135. }
  41136. /**
  41137. * Helper function to auto-create an ActionEvent from a source mesh.
  41138. * @param source The source mesh that triggered the event
  41139. * @param evt {Event} The original (browser) event
  41140. */
  41141. ActionEvent.CreateNew = function (source, evt, additionalData) {
  41142. var scene = source.getScene();
  41143. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41144. };
  41145. /**
  41146. * Helper function to auto-create an ActionEvent from a source mesh.
  41147. * @param source The source sprite that triggered the event
  41148. * @param scene Scene associated with the sprite
  41149. * @param evt {Event} The original (browser) event
  41150. */
  41151. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  41152. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41153. };
  41154. /**
  41155. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  41156. * @param scene the scene where the event occurred
  41157. * @param evt {Event} The original (browser) event
  41158. */
  41159. ActionEvent.CreateNewFromScene = function (scene, evt) {
  41160. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  41161. };
  41162. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  41163. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  41164. };
  41165. return ActionEvent;
  41166. }());
  41167. BABYLON.ActionEvent = ActionEvent;
  41168. /**
  41169. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  41170. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  41171. */
  41172. var ActionManager = (function () {
  41173. function ActionManager(scene) {
  41174. // Members
  41175. this.actions = new Array();
  41176. this.hoverCursor = '';
  41177. this._scene = scene;
  41178. scene._actionManagers.push(this);
  41179. }
  41180. Object.defineProperty(ActionManager, "NothingTrigger", {
  41181. get: function () {
  41182. return ActionManager._NothingTrigger;
  41183. },
  41184. enumerable: true,
  41185. configurable: true
  41186. });
  41187. Object.defineProperty(ActionManager, "OnPickTrigger", {
  41188. get: function () {
  41189. return ActionManager._OnPickTrigger;
  41190. },
  41191. enumerable: true,
  41192. configurable: true
  41193. });
  41194. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  41195. get: function () {
  41196. return ActionManager._OnLeftPickTrigger;
  41197. },
  41198. enumerable: true,
  41199. configurable: true
  41200. });
  41201. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  41202. get: function () {
  41203. return ActionManager._OnRightPickTrigger;
  41204. },
  41205. enumerable: true,
  41206. configurable: true
  41207. });
  41208. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  41209. get: function () {
  41210. return ActionManager._OnCenterPickTrigger;
  41211. },
  41212. enumerable: true,
  41213. configurable: true
  41214. });
  41215. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  41216. get: function () {
  41217. return ActionManager._OnPickDownTrigger;
  41218. },
  41219. enumerable: true,
  41220. configurable: true
  41221. });
  41222. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  41223. get: function () {
  41224. return ActionManager._OnDoublePickTrigger;
  41225. },
  41226. enumerable: true,
  41227. configurable: true
  41228. });
  41229. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  41230. get: function () {
  41231. return ActionManager._OnPickUpTrigger;
  41232. },
  41233. enumerable: true,
  41234. configurable: true
  41235. });
  41236. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  41237. /// This trigger will only be raised if you also declared a OnPickDown
  41238. get: function () {
  41239. return ActionManager._OnPickOutTrigger;
  41240. },
  41241. enumerable: true,
  41242. configurable: true
  41243. });
  41244. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  41245. get: function () {
  41246. return ActionManager._OnLongPressTrigger;
  41247. },
  41248. enumerable: true,
  41249. configurable: true
  41250. });
  41251. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  41252. get: function () {
  41253. return ActionManager._OnPointerOverTrigger;
  41254. },
  41255. enumerable: true,
  41256. configurable: true
  41257. });
  41258. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  41259. get: function () {
  41260. return ActionManager._OnPointerOutTrigger;
  41261. },
  41262. enumerable: true,
  41263. configurable: true
  41264. });
  41265. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  41266. get: function () {
  41267. return ActionManager._OnEveryFrameTrigger;
  41268. },
  41269. enumerable: true,
  41270. configurable: true
  41271. });
  41272. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  41273. get: function () {
  41274. return ActionManager._OnIntersectionEnterTrigger;
  41275. },
  41276. enumerable: true,
  41277. configurable: true
  41278. });
  41279. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  41280. get: function () {
  41281. return ActionManager._OnIntersectionExitTrigger;
  41282. },
  41283. enumerable: true,
  41284. configurable: true
  41285. });
  41286. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  41287. get: function () {
  41288. return ActionManager._OnKeyDownTrigger;
  41289. },
  41290. enumerable: true,
  41291. configurable: true
  41292. });
  41293. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  41294. get: function () {
  41295. return ActionManager._OnKeyUpTrigger;
  41296. },
  41297. enumerable: true,
  41298. configurable: true
  41299. });
  41300. // Methods
  41301. ActionManager.prototype.dispose = function () {
  41302. var index = this._scene._actionManagers.indexOf(this);
  41303. for (var i = 0; i < this.actions.length; i++) {
  41304. var action = this.actions[i];
  41305. ActionManager.Triggers[action.trigger]--;
  41306. if (ActionManager.Triggers[action.trigger] === 0) {
  41307. delete ActionManager.Triggers[action.trigger];
  41308. }
  41309. }
  41310. if (index > -1) {
  41311. this._scene._actionManagers.splice(index, 1);
  41312. }
  41313. };
  41314. ActionManager.prototype.getScene = function () {
  41315. return this._scene;
  41316. };
  41317. /**
  41318. * Does this action manager handles actions of any of the given triggers
  41319. * @param {number[]} triggers - the triggers to be tested
  41320. * @return {boolean} whether one (or more) of the triggers is handeled
  41321. */
  41322. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  41323. for (var index = 0; index < this.actions.length; index++) {
  41324. var action = this.actions[index];
  41325. if (triggers.indexOf(action.trigger) > -1) {
  41326. return true;
  41327. }
  41328. }
  41329. return false;
  41330. };
  41331. /**
  41332. * Does this action manager handles actions of a given trigger
  41333. * @param {number} trigger - the trigger to be tested
  41334. * @return {boolean} whether the trigger is handeled
  41335. */
  41336. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  41337. for (var index = 0; index < this.actions.length; index++) {
  41338. var action = this.actions[index];
  41339. if (action.trigger === trigger) {
  41340. return true;
  41341. }
  41342. }
  41343. return false;
  41344. };
  41345. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  41346. /**
  41347. * Does this action manager has pointer triggers
  41348. * @return {boolean} whether or not it has pointer triggers
  41349. */
  41350. get: function () {
  41351. for (var index = 0; index < this.actions.length; index++) {
  41352. var action = this.actions[index];
  41353. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  41354. return true;
  41355. }
  41356. }
  41357. return false;
  41358. },
  41359. enumerable: true,
  41360. configurable: true
  41361. });
  41362. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  41363. /**
  41364. * Does this action manager has pick triggers
  41365. * @return {boolean} whether or not it has pick triggers
  41366. */
  41367. get: function () {
  41368. for (var index = 0; index < this.actions.length; index++) {
  41369. var action = this.actions[index];
  41370. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  41371. return true;
  41372. }
  41373. }
  41374. return false;
  41375. },
  41376. enumerable: true,
  41377. configurable: true
  41378. });
  41379. Object.defineProperty(ActionManager, "HasTriggers", {
  41380. /**
  41381. * Does exist one action manager with at least one trigger
  41382. * @return {boolean} whether or not it exists one action manager with one trigger
  41383. **/
  41384. get: function () {
  41385. for (var t in ActionManager.Triggers) {
  41386. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41387. return true;
  41388. }
  41389. }
  41390. return false;
  41391. },
  41392. enumerable: true,
  41393. configurable: true
  41394. });
  41395. Object.defineProperty(ActionManager, "HasPickTriggers", {
  41396. /**
  41397. * Does exist one action manager with at least one pick trigger
  41398. * @return {boolean} whether or not it exists one action manager with one pick trigger
  41399. **/
  41400. get: function () {
  41401. for (var t in ActionManager.Triggers) {
  41402. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41403. var t_int = parseInt(t);
  41404. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  41405. return true;
  41406. }
  41407. }
  41408. }
  41409. return false;
  41410. },
  41411. enumerable: true,
  41412. configurable: true
  41413. });
  41414. /**
  41415. * Does exist one action manager that handles actions of a given trigger
  41416. * @param {number} trigger - the trigger to be tested
  41417. * @return {boolean} whether the trigger is handeled by at least one action manager
  41418. **/
  41419. ActionManager.HasSpecificTrigger = function (trigger) {
  41420. for (var t in ActionManager.Triggers) {
  41421. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41422. var t_int = parseInt(t);
  41423. if (t_int === trigger) {
  41424. return true;
  41425. }
  41426. }
  41427. }
  41428. return false;
  41429. };
  41430. /**
  41431. * Registers an action to this action manager
  41432. * @param {BABYLON.Action} action - the action to be registered
  41433. * @return {BABYLON.Action} the action amended (prepared) after registration
  41434. */
  41435. ActionManager.prototype.registerAction = function (action) {
  41436. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  41437. if (this.getScene().actionManager !== this) {
  41438. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  41439. return null;
  41440. }
  41441. }
  41442. this.actions.push(action);
  41443. if (ActionManager.Triggers[action.trigger]) {
  41444. ActionManager.Triggers[action.trigger]++;
  41445. }
  41446. else {
  41447. ActionManager.Triggers[action.trigger] = 1;
  41448. }
  41449. action._actionManager = this;
  41450. action._prepare();
  41451. return action;
  41452. };
  41453. /**
  41454. * Process a specific trigger
  41455. * @param {number} trigger - the trigger to process
  41456. * @param evt {BABYLON.ActionEvent} the event details to be processed
  41457. */
  41458. ActionManager.prototype.processTrigger = function (trigger, evt) {
  41459. for (var index = 0; index < this.actions.length; index++) {
  41460. var action = this.actions[index];
  41461. if (action.trigger === trigger) {
  41462. if (trigger === ActionManager.OnKeyUpTrigger
  41463. || trigger === ActionManager.OnKeyDownTrigger) {
  41464. var parameter = action.getTriggerParameter();
  41465. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  41466. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  41467. var actualkey = String.fromCharCode(unicode).toLowerCase();
  41468. if (actualkey !== parameter.toLowerCase()) {
  41469. continue;
  41470. }
  41471. }
  41472. }
  41473. action._executeCurrent(evt);
  41474. }
  41475. }
  41476. };
  41477. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  41478. var properties = propertyPath.split(".");
  41479. for (var index = 0; index < properties.length - 1; index++) {
  41480. target = target[properties[index]];
  41481. }
  41482. return target;
  41483. };
  41484. ActionManager.prototype._getProperty = function (propertyPath) {
  41485. var properties = propertyPath.split(".");
  41486. return properties[properties.length - 1];
  41487. };
  41488. ActionManager.prototype.serialize = function (name) {
  41489. var root = {
  41490. children: [],
  41491. name: name,
  41492. type: 3,
  41493. properties: [] // Empty for root but required
  41494. };
  41495. for (var i = 0; i < this.actions.length; i++) {
  41496. var triggerObject = {
  41497. type: 0,
  41498. children: [],
  41499. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  41500. properties: []
  41501. };
  41502. var triggerOptions = this.actions[i].triggerOptions;
  41503. if (triggerOptions && typeof triggerOptions !== "number") {
  41504. if (triggerOptions.parameter instanceof BABYLON.Node) {
  41505. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  41506. }
  41507. else {
  41508. var parameter = {};
  41509. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  41510. if (triggerOptions.parameter.mesh) {
  41511. parameter._meshId = triggerOptions.parameter.mesh.id;
  41512. }
  41513. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  41514. }
  41515. }
  41516. // Serialize child action, recursively
  41517. this.actions[i].serialize(triggerObject);
  41518. // Add serialized trigger
  41519. root.children.push(triggerObject);
  41520. }
  41521. return root;
  41522. };
  41523. ActionManager.Parse = function (parsedActions, object, scene) {
  41524. var actionManager = new BABYLON.ActionManager(scene);
  41525. if (object === null)
  41526. scene.actionManager = actionManager;
  41527. else
  41528. object.actionManager = actionManager;
  41529. // instanciate a new object
  41530. var instanciate = function (name, params) {
  41531. var newInstance = Object.create(BABYLON[name].prototype);
  41532. newInstance.constructor.apply(newInstance, params);
  41533. return newInstance;
  41534. };
  41535. var parseParameter = function (name, value, target, propertyPath) {
  41536. if (propertyPath === null) {
  41537. // String, boolean or float
  41538. var floatValue = parseFloat(value);
  41539. if (value === "true" || value === "false")
  41540. return value === "true";
  41541. else
  41542. return isNaN(floatValue) ? value : floatValue;
  41543. }
  41544. var effectiveTarget = propertyPath.split(".");
  41545. var values = value.split(",");
  41546. // Get effective Target
  41547. for (var i = 0; i < effectiveTarget.length; i++) {
  41548. target = target[effectiveTarget[i]];
  41549. }
  41550. // Return appropriate value with its type
  41551. if (typeof (target) === "boolean")
  41552. return values[0] === "true";
  41553. if (typeof (target) === "string")
  41554. return values[0];
  41555. // Parameters with multiple values such as Vector3 etc.
  41556. var split = new Array();
  41557. for (var i = 0; i < values.length; i++)
  41558. split.push(parseFloat(values[i]));
  41559. if (target instanceof BABYLON.Vector3)
  41560. return BABYLON.Vector3.FromArray(split);
  41561. if (target instanceof BABYLON.Vector4)
  41562. return BABYLON.Vector4.FromArray(split);
  41563. if (target instanceof BABYLON.Color3)
  41564. return BABYLON.Color3.FromArray(split);
  41565. if (target instanceof BABYLON.Color4)
  41566. return BABYLON.Color4.FromArray(split);
  41567. return parseFloat(values[0]);
  41568. };
  41569. // traverse graph per trigger
  41570. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  41571. if (combineArray === void 0) { combineArray = null; }
  41572. if (parsedAction.detached)
  41573. return;
  41574. var parameters = new Array();
  41575. var target = null;
  41576. var propertyPath = null;
  41577. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  41578. // Parameters
  41579. if (parsedAction.type === 2)
  41580. parameters.push(actionManager);
  41581. else
  41582. parameters.push(trigger);
  41583. if (combine) {
  41584. var actions = new Array();
  41585. for (var j = 0; j < parsedAction.combine.length; j++) {
  41586. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  41587. }
  41588. parameters.push(actions);
  41589. }
  41590. else {
  41591. for (var i = 0; i < parsedAction.properties.length; i++) {
  41592. var value = parsedAction.properties[i].value;
  41593. var name = parsedAction.properties[i].name;
  41594. var targetType = parsedAction.properties[i].targetType;
  41595. if (name === "target")
  41596. if (targetType !== null && targetType === "SceneProperties")
  41597. value = target = scene;
  41598. else
  41599. value = target = scene.getNodeByName(value);
  41600. else if (name === "parent")
  41601. value = scene.getNodeByName(value);
  41602. else if (name === "sound")
  41603. value = scene.getSoundByName(value);
  41604. else if (name !== "propertyPath") {
  41605. if (parsedAction.type === 2 && name === "operator")
  41606. value = BABYLON.ValueCondition[value];
  41607. else
  41608. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  41609. }
  41610. else {
  41611. propertyPath = value;
  41612. }
  41613. parameters.push(value);
  41614. }
  41615. }
  41616. if (combineArray === null) {
  41617. parameters.push(condition);
  41618. }
  41619. else {
  41620. parameters.push(null);
  41621. }
  41622. // If interpolate value action
  41623. if (parsedAction.name === "InterpolateValueAction") {
  41624. var param = parameters[parameters.length - 2];
  41625. parameters[parameters.length - 1] = param;
  41626. parameters[parameters.length - 2] = condition;
  41627. }
  41628. // Action or condition(s) and not CombineAction
  41629. var newAction = instanciate(parsedAction.name, parameters);
  41630. if (newAction instanceof BABYLON.Condition && condition !== null) {
  41631. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  41632. if (action)
  41633. action.then(nothing);
  41634. else
  41635. actionManager.registerAction(nothing);
  41636. action = nothing;
  41637. }
  41638. if (combineArray === null) {
  41639. if (newAction instanceof BABYLON.Condition) {
  41640. condition = newAction;
  41641. newAction = action;
  41642. }
  41643. else {
  41644. condition = null;
  41645. if (action)
  41646. action.then(newAction);
  41647. else
  41648. actionManager.registerAction(newAction);
  41649. }
  41650. }
  41651. else {
  41652. combineArray.push(newAction);
  41653. }
  41654. for (var i = 0; i < parsedAction.children.length; i++)
  41655. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  41656. };
  41657. // triggers
  41658. for (var i = 0; i < parsedActions.children.length; i++) {
  41659. var triggerParams;
  41660. var trigger = parsedActions.children[i];
  41661. if (trigger.properties.length > 0) {
  41662. var param = trigger.properties[0].value;
  41663. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  41664. if (value._meshId) {
  41665. value.mesh = scene.getMeshByID(value._meshId);
  41666. }
  41667. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  41668. }
  41669. else
  41670. triggerParams = BABYLON.ActionManager[trigger.name];
  41671. for (var j = 0; j < trigger.children.length; j++) {
  41672. if (!trigger.detached)
  41673. traverse(trigger.children[j], triggerParams, null, null);
  41674. }
  41675. }
  41676. };
  41677. ActionManager.GetTriggerName = function (trigger) {
  41678. switch (trigger) {
  41679. case 0: return "NothingTrigger";
  41680. case 1: return "OnPickTrigger";
  41681. case 2: return "OnLeftPickTrigger";
  41682. case 3: return "OnRightPickTrigger";
  41683. case 4: return "OnCenterPickTrigger";
  41684. case 5: return "OnPickDownTrigger";
  41685. case 6: return "OnPickUpTrigger";
  41686. case 7: return "OnLongPressTrigger";
  41687. case 8: return "OnPointerOverTrigger";
  41688. case 9: return "OnPointerOutTrigger";
  41689. case 10: return "OnEveryFrameTrigger";
  41690. case 11: return "OnIntersectionEnterTrigger";
  41691. case 12: return "OnIntersectionExitTrigger";
  41692. case 13: return "OnKeyDownTrigger";
  41693. case 14: return "OnKeyUpTrigger";
  41694. case 15: return "OnPickOutTrigger";
  41695. default: return "";
  41696. }
  41697. };
  41698. return ActionManager;
  41699. }());
  41700. // Statics
  41701. ActionManager._NothingTrigger = 0;
  41702. ActionManager._OnPickTrigger = 1;
  41703. ActionManager._OnLeftPickTrigger = 2;
  41704. ActionManager._OnRightPickTrigger = 3;
  41705. ActionManager._OnCenterPickTrigger = 4;
  41706. ActionManager._OnPickDownTrigger = 5;
  41707. ActionManager._OnDoublePickTrigger = 6;
  41708. ActionManager._OnPickUpTrigger = 7;
  41709. ActionManager._OnLongPressTrigger = 8;
  41710. ActionManager._OnPointerOverTrigger = 9;
  41711. ActionManager._OnPointerOutTrigger = 10;
  41712. ActionManager._OnEveryFrameTrigger = 11;
  41713. ActionManager._OnIntersectionEnterTrigger = 12;
  41714. ActionManager._OnIntersectionExitTrigger = 13;
  41715. ActionManager._OnKeyDownTrigger = 14;
  41716. ActionManager._OnKeyUpTrigger = 15;
  41717. ActionManager._OnPickOutTrigger = 16;
  41718. ActionManager.Triggers = {};
  41719. BABYLON.ActionManager = ActionManager;
  41720. })(BABYLON || (BABYLON = {}));
  41721. //# sourceMappingURL=babylon.actionManager.js.map
  41722. var BABYLON;
  41723. (function (BABYLON) {
  41724. var InterpolateValueAction = (function (_super) {
  41725. __extends(InterpolateValueAction, _super);
  41726. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  41727. if (duration === void 0) { duration = 1000; }
  41728. var _this = _super.call(this, triggerOptions, condition) || this;
  41729. _this.propertyPath = propertyPath;
  41730. _this.value = value;
  41731. _this.duration = duration;
  41732. _this.stopOtherAnimations = stopOtherAnimations;
  41733. _this.onInterpolationDone = onInterpolationDone;
  41734. _this._target = _this._effectiveTarget = target;
  41735. return _this;
  41736. }
  41737. InterpolateValueAction.prototype._prepare = function () {
  41738. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41739. this._property = this._getProperty(this.propertyPath);
  41740. };
  41741. InterpolateValueAction.prototype.execute = function () {
  41742. var scene = this._actionManager.getScene();
  41743. var keys = [
  41744. {
  41745. frame: 0,
  41746. value: this._effectiveTarget[this._property]
  41747. }, {
  41748. frame: 100,
  41749. value: this.value
  41750. }
  41751. ];
  41752. var dataType;
  41753. if (typeof this.value === "number") {
  41754. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  41755. }
  41756. else if (this.value instanceof BABYLON.Color3) {
  41757. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  41758. }
  41759. else if (this.value instanceof BABYLON.Vector3) {
  41760. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  41761. }
  41762. else if (this.value instanceof BABYLON.Matrix) {
  41763. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  41764. }
  41765. else if (this.value instanceof BABYLON.Quaternion) {
  41766. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  41767. }
  41768. else {
  41769. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  41770. return;
  41771. }
  41772. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  41773. animation.setKeys(keys);
  41774. if (this.stopOtherAnimations) {
  41775. scene.stopAnimation(this._effectiveTarget);
  41776. }
  41777. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  41778. };
  41779. InterpolateValueAction.prototype.serialize = function (parent) {
  41780. return _super.prototype._serialize.call(this, {
  41781. name: "InterpolateValueAction",
  41782. properties: [
  41783. BABYLON.Action._GetTargetProperty(this._target),
  41784. { name: "propertyPath", value: this.propertyPath },
  41785. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41786. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  41787. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  41788. ]
  41789. }, parent);
  41790. };
  41791. return InterpolateValueAction;
  41792. }(BABYLON.Action));
  41793. BABYLON.InterpolateValueAction = InterpolateValueAction;
  41794. })(BABYLON || (BABYLON = {}));
  41795. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  41796. var BABYLON;
  41797. (function (BABYLON) {
  41798. var SwitchBooleanAction = (function (_super) {
  41799. __extends(SwitchBooleanAction, _super);
  41800. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  41801. var _this = _super.call(this, triggerOptions, condition) || this;
  41802. _this.propertyPath = propertyPath;
  41803. _this._target = _this._effectiveTarget = target;
  41804. return _this;
  41805. }
  41806. SwitchBooleanAction.prototype._prepare = function () {
  41807. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41808. this._property = this._getProperty(this.propertyPath);
  41809. };
  41810. SwitchBooleanAction.prototype.execute = function () {
  41811. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  41812. };
  41813. SwitchBooleanAction.prototype.serialize = function (parent) {
  41814. return _super.prototype._serialize.call(this, {
  41815. name: "SwitchBooleanAction",
  41816. properties: [
  41817. BABYLON.Action._GetTargetProperty(this._target),
  41818. { name: "propertyPath", value: this.propertyPath }
  41819. ]
  41820. }, parent);
  41821. };
  41822. return SwitchBooleanAction;
  41823. }(BABYLON.Action));
  41824. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  41825. var SetStateAction = (function (_super) {
  41826. __extends(SetStateAction, _super);
  41827. function SetStateAction(triggerOptions, target, value, condition) {
  41828. var _this = _super.call(this, triggerOptions, condition) || this;
  41829. _this.value = value;
  41830. _this._target = target;
  41831. return _this;
  41832. }
  41833. SetStateAction.prototype.execute = function () {
  41834. this._target.state = this.value;
  41835. };
  41836. SetStateAction.prototype.serialize = function (parent) {
  41837. return _super.prototype._serialize.call(this, {
  41838. name: "SetStateAction",
  41839. properties: [
  41840. BABYLON.Action._GetTargetProperty(this._target),
  41841. { name: "value", value: this.value }
  41842. ]
  41843. }, parent);
  41844. };
  41845. return SetStateAction;
  41846. }(BABYLON.Action));
  41847. BABYLON.SetStateAction = SetStateAction;
  41848. var SetValueAction = (function (_super) {
  41849. __extends(SetValueAction, _super);
  41850. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  41851. var _this = _super.call(this, triggerOptions, condition) || this;
  41852. _this.propertyPath = propertyPath;
  41853. _this.value = value;
  41854. _this._target = _this._effectiveTarget = target;
  41855. return _this;
  41856. }
  41857. SetValueAction.prototype._prepare = function () {
  41858. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41859. this._property = this._getProperty(this.propertyPath);
  41860. };
  41861. SetValueAction.prototype.execute = function () {
  41862. this._effectiveTarget[this._property] = this.value;
  41863. if (this._target.markAsDirty) {
  41864. this._target.markAsDirty(this._property);
  41865. }
  41866. };
  41867. SetValueAction.prototype.serialize = function (parent) {
  41868. return _super.prototype._serialize.call(this, {
  41869. name: "SetValueAction",
  41870. properties: [
  41871. BABYLON.Action._GetTargetProperty(this._target),
  41872. { name: "propertyPath", value: this.propertyPath },
  41873. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  41874. ]
  41875. }, parent);
  41876. };
  41877. return SetValueAction;
  41878. }(BABYLON.Action));
  41879. BABYLON.SetValueAction = SetValueAction;
  41880. var IncrementValueAction = (function (_super) {
  41881. __extends(IncrementValueAction, _super);
  41882. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  41883. var _this = _super.call(this, triggerOptions, condition) || this;
  41884. _this.propertyPath = propertyPath;
  41885. _this.value = value;
  41886. _this._target = _this._effectiveTarget = target;
  41887. return _this;
  41888. }
  41889. IncrementValueAction.prototype._prepare = function () {
  41890. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41891. this._property = this._getProperty(this.propertyPath);
  41892. if (typeof this._effectiveTarget[this._property] !== "number") {
  41893. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  41894. }
  41895. };
  41896. IncrementValueAction.prototype.execute = function () {
  41897. this._effectiveTarget[this._property] += this.value;
  41898. if (this._target.markAsDirty) {
  41899. this._target.markAsDirty(this._property);
  41900. }
  41901. };
  41902. IncrementValueAction.prototype.serialize = function (parent) {
  41903. return _super.prototype._serialize.call(this, {
  41904. name: "IncrementValueAction",
  41905. properties: [
  41906. BABYLON.Action._GetTargetProperty(this._target),
  41907. { name: "propertyPath", value: this.propertyPath },
  41908. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  41909. ]
  41910. }, parent);
  41911. };
  41912. return IncrementValueAction;
  41913. }(BABYLON.Action));
  41914. BABYLON.IncrementValueAction = IncrementValueAction;
  41915. var PlayAnimationAction = (function (_super) {
  41916. __extends(PlayAnimationAction, _super);
  41917. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  41918. var _this = _super.call(this, triggerOptions, condition) || this;
  41919. _this.from = from;
  41920. _this.to = to;
  41921. _this.loop = loop;
  41922. _this._target = target;
  41923. return _this;
  41924. }
  41925. PlayAnimationAction.prototype._prepare = function () {
  41926. };
  41927. PlayAnimationAction.prototype.execute = function () {
  41928. var scene = this._actionManager.getScene();
  41929. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  41930. };
  41931. PlayAnimationAction.prototype.serialize = function (parent) {
  41932. return _super.prototype._serialize.call(this, {
  41933. name: "PlayAnimationAction",
  41934. properties: [
  41935. BABYLON.Action._GetTargetProperty(this._target),
  41936. { name: "from", value: String(this.from) },
  41937. { name: "to", value: String(this.to) },
  41938. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  41939. ]
  41940. }, parent);
  41941. };
  41942. return PlayAnimationAction;
  41943. }(BABYLON.Action));
  41944. BABYLON.PlayAnimationAction = PlayAnimationAction;
  41945. var StopAnimationAction = (function (_super) {
  41946. __extends(StopAnimationAction, _super);
  41947. function StopAnimationAction(triggerOptions, target, condition) {
  41948. var _this = _super.call(this, triggerOptions, condition) || this;
  41949. _this._target = target;
  41950. return _this;
  41951. }
  41952. StopAnimationAction.prototype._prepare = function () {
  41953. };
  41954. StopAnimationAction.prototype.execute = function () {
  41955. var scene = this._actionManager.getScene();
  41956. scene.stopAnimation(this._target);
  41957. };
  41958. StopAnimationAction.prototype.serialize = function (parent) {
  41959. return _super.prototype._serialize.call(this, {
  41960. name: "StopAnimationAction",
  41961. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  41962. }, parent);
  41963. };
  41964. return StopAnimationAction;
  41965. }(BABYLON.Action));
  41966. BABYLON.StopAnimationAction = StopAnimationAction;
  41967. var DoNothingAction = (function (_super) {
  41968. __extends(DoNothingAction, _super);
  41969. function DoNothingAction(triggerOptions, condition) {
  41970. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  41971. return _super.call(this, triggerOptions, condition) || this;
  41972. }
  41973. DoNothingAction.prototype.execute = function () {
  41974. };
  41975. DoNothingAction.prototype.serialize = function (parent) {
  41976. return _super.prototype._serialize.call(this, {
  41977. name: "DoNothingAction",
  41978. properties: []
  41979. }, parent);
  41980. };
  41981. return DoNothingAction;
  41982. }(BABYLON.Action));
  41983. BABYLON.DoNothingAction = DoNothingAction;
  41984. var CombineAction = (function (_super) {
  41985. __extends(CombineAction, _super);
  41986. function CombineAction(triggerOptions, children, condition) {
  41987. var _this = _super.call(this, triggerOptions, condition) || this;
  41988. _this.children = children;
  41989. return _this;
  41990. }
  41991. CombineAction.prototype._prepare = function () {
  41992. for (var index = 0; index < this.children.length; index++) {
  41993. this.children[index]._actionManager = this._actionManager;
  41994. this.children[index]._prepare();
  41995. }
  41996. };
  41997. CombineAction.prototype.execute = function (evt) {
  41998. for (var index = 0; index < this.children.length; index++) {
  41999. this.children[index].execute(evt);
  42000. }
  42001. };
  42002. CombineAction.prototype.serialize = function (parent) {
  42003. var serializationObject = _super.prototype._serialize.call(this, {
  42004. name: "CombineAction",
  42005. properties: [],
  42006. combine: []
  42007. }, parent);
  42008. for (var i = 0; i < this.children.length; i++) {
  42009. serializationObject.combine.push(this.children[i].serialize(null));
  42010. }
  42011. return serializationObject;
  42012. };
  42013. return CombineAction;
  42014. }(BABYLON.Action));
  42015. BABYLON.CombineAction = CombineAction;
  42016. var ExecuteCodeAction = (function (_super) {
  42017. __extends(ExecuteCodeAction, _super);
  42018. function ExecuteCodeAction(triggerOptions, func, condition) {
  42019. var _this = _super.call(this, triggerOptions, condition) || this;
  42020. _this.func = func;
  42021. return _this;
  42022. }
  42023. ExecuteCodeAction.prototype.execute = function (evt) {
  42024. this.func(evt);
  42025. };
  42026. return ExecuteCodeAction;
  42027. }(BABYLON.Action));
  42028. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  42029. var SetParentAction = (function (_super) {
  42030. __extends(SetParentAction, _super);
  42031. function SetParentAction(triggerOptions, target, parent, condition) {
  42032. var _this = _super.call(this, triggerOptions, condition) || this;
  42033. _this._target = target;
  42034. _this._parent = parent;
  42035. return _this;
  42036. }
  42037. SetParentAction.prototype._prepare = function () {
  42038. };
  42039. SetParentAction.prototype.execute = function () {
  42040. if (this._target.parent === this._parent) {
  42041. return;
  42042. }
  42043. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  42044. invertParentWorldMatrix.invert();
  42045. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  42046. this._target.parent = this._parent;
  42047. };
  42048. SetParentAction.prototype.serialize = function (parent) {
  42049. return _super.prototype._serialize.call(this, {
  42050. name: "SetParentAction",
  42051. properties: [
  42052. BABYLON.Action._GetTargetProperty(this._target),
  42053. BABYLON.Action._GetTargetProperty(this._parent),
  42054. ]
  42055. }, parent);
  42056. };
  42057. return SetParentAction;
  42058. }(BABYLON.Action));
  42059. BABYLON.SetParentAction = SetParentAction;
  42060. var PlaySoundAction = (function (_super) {
  42061. __extends(PlaySoundAction, _super);
  42062. function PlaySoundAction(triggerOptions, sound, condition) {
  42063. var _this = _super.call(this, triggerOptions, condition) || this;
  42064. _this._sound = sound;
  42065. return _this;
  42066. }
  42067. PlaySoundAction.prototype._prepare = function () {
  42068. };
  42069. PlaySoundAction.prototype.execute = function () {
  42070. if (this._sound !== undefined)
  42071. this._sound.play();
  42072. };
  42073. PlaySoundAction.prototype.serialize = function (parent) {
  42074. return _super.prototype._serialize.call(this, {
  42075. name: "PlaySoundAction",
  42076. properties: [{ name: "sound", value: this._sound.name }]
  42077. }, parent);
  42078. };
  42079. return PlaySoundAction;
  42080. }(BABYLON.Action));
  42081. BABYLON.PlaySoundAction = PlaySoundAction;
  42082. var StopSoundAction = (function (_super) {
  42083. __extends(StopSoundAction, _super);
  42084. function StopSoundAction(triggerOptions, sound, condition) {
  42085. var _this = _super.call(this, triggerOptions, condition) || this;
  42086. _this._sound = sound;
  42087. return _this;
  42088. }
  42089. StopSoundAction.prototype._prepare = function () {
  42090. };
  42091. StopSoundAction.prototype.execute = function () {
  42092. if (this._sound !== undefined)
  42093. this._sound.stop();
  42094. };
  42095. StopSoundAction.prototype.serialize = function (parent) {
  42096. return _super.prototype._serialize.call(this, {
  42097. name: "StopSoundAction",
  42098. properties: [{ name: "sound", value: this._sound.name }]
  42099. }, parent);
  42100. };
  42101. return StopSoundAction;
  42102. }(BABYLON.Action));
  42103. BABYLON.StopSoundAction = StopSoundAction;
  42104. })(BABYLON || (BABYLON = {}));
  42105. //# sourceMappingURL=babylon.directActions.js.map
  42106. var BABYLON;
  42107. (function (BABYLON) {
  42108. var Geometry = (function () {
  42109. function Geometry(id, scene, vertexData, updatable, mesh) {
  42110. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  42111. this._totalVertices = 0;
  42112. this._isDisposed = false;
  42113. this.id = id;
  42114. this._engine = scene.getEngine();
  42115. this._meshes = [];
  42116. this._scene = scene;
  42117. //Init vertex buffer cache
  42118. this._vertexBuffers = {};
  42119. this._indices = [];
  42120. // vertexData
  42121. if (vertexData) {
  42122. this.setAllVerticesData(vertexData, updatable);
  42123. }
  42124. else {
  42125. this._totalVertices = 0;
  42126. this._indices = [];
  42127. }
  42128. if (this._engine.getCaps().vertexArrayObject) {
  42129. this._vertexArrayObjects = {};
  42130. }
  42131. // applyToMesh
  42132. if (mesh) {
  42133. if (mesh instanceof BABYLON.LinesMesh) {
  42134. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  42135. this.updateExtend();
  42136. }
  42137. this.applyToMesh(mesh);
  42138. mesh.computeWorldMatrix(true);
  42139. }
  42140. }
  42141. Object.defineProperty(Geometry.prototype, "boundingBias", {
  42142. /**
  42143. * 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
  42144. * @returns The Bias Vector
  42145. */
  42146. get: function () {
  42147. return this._boundingBias;
  42148. },
  42149. set: function (value) {
  42150. if (this._boundingBias && this._boundingBias.equals(value)) {
  42151. return;
  42152. }
  42153. this._boundingBias = value.clone();
  42154. this.updateBoundingInfo(true, null);
  42155. },
  42156. enumerable: true,
  42157. configurable: true
  42158. });
  42159. Object.defineProperty(Geometry.prototype, "extend", {
  42160. get: function () {
  42161. return this._extend;
  42162. },
  42163. enumerable: true,
  42164. configurable: true
  42165. });
  42166. Geometry.prototype.getScene = function () {
  42167. return this._scene;
  42168. };
  42169. Geometry.prototype.getEngine = function () {
  42170. return this._engine;
  42171. };
  42172. Geometry.prototype.isReady = function () {
  42173. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  42174. };
  42175. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  42176. get: function () {
  42177. for (var index = 0; index < this._meshes.length; index++) {
  42178. if (!this._meshes[index].doNotSerialize) {
  42179. return false;
  42180. }
  42181. }
  42182. return true;
  42183. },
  42184. enumerable: true,
  42185. configurable: true
  42186. });
  42187. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  42188. vertexData.applyToGeometry(this, updatable);
  42189. this.notifyUpdate();
  42190. };
  42191. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  42192. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  42193. this.setVerticesBuffer(buffer);
  42194. };
  42195. Geometry.prototype.setVerticesBuffer = function (buffer) {
  42196. var kind = buffer.getKind();
  42197. if (this._vertexBuffers[kind]) {
  42198. this._vertexBuffers[kind].dispose();
  42199. }
  42200. this._vertexBuffers[kind] = buffer;
  42201. if (kind === BABYLON.VertexBuffer.PositionKind) {
  42202. var data = buffer.getData();
  42203. var stride = buffer.getStrideSize();
  42204. this._totalVertices = data.length / stride;
  42205. this.updateExtend(data, stride);
  42206. var meshes = this._meshes;
  42207. var numOfMeshes = meshes.length;
  42208. for (var index = 0; index < numOfMeshes; index++) {
  42209. var mesh = meshes[index];
  42210. mesh._resetPointsArrayCache();
  42211. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  42212. mesh._createGlobalSubMesh();
  42213. mesh.computeWorldMatrix(true);
  42214. }
  42215. }
  42216. this.notifyUpdate(kind);
  42217. if (this._vertexArrayObjects) {
  42218. this._disposeVertexArrayObjects();
  42219. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  42220. }
  42221. };
  42222. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  42223. var vertexBuffer = this.getVertexBuffer(kind);
  42224. if (!vertexBuffer) {
  42225. return;
  42226. }
  42227. vertexBuffer.updateDirectly(data, offset);
  42228. this.notifyUpdate(kind);
  42229. };
  42230. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  42231. var vertexBuffer = this.getVertexBuffer(kind);
  42232. if (!vertexBuffer) {
  42233. return;
  42234. }
  42235. vertexBuffer.update(data);
  42236. if (kind === BABYLON.VertexBuffer.PositionKind) {
  42237. var stride = vertexBuffer.getStrideSize();
  42238. this._totalVertices = data.length / stride;
  42239. this.updateBoundingInfo(updateExtends, data);
  42240. }
  42241. this.notifyUpdate(kind);
  42242. };
  42243. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  42244. if (updateExtends) {
  42245. this.updateExtend(data);
  42246. }
  42247. var meshes = this._meshes;
  42248. var numOfMeshes = meshes.length;
  42249. for (var index = 0; index < numOfMeshes; index++) {
  42250. var mesh = meshes[index];
  42251. mesh._resetPointsArrayCache();
  42252. if (updateExtends) {
  42253. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  42254. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  42255. var subMesh = mesh.subMeshes[subIndex];
  42256. subMesh.refreshBoundingInfo();
  42257. }
  42258. }
  42259. }
  42260. };
  42261. Geometry.prototype._bind = function (effect, indexToBind) {
  42262. if (indexToBind === void 0) { indexToBind = undefined; }
  42263. if (indexToBind === undefined) {
  42264. indexToBind = this._indexBuffer;
  42265. }
  42266. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  42267. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  42268. return;
  42269. }
  42270. // Using VAO
  42271. if (!this._vertexArrayObjects[effect.key]) {
  42272. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  42273. }
  42274. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  42275. };
  42276. Geometry.prototype.getTotalVertices = function () {
  42277. if (!this.isReady()) {
  42278. return 0;
  42279. }
  42280. return this._totalVertices;
  42281. };
  42282. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  42283. var vertexBuffer = this.getVertexBuffer(kind);
  42284. if (!vertexBuffer) {
  42285. return null;
  42286. }
  42287. var orig = vertexBuffer.getData();
  42288. if (!copyWhenShared || this._meshes.length === 1) {
  42289. return orig;
  42290. }
  42291. else {
  42292. var len = orig.length;
  42293. var copy = [];
  42294. for (var i = 0; i < len; i++) {
  42295. copy.push(orig[i]);
  42296. }
  42297. return copy;
  42298. }
  42299. };
  42300. Geometry.prototype.getVertexBuffer = function (kind) {
  42301. if (!this.isReady()) {
  42302. return null;
  42303. }
  42304. return this._vertexBuffers[kind];
  42305. };
  42306. Geometry.prototype.getVertexBuffers = function () {
  42307. if (!this.isReady()) {
  42308. return null;
  42309. }
  42310. return this._vertexBuffers;
  42311. };
  42312. Geometry.prototype.isVerticesDataPresent = function (kind) {
  42313. if (!this._vertexBuffers) {
  42314. if (this._delayInfo) {
  42315. return this._delayInfo.indexOf(kind) !== -1;
  42316. }
  42317. return false;
  42318. }
  42319. return this._vertexBuffers[kind] !== undefined;
  42320. };
  42321. Geometry.prototype.getVerticesDataKinds = function () {
  42322. var result = [];
  42323. var kind;
  42324. if (!this._vertexBuffers && this._delayInfo) {
  42325. for (kind in this._delayInfo) {
  42326. result.push(kind);
  42327. }
  42328. }
  42329. else {
  42330. for (kind in this._vertexBuffers) {
  42331. result.push(kind);
  42332. }
  42333. }
  42334. return result;
  42335. };
  42336. Geometry.prototype.setIndices = function (indices, totalVertices) {
  42337. if (this._indexBuffer) {
  42338. this._engine._releaseBuffer(this._indexBuffer);
  42339. }
  42340. this._disposeVertexArrayObjects();
  42341. this._indices = indices;
  42342. if (this._meshes.length !== 0 && this._indices) {
  42343. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  42344. }
  42345. if (totalVertices !== undefined) {
  42346. this._totalVertices = totalVertices;
  42347. }
  42348. var meshes = this._meshes;
  42349. var numOfMeshes = meshes.length;
  42350. for (var index = 0; index < numOfMeshes; index++) {
  42351. meshes[index]._createGlobalSubMesh();
  42352. }
  42353. this.notifyUpdate();
  42354. };
  42355. Geometry.prototype.getTotalIndices = function () {
  42356. if (!this.isReady()) {
  42357. return 0;
  42358. }
  42359. return this._indices.length;
  42360. };
  42361. Geometry.prototype.getIndices = function (copyWhenShared) {
  42362. if (!this.isReady()) {
  42363. return null;
  42364. }
  42365. var orig = this._indices;
  42366. if (!copyWhenShared || this._meshes.length === 1) {
  42367. return orig;
  42368. }
  42369. else {
  42370. var len = orig.length;
  42371. var copy = [];
  42372. for (var i = 0; i < len; i++) {
  42373. copy.push(orig[i]);
  42374. }
  42375. return copy;
  42376. }
  42377. };
  42378. Geometry.prototype.getIndexBuffer = function () {
  42379. if (!this.isReady()) {
  42380. return null;
  42381. }
  42382. return this._indexBuffer;
  42383. };
  42384. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  42385. var meshes = this._meshes;
  42386. var index = meshes.indexOf(mesh);
  42387. if (index === -1) {
  42388. return;
  42389. }
  42390. meshes.splice(index, 1);
  42391. mesh._geometry = null;
  42392. if (meshes.length === 0 && shouldDispose) {
  42393. this.dispose();
  42394. }
  42395. };
  42396. Geometry.prototype.applyToMesh = function (mesh) {
  42397. if (mesh._geometry === this) {
  42398. return;
  42399. }
  42400. var previousGeometry = mesh._geometry;
  42401. if (previousGeometry) {
  42402. previousGeometry.releaseForMesh(mesh);
  42403. }
  42404. var meshes = this._meshes;
  42405. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  42406. mesh._geometry = this;
  42407. this._scene.pushGeometry(this);
  42408. meshes.push(mesh);
  42409. if (this.isReady()) {
  42410. this._applyToMesh(mesh);
  42411. }
  42412. else {
  42413. mesh._boundingInfo = this._boundingInfo;
  42414. }
  42415. };
  42416. Geometry.prototype.updateExtend = function (data, stride) {
  42417. if (data === void 0) { data = null; }
  42418. if (!data) {
  42419. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  42420. }
  42421. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  42422. };
  42423. Geometry.prototype._applyToMesh = function (mesh) {
  42424. var numOfMeshes = this._meshes.length;
  42425. // vertexBuffers
  42426. for (var kind in this._vertexBuffers) {
  42427. if (numOfMeshes === 1) {
  42428. this._vertexBuffers[kind].create();
  42429. }
  42430. var buffer = this._vertexBuffers[kind].getBuffer();
  42431. if (buffer)
  42432. buffer.references = numOfMeshes;
  42433. if (kind === BABYLON.VertexBuffer.PositionKind) {
  42434. mesh._resetPointsArrayCache();
  42435. if (!this._extend) {
  42436. this.updateExtend(this._vertexBuffers[kind].getData());
  42437. }
  42438. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  42439. mesh._createGlobalSubMesh();
  42440. //bounding info was just created again, world matrix should be applied again.
  42441. mesh._updateBoundingInfo();
  42442. }
  42443. }
  42444. // indexBuffer
  42445. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  42446. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  42447. }
  42448. if (this._indexBuffer) {
  42449. this._indexBuffer.references = numOfMeshes;
  42450. }
  42451. };
  42452. Geometry.prototype.notifyUpdate = function (kind) {
  42453. if (this.onGeometryUpdated) {
  42454. this.onGeometryUpdated(this, kind);
  42455. }
  42456. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  42457. var mesh = _a[_i];
  42458. mesh._markSubMeshesAsAttributesDirty();
  42459. }
  42460. };
  42461. Geometry.prototype.load = function (scene, onLoaded) {
  42462. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  42463. return;
  42464. }
  42465. if (this.isReady()) {
  42466. if (onLoaded) {
  42467. onLoaded();
  42468. }
  42469. return;
  42470. }
  42471. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  42472. this._queueLoad(scene, onLoaded);
  42473. };
  42474. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  42475. var _this = this;
  42476. scene._addPendingData(this);
  42477. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  42478. _this._delayLoadingFunction(JSON.parse(data), _this);
  42479. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  42480. _this._delayInfo = [];
  42481. scene._removePendingData(_this);
  42482. var meshes = _this._meshes;
  42483. var numOfMeshes = meshes.length;
  42484. for (var index = 0; index < numOfMeshes; index++) {
  42485. _this._applyToMesh(meshes[index]);
  42486. }
  42487. if (onLoaded) {
  42488. onLoaded();
  42489. }
  42490. }, function () { }, scene.database);
  42491. };
  42492. /**
  42493. * Invert the geometry to move from a right handed system to a left handed one.
  42494. */
  42495. Geometry.prototype.toLeftHanded = function () {
  42496. // Flip faces
  42497. var tIndices = this.getIndices(false);
  42498. if (tIndices != null && tIndices.length > 0) {
  42499. for (var i = 0; i < tIndices.length; i += 3) {
  42500. var tTemp = tIndices[i + 0];
  42501. tIndices[i + 0] = tIndices[i + 2];
  42502. tIndices[i + 2] = tTemp;
  42503. }
  42504. this.setIndices(tIndices);
  42505. }
  42506. // Negate position.z
  42507. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  42508. if (tPositions != null && tPositions.length > 0) {
  42509. for (var i = 0; i < tPositions.length; i += 3) {
  42510. tPositions[i + 2] = -tPositions[i + 2];
  42511. }
  42512. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  42513. }
  42514. // Negate normal.z
  42515. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  42516. if (tNormals != null && tNormals.length > 0) {
  42517. for (var i = 0; i < tNormals.length; i += 3) {
  42518. tNormals[i + 2] = -tNormals[i + 2];
  42519. }
  42520. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  42521. }
  42522. };
  42523. Geometry.prototype.isDisposed = function () {
  42524. return this._isDisposed;
  42525. };
  42526. Geometry.prototype._disposeVertexArrayObjects = function () {
  42527. if (this._vertexArrayObjects) {
  42528. for (var kind in this._vertexArrayObjects) {
  42529. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  42530. }
  42531. this._vertexArrayObjects = {};
  42532. }
  42533. };
  42534. Geometry.prototype.dispose = function () {
  42535. var meshes = this._meshes;
  42536. var numOfMeshes = meshes.length;
  42537. var index;
  42538. for (index = 0; index < numOfMeshes; index++) {
  42539. this.releaseForMesh(meshes[index]);
  42540. }
  42541. this._meshes = [];
  42542. this._disposeVertexArrayObjects();
  42543. for (var kind in this._vertexBuffers) {
  42544. this._vertexBuffers[kind].dispose();
  42545. }
  42546. this._vertexBuffers = {};
  42547. this._totalVertices = 0;
  42548. if (this._indexBuffer) {
  42549. this._engine._releaseBuffer(this._indexBuffer);
  42550. }
  42551. this._indexBuffer = null;
  42552. this._indices = [];
  42553. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  42554. this.delayLoadingFile = null;
  42555. this._delayLoadingFunction = null;
  42556. this._delayInfo = [];
  42557. this._boundingInfo = null;
  42558. this._scene.removeGeometry(this);
  42559. this._isDisposed = true;
  42560. };
  42561. Geometry.prototype.copy = function (id) {
  42562. var vertexData = new BABYLON.VertexData();
  42563. vertexData.indices = [];
  42564. var indices = this.getIndices();
  42565. for (var index = 0; index < indices.length; index++) {
  42566. vertexData.indices.push(indices[index]);
  42567. }
  42568. var updatable = false;
  42569. var stopChecking = false;
  42570. var kind;
  42571. for (kind in this._vertexBuffers) {
  42572. // using slice() to make a copy of the array and not just reference it
  42573. var data = this.getVerticesData(kind);
  42574. if (data instanceof Float32Array) {
  42575. vertexData.set(new Float32Array(data), kind);
  42576. }
  42577. else {
  42578. vertexData.set(data.slice(0), kind);
  42579. }
  42580. if (!stopChecking) {
  42581. updatable = this.getVertexBuffer(kind).isUpdatable();
  42582. stopChecking = !updatable;
  42583. }
  42584. }
  42585. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  42586. geometry.delayLoadState = this.delayLoadState;
  42587. geometry.delayLoadingFile = this.delayLoadingFile;
  42588. geometry._delayLoadingFunction = this._delayLoadingFunction;
  42589. for (kind in this._delayInfo) {
  42590. geometry._delayInfo = geometry._delayInfo || [];
  42591. geometry._delayInfo.push(kind);
  42592. }
  42593. // Bounding info
  42594. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  42595. return geometry;
  42596. };
  42597. Geometry.prototype.serialize = function () {
  42598. var serializationObject = {};
  42599. serializationObject.id = this.id;
  42600. if (BABYLON.Tags.HasTags(this)) {
  42601. serializationObject.tags = BABYLON.Tags.GetTags(this);
  42602. }
  42603. return serializationObject;
  42604. };
  42605. Geometry.prototype.serializeVerticeData = function () {
  42606. var serializationObject = this.serialize();
  42607. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  42608. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42609. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  42610. serializationObject.positions._updatable = true;
  42611. }
  42612. }
  42613. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42614. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42615. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  42616. serializationObject.normals._updatable = true;
  42617. }
  42618. }
  42619. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42620. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42621. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  42622. serializationObject.uvs._updatable = true;
  42623. }
  42624. }
  42625. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  42626. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  42627. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  42628. serializationObject.uv2s._updatable = true;
  42629. }
  42630. }
  42631. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  42632. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  42633. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  42634. serializationObject.uv3s._updatable = true;
  42635. }
  42636. }
  42637. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  42638. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  42639. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  42640. serializationObject.uv4s._updatable = true;
  42641. }
  42642. }
  42643. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  42644. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  42645. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  42646. serializationObject.uv5s._updatable = true;
  42647. }
  42648. }
  42649. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  42650. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  42651. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  42652. serializationObject.uv6s._updatable = true;
  42653. }
  42654. }
  42655. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  42656. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42657. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  42658. serializationObject.colors._updatable = true;
  42659. }
  42660. }
  42661. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  42662. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  42663. serializationObject.matricesIndices._isExpanded = true;
  42664. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  42665. serializationObject.matricesIndices._updatable = true;
  42666. }
  42667. }
  42668. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  42669. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  42670. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  42671. serializationObject.matricesWeights._updatable = true;
  42672. }
  42673. }
  42674. serializationObject.indices = this.getIndices();
  42675. return serializationObject;
  42676. };
  42677. // Statics
  42678. Geometry.ExtractFromMesh = function (mesh, id) {
  42679. var geometry = mesh._geometry;
  42680. if (!geometry) {
  42681. return null;
  42682. }
  42683. return geometry.copy(id);
  42684. };
  42685. /**
  42686. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  42687. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  42688. * Be aware Math.random() could cause collisions, but:
  42689. * "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"
  42690. */
  42691. Geometry.RandomId = function () {
  42692. return BABYLON.Tools.RandomId();
  42693. };
  42694. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  42695. var scene = mesh.getScene();
  42696. // Geometry
  42697. var geometryId = parsedGeometry.geometryId;
  42698. if (geometryId) {
  42699. var geometry = scene.getGeometryByID(geometryId);
  42700. if (geometry) {
  42701. geometry.applyToMesh(mesh);
  42702. }
  42703. }
  42704. else if (parsedGeometry instanceof ArrayBuffer) {
  42705. var binaryInfo = mesh._binaryInfo;
  42706. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  42707. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  42708. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  42709. }
  42710. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  42711. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  42712. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  42713. }
  42714. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  42715. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  42716. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  42717. }
  42718. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  42719. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  42720. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  42721. }
  42722. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  42723. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  42724. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  42725. }
  42726. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  42727. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  42728. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  42729. }
  42730. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  42731. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  42732. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  42733. }
  42734. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  42735. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  42736. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  42737. }
  42738. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  42739. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  42740. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  42741. }
  42742. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  42743. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  42744. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  42745. }
  42746. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  42747. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  42748. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  42749. }
  42750. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  42751. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  42752. mesh.setIndices(indicesData);
  42753. }
  42754. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  42755. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  42756. mesh.subMeshes = [];
  42757. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  42758. var materialIndex = subMeshesData[(i * 5) + 0];
  42759. var verticesStart = subMeshesData[(i * 5) + 1];
  42760. var verticesCount = subMeshesData[(i * 5) + 2];
  42761. var indexStart = subMeshesData[(i * 5) + 3];
  42762. var indexCount = subMeshesData[(i * 5) + 4];
  42763. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  42764. }
  42765. }
  42766. }
  42767. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  42768. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  42769. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  42770. if (parsedGeometry.uvs) {
  42771. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  42772. }
  42773. if (parsedGeometry.uvs2) {
  42774. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  42775. }
  42776. if (parsedGeometry.uvs3) {
  42777. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  42778. }
  42779. if (parsedGeometry.uvs4) {
  42780. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  42781. }
  42782. if (parsedGeometry.uvs5) {
  42783. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  42784. }
  42785. if (parsedGeometry.uvs6) {
  42786. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  42787. }
  42788. if (parsedGeometry.colors) {
  42789. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  42790. }
  42791. if (parsedGeometry.matricesIndices) {
  42792. if (!parsedGeometry.matricesIndices._isExpanded) {
  42793. var floatIndices = [];
  42794. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  42795. var matricesIndex = parsedGeometry.matricesIndices[i];
  42796. floatIndices.push(matricesIndex & 0x000000FF);
  42797. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  42798. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  42799. floatIndices.push(matricesIndex >> 24);
  42800. }
  42801. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  42802. }
  42803. else {
  42804. delete parsedGeometry.matricesIndices._isExpanded;
  42805. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  42806. }
  42807. }
  42808. if (parsedGeometry.matricesIndicesExtra) {
  42809. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  42810. var floatIndices = [];
  42811. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  42812. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  42813. floatIndices.push(matricesIndex & 0x000000FF);
  42814. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  42815. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  42816. floatIndices.push(matricesIndex >> 24);
  42817. }
  42818. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  42819. }
  42820. else {
  42821. delete parsedGeometry.matricesIndices._isExpanded;
  42822. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  42823. }
  42824. }
  42825. if (parsedGeometry.matricesWeights) {
  42826. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  42827. }
  42828. if (parsedGeometry.matricesWeightsExtra) {
  42829. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  42830. }
  42831. mesh.setIndices(parsedGeometry.indices);
  42832. }
  42833. // SubMeshes
  42834. if (parsedGeometry.subMeshes) {
  42835. mesh.subMeshes = [];
  42836. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  42837. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  42838. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  42839. }
  42840. }
  42841. // Flat shading
  42842. if (mesh._shouldGenerateFlatShading) {
  42843. mesh.convertToFlatShadedMesh();
  42844. delete mesh._shouldGenerateFlatShading;
  42845. }
  42846. // Update
  42847. mesh.computeWorldMatrix(true);
  42848. // Octree
  42849. if (scene['_selectionOctree']) {
  42850. scene['_selectionOctree'].addMesh(mesh);
  42851. }
  42852. };
  42853. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  42854. if (scene.getGeometryByID(parsedVertexData.id)) {
  42855. return null; // null since geometry could be something else than a box...
  42856. }
  42857. var geometry = new Geometry(parsedVertexData.id, scene);
  42858. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  42859. if (parsedVertexData.delayLoadingFile) {
  42860. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  42861. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  42862. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  42863. geometry._delayInfo = [];
  42864. if (parsedVertexData.hasUVs) {
  42865. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  42866. }
  42867. if (parsedVertexData.hasUVs2) {
  42868. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  42869. }
  42870. if (parsedVertexData.hasUVs3) {
  42871. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  42872. }
  42873. if (parsedVertexData.hasUVs4) {
  42874. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  42875. }
  42876. if (parsedVertexData.hasUVs5) {
  42877. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  42878. }
  42879. if (parsedVertexData.hasUVs6) {
  42880. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  42881. }
  42882. if (parsedVertexData.hasColors) {
  42883. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  42884. }
  42885. if (parsedVertexData.hasMatricesIndices) {
  42886. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42887. }
  42888. if (parsedVertexData.hasMatricesWeights) {
  42889. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42890. }
  42891. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  42892. }
  42893. else {
  42894. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  42895. }
  42896. scene.pushGeometry(geometry, true);
  42897. return geometry;
  42898. };
  42899. return Geometry;
  42900. }());
  42901. BABYLON.Geometry = Geometry;
  42902. /////// Primitives //////////////////////////////////////////////
  42903. (function (Geometry) {
  42904. var Primitives;
  42905. (function (Primitives) {
  42906. /// Abstract class
  42907. var _Primitive = (function (_super) {
  42908. __extends(_Primitive, _super);
  42909. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  42910. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  42911. _this._canBeRegenerated = _canBeRegenerated;
  42912. _this._beingRegenerated = true;
  42913. _this.regenerate();
  42914. _this._beingRegenerated = false;
  42915. return _this;
  42916. }
  42917. _Primitive.prototype.canBeRegenerated = function () {
  42918. return this._canBeRegenerated;
  42919. };
  42920. _Primitive.prototype.regenerate = function () {
  42921. if (!this._canBeRegenerated) {
  42922. return;
  42923. }
  42924. this._beingRegenerated = true;
  42925. this.setAllVerticesData(this._regenerateVertexData(), false);
  42926. this._beingRegenerated = false;
  42927. };
  42928. _Primitive.prototype.asNewGeometry = function (id) {
  42929. return _super.prototype.copy.call(this, id);
  42930. };
  42931. // overrides
  42932. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  42933. if (!this._beingRegenerated) {
  42934. return;
  42935. }
  42936. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  42937. };
  42938. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  42939. if (!this._beingRegenerated) {
  42940. return;
  42941. }
  42942. _super.prototype.setVerticesData.call(this, kind, data, false);
  42943. };
  42944. // to override
  42945. // protected
  42946. _Primitive.prototype._regenerateVertexData = function () {
  42947. throw new Error("Abstract method");
  42948. };
  42949. _Primitive.prototype.copy = function (id) {
  42950. throw new Error("Must be overriden in sub-classes.");
  42951. };
  42952. _Primitive.prototype.serialize = function () {
  42953. var serializationObject = _super.prototype.serialize.call(this);
  42954. serializationObject.canBeRegenerated = this.canBeRegenerated();
  42955. return serializationObject;
  42956. };
  42957. return _Primitive;
  42958. }(Geometry));
  42959. Primitives._Primitive = _Primitive;
  42960. var Ribbon = (function (_super) {
  42961. __extends(Ribbon, _super);
  42962. // Members
  42963. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  42964. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42965. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42966. _this.pathArray = pathArray;
  42967. _this.closeArray = closeArray;
  42968. _this.closePath = closePath;
  42969. _this.offset = offset;
  42970. _this.side = side;
  42971. return _this;
  42972. }
  42973. Ribbon.prototype._regenerateVertexData = function () {
  42974. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  42975. };
  42976. Ribbon.prototype.copy = function (id) {
  42977. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  42978. };
  42979. return Ribbon;
  42980. }(_Primitive));
  42981. Primitives.Ribbon = Ribbon;
  42982. var Box = (function (_super) {
  42983. __extends(Box, _super);
  42984. // Members
  42985. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  42986. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42987. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42988. _this.size = size;
  42989. _this.side = side;
  42990. return _this;
  42991. }
  42992. Box.prototype._regenerateVertexData = function () {
  42993. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  42994. };
  42995. Box.prototype.copy = function (id) {
  42996. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  42997. };
  42998. Box.prototype.serialize = function () {
  42999. var serializationObject = _super.prototype.serialize.call(this);
  43000. serializationObject.size = this.size;
  43001. return serializationObject;
  43002. };
  43003. Box.Parse = function (parsedBox, scene) {
  43004. if (scene.getGeometryByID(parsedBox.id)) {
  43005. return null; // null since geometry could be something else than a box...
  43006. }
  43007. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  43008. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  43009. scene.pushGeometry(box, true);
  43010. return box;
  43011. };
  43012. return Box;
  43013. }(_Primitive));
  43014. Primitives.Box = Box;
  43015. var Sphere = (function (_super) {
  43016. __extends(Sphere, _super);
  43017. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  43018. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  43019. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43020. _this.segments = segments;
  43021. _this.diameter = diameter;
  43022. _this.side = side;
  43023. return _this;
  43024. }
  43025. Sphere.prototype._regenerateVertexData = function () {
  43026. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  43027. };
  43028. Sphere.prototype.copy = function (id) {
  43029. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  43030. };
  43031. Sphere.prototype.serialize = function () {
  43032. var serializationObject = _super.prototype.serialize.call(this);
  43033. serializationObject.segments = this.segments;
  43034. serializationObject.diameter = this.diameter;
  43035. return serializationObject;
  43036. };
  43037. Sphere.Parse = function (parsedSphere, scene) {
  43038. if (scene.getGeometryByID(parsedSphere.id)) {
  43039. return null; // null since geometry could be something else than a sphere...
  43040. }
  43041. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  43042. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  43043. scene.pushGeometry(sphere, true);
  43044. return sphere;
  43045. };
  43046. return Sphere;
  43047. }(_Primitive));
  43048. Primitives.Sphere = Sphere;
  43049. var Disc = (function (_super) {
  43050. __extends(Disc, _super);
  43051. // Members
  43052. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  43053. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  43054. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43055. _this.radius = radius;
  43056. _this.tessellation = tessellation;
  43057. _this.side = side;
  43058. return _this;
  43059. }
  43060. Disc.prototype._regenerateVertexData = function () {
  43061. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  43062. };
  43063. Disc.prototype.copy = function (id) {
  43064. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  43065. };
  43066. return Disc;
  43067. }(_Primitive));
  43068. Primitives.Disc = Disc;
  43069. var Cylinder = (function (_super) {
  43070. __extends(Cylinder, _super);
  43071. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  43072. if (subdivisions === void 0) { subdivisions = 1; }
  43073. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  43074. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43075. _this.height = height;
  43076. _this.diameterTop = diameterTop;
  43077. _this.diameterBottom = diameterBottom;
  43078. _this.tessellation = tessellation;
  43079. _this.subdivisions = subdivisions;
  43080. _this.side = side;
  43081. return _this;
  43082. }
  43083. Cylinder.prototype._regenerateVertexData = function () {
  43084. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  43085. };
  43086. Cylinder.prototype.copy = function (id) {
  43087. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  43088. };
  43089. Cylinder.prototype.serialize = function () {
  43090. var serializationObject = _super.prototype.serialize.call(this);
  43091. serializationObject.height = this.height;
  43092. serializationObject.diameterTop = this.diameterTop;
  43093. serializationObject.diameterBottom = this.diameterBottom;
  43094. serializationObject.tessellation = this.tessellation;
  43095. return serializationObject;
  43096. };
  43097. Cylinder.Parse = function (parsedCylinder, scene) {
  43098. if (scene.getGeometryByID(parsedCylinder.id)) {
  43099. return null; // null since geometry could be something else than a cylinder...
  43100. }
  43101. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  43102. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  43103. scene.pushGeometry(cylinder, true);
  43104. return cylinder;
  43105. };
  43106. return Cylinder;
  43107. }(_Primitive));
  43108. Primitives.Cylinder = Cylinder;
  43109. var Torus = (function (_super) {
  43110. __extends(Torus, _super);
  43111. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  43112. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  43113. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43114. _this.diameter = diameter;
  43115. _this.thickness = thickness;
  43116. _this.tessellation = tessellation;
  43117. _this.side = side;
  43118. return _this;
  43119. }
  43120. Torus.prototype._regenerateVertexData = function () {
  43121. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  43122. };
  43123. Torus.prototype.copy = function (id) {
  43124. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  43125. };
  43126. Torus.prototype.serialize = function () {
  43127. var serializationObject = _super.prototype.serialize.call(this);
  43128. serializationObject.diameter = this.diameter;
  43129. serializationObject.thickness = this.thickness;
  43130. serializationObject.tessellation = this.tessellation;
  43131. return serializationObject;
  43132. };
  43133. Torus.Parse = function (parsedTorus, scene) {
  43134. if (scene.getGeometryByID(parsedTorus.id)) {
  43135. return null; // null since geometry could be something else than a torus...
  43136. }
  43137. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  43138. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  43139. scene.pushGeometry(torus, true);
  43140. return torus;
  43141. };
  43142. return Torus;
  43143. }(_Primitive));
  43144. Primitives.Torus = Torus;
  43145. var Ground = (function (_super) {
  43146. __extends(Ground, _super);
  43147. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  43148. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43149. _this.width = width;
  43150. _this.height = height;
  43151. _this.subdivisions = subdivisions;
  43152. return _this;
  43153. }
  43154. Ground.prototype._regenerateVertexData = function () {
  43155. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  43156. };
  43157. Ground.prototype.copy = function (id) {
  43158. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  43159. };
  43160. Ground.prototype.serialize = function () {
  43161. var serializationObject = _super.prototype.serialize.call(this);
  43162. serializationObject.width = this.width;
  43163. serializationObject.height = this.height;
  43164. serializationObject.subdivisions = this.subdivisions;
  43165. return serializationObject;
  43166. };
  43167. Ground.Parse = function (parsedGround, scene) {
  43168. if (scene.getGeometryByID(parsedGround.id)) {
  43169. return null; // null since geometry could be something else than a ground...
  43170. }
  43171. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  43172. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  43173. scene.pushGeometry(ground, true);
  43174. return ground;
  43175. };
  43176. return Ground;
  43177. }(_Primitive));
  43178. Primitives.Ground = Ground;
  43179. var TiledGround = (function (_super) {
  43180. __extends(TiledGround, _super);
  43181. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  43182. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43183. _this.xmin = xmin;
  43184. _this.zmin = zmin;
  43185. _this.xmax = xmax;
  43186. _this.zmax = zmax;
  43187. _this.subdivisions = subdivisions;
  43188. _this.precision = precision;
  43189. return _this;
  43190. }
  43191. TiledGround.prototype._regenerateVertexData = function () {
  43192. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  43193. };
  43194. TiledGround.prototype.copy = function (id) {
  43195. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  43196. };
  43197. return TiledGround;
  43198. }(_Primitive));
  43199. Primitives.TiledGround = TiledGround;
  43200. var Plane = (function (_super) {
  43201. __extends(Plane, _super);
  43202. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  43203. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  43204. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43205. _this.size = size;
  43206. _this.side = side;
  43207. return _this;
  43208. }
  43209. Plane.prototype._regenerateVertexData = function () {
  43210. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  43211. };
  43212. Plane.prototype.copy = function (id) {
  43213. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  43214. };
  43215. Plane.prototype.serialize = function () {
  43216. var serializationObject = _super.prototype.serialize.call(this);
  43217. serializationObject.size = this.size;
  43218. return serializationObject;
  43219. };
  43220. Plane.Parse = function (parsedPlane, scene) {
  43221. if (scene.getGeometryByID(parsedPlane.id)) {
  43222. return null; // null since geometry could be something else than a ground...
  43223. }
  43224. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  43225. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  43226. scene.pushGeometry(plane, true);
  43227. return plane;
  43228. };
  43229. return Plane;
  43230. }(_Primitive));
  43231. Primitives.Plane = Plane;
  43232. var TorusKnot = (function (_super) {
  43233. __extends(TorusKnot, _super);
  43234. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  43235. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  43236. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43237. _this.radius = radius;
  43238. _this.tube = tube;
  43239. _this.radialSegments = radialSegments;
  43240. _this.tubularSegments = tubularSegments;
  43241. _this.p = p;
  43242. _this.q = q;
  43243. _this.side = side;
  43244. return _this;
  43245. }
  43246. TorusKnot.prototype._regenerateVertexData = function () {
  43247. 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 });
  43248. };
  43249. TorusKnot.prototype.copy = function (id) {
  43250. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  43251. };
  43252. TorusKnot.prototype.serialize = function () {
  43253. var serializationObject = _super.prototype.serialize.call(this);
  43254. serializationObject.radius = this.radius;
  43255. serializationObject.tube = this.tube;
  43256. serializationObject.radialSegments = this.radialSegments;
  43257. serializationObject.tubularSegments = this.tubularSegments;
  43258. serializationObject.p = this.p;
  43259. serializationObject.q = this.q;
  43260. return serializationObject;
  43261. };
  43262. ;
  43263. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  43264. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  43265. return null; // null since geometry could be something else than a ground...
  43266. }
  43267. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  43268. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  43269. scene.pushGeometry(torusKnot, true);
  43270. return torusKnot;
  43271. };
  43272. return TorusKnot;
  43273. }(_Primitive));
  43274. Primitives.TorusKnot = TorusKnot;
  43275. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  43276. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  43277. })(BABYLON || (BABYLON = {}));
  43278. //# sourceMappingURL=babylon.geometry.js.map
  43279. /// <reference path="babylon.mesh.ts" />
  43280. var BABYLON;
  43281. (function (BABYLON) {
  43282. var GroundMesh = (function (_super) {
  43283. __extends(GroundMesh, _super);
  43284. function GroundMesh(name, scene) {
  43285. var _this = _super.call(this, name, scene) || this;
  43286. _this.generateOctree = false;
  43287. _this._worldInverse = new BABYLON.Matrix();
  43288. return _this;
  43289. }
  43290. GroundMesh.prototype.getClassName = function () {
  43291. return "GroundMesh";
  43292. };
  43293. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  43294. get: function () {
  43295. return Math.min(this._subdivisionsX, this._subdivisionsY);
  43296. },
  43297. enumerable: true,
  43298. configurable: true
  43299. });
  43300. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  43301. get: function () {
  43302. return this._subdivisionsX;
  43303. },
  43304. enumerable: true,
  43305. configurable: true
  43306. });
  43307. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  43308. get: function () {
  43309. return this._subdivisionsY;
  43310. },
  43311. enumerable: true,
  43312. configurable: true
  43313. });
  43314. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  43315. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  43316. this._subdivisionsX = chunksCount;
  43317. this._subdivisionsY = chunksCount;
  43318. this.subdivide(chunksCount);
  43319. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  43320. };
  43321. /**
  43322. * Returns a height (y) value in the Worl system :
  43323. * the ground altitude at the coordinates (x, z) expressed in the World system.
  43324. * Returns the ground y position if (x, z) are outside the ground surface.
  43325. */
  43326. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  43327. var world = this.getWorldMatrix();
  43328. var invMat = BABYLON.Tmp.Matrix[5];
  43329. world.invertToRef(invMat);
  43330. var tmpVect = BABYLON.Tmp.Vector3[8];
  43331. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  43332. x = tmpVect.x;
  43333. z = tmpVect.z;
  43334. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43335. return this.position.y;
  43336. }
  43337. if (!this._heightQuads || this._heightQuads.length == 0) {
  43338. this._initHeightQuads();
  43339. this._computeHeightQuads();
  43340. }
  43341. var facet = this._getFacetAt(x, z);
  43342. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  43343. // return y in the World system
  43344. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  43345. return tmpVect.y;
  43346. };
  43347. /**
  43348. * Returns a normalized vector (Vector3) orthogonal to the ground
  43349. * at the ground coordinates (x, z) expressed in the World system.
  43350. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  43351. */
  43352. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  43353. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  43354. this.getNormalAtCoordinatesToRef(x, z, normal);
  43355. return normal;
  43356. };
  43357. /**
  43358. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  43359. * at the ground coordinates (x, z) expressed in the World system.
  43360. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  43361. * Returns the GroundMesh.
  43362. */
  43363. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  43364. var world = this.getWorldMatrix();
  43365. var tmpMat = BABYLON.Tmp.Matrix[5];
  43366. world.invertToRef(tmpMat);
  43367. var tmpVect = BABYLON.Tmp.Vector3[8];
  43368. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  43369. x = tmpVect.x;
  43370. z = tmpVect.z;
  43371. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43372. return this;
  43373. }
  43374. if (!this._heightQuads || this._heightQuads.length == 0) {
  43375. this._initHeightQuads();
  43376. this._computeHeightQuads();
  43377. }
  43378. var facet = this._getFacetAt(x, z);
  43379. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  43380. return this;
  43381. };
  43382. /**
  43383. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  43384. * if the ground has been updated.
  43385. * This can be used in the render loop.
  43386. * Returns the GroundMesh.
  43387. */
  43388. GroundMesh.prototype.updateCoordinateHeights = function () {
  43389. if (!this._heightQuads || this._heightQuads.length == 0) {
  43390. this._initHeightQuads();
  43391. }
  43392. this._computeHeightQuads();
  43393. return this;
  43394. };
  43395. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  43396. GroundMesh.prototype._getFacetAt = function (x, z) {
  43397. // retrieve col and row from x, z coordinates in the ground local system
  43398. var subdivisionsX = this._subdivisionsX;
  43399. var subdivisionsY = this._subdivisionsY;
  43400. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  43401. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  43402. var quad = this._heightQuads[row * this._subdivisionsX + col];
  43403. var facet;
  43404. if (z < quad.slope.x * x + quad.slope.y) {
  43405. facet = quad.facet1;
  43406. }
  43407. else {
  43408. facet = quad.facet2;
  43409. }
  43410. return facet;
  43411. };
  43412. // Creates and populates the heightMap array with "facet" elements :
  43413. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  43414. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43415. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43416. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43417. // Returns the GroundMesh.
  43418. GroundMesh.prototype._initHeightQuads = function () {
  43419. var subdivisionsX = this._subdivisionsX;
  43420. var subdivisionsY = this._subdivisionsY;
  43421. this._heightQuads = new Array();
  43422. for (var row = 0; row < subdivisionsY; row++) {
  43423. for (var col = 0; col < subdivisionsX; col++) {
  43424. 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) };
  43425. this._heightQuads[row * subdivisionsX + col] = quad;
  43426. }
  43427. }
  43428. return this;
  43429. };
  43430. // Compute each quad element values and update the the heightMap array :
  43431. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43432. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43433. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43434. // Returns the GroundMesh.
  43435. GroundMesh.prototype._computeHeightQuads = function () {
  43436. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43437. var v1 = BABYLON.Tmp.Vector3[3];
  43438. var v2 = BABYLON.Tmp.Vector3[2];
  43439. var v3 = BABYLON.Tmp.Vector3[1];
  43440. var v4 = BABYLON.Tmp.Vector3[0];
  43441. var v1v2 = BABYLON.Tmp.Vector3[4];
  43442. var v1v3 = BABYLON.Tmp.Vector3[5];
  43443. var v1v4 = BABYLON.Tmp.Vector3[6];
  43444. var norm1 = BABYLON.Tmp.Vector3[7];
  43445. var norm2 = BABYLON.Tmp.Vector3[8];
  43446. var i = 0;
  43447. var j = 0;
  43448. var k = 0;
  43449. var cd = 0; // 2D slope coefficient : z = cd * x + h
  43450. var h = 0;
  43451. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  43452. var d2 = 0;
  43453. var subdivisionsX = this._subdivisionsX;
  43454. var subdivisionsY = this._subdivisionsY;
  43455. for (var row = 0; row < subdivisionsY; row++) {
  43456. for (var col = 0; col < subdivisionsX; col++) {
  43457. i = col * 3;
  43458. j = row * (subdivisionsX + 1) * 3;
  43459. k = (row + 1) * (subdivisionsX + 1) * 3;
  43460. v1.x = positions[j + i];
  43461. v1.y = positions[j + i + 1];
  43462. v1.z = positions[j + i + 2];
  43463. v2.x = positions[j + i + 3];
  43464. v2.y = positions[j + i + 4];
  43465. v2.z = positions[j + i + 5];
  43466. v3.x = positions[k + i];
  43467. v3.y = positions[k + i + 1];
  43468. v3.z = positions[k + i + 2];
  43469. v4.x = positions[k + i + 3];
  43470. v4.y = positions[k + i + 4];
  43471. v4.z = positions[k + i + 5];
  43472. // 2D slope V1V4
  43473. cd = (v4.z - v1.z) / (v4.x - v1.x);
  43474. h = v1.z - cd * v1.x; // v1 belongs to the slope
  43475. // facet equations :
  43476. // we compute each facet normal vector
  43477. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  43478. // we compute the value d by applying the equation to v1 which belongs to the plane
  43479. // then we store the facet equation in a Vector4
  43480. v2.subtractToRef(v1, v1v2);
  43481. v3.subtractToRef(v1, v1v3);
  43482. v4.subtractToRef(v1, v1v4);
  43483. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  43484. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  43485. norm1.normalize();
  43486. norm2.normalize();
  43487. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  43488. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  43489. var quad = this._heightQuads[row * subdivisionsX + col];
  43490. quad.slope.copyFromFloats(cd, h);
  43491. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  43492. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  43493. }
  43494. }
  43495. return this;
  43496. };
  43497. GroundMesh.prototype.serialize = function (serializationObject) {
  43498. _super.prototype.serialize.call(this, serializationObject);
  43499. serializationObject.subdivisionsX = this._subdivisionsX;
  43500. serializationObject.subdivisionsY = this._subdivisionsY;
  43501. serializationObject.minX = this._minX;
  43502. serializationObject.maxX = this._maxX;
  43503. serializationObject.minZ = this._minZ;
  43504. serializationObject.maxZ = this._maxZ;
  43505. serializationObject.width = this._width;
  43506. serializationObject.height = this._height;
  43507. };
  43508. GroundMesh.Parse = function (parsedMesh, scene) {
  43509. var result = new GroundMesh(parsedMesh.name, scene);
  43510. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  43511. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  43512. result._minX = parsedMesh.minX;
  43513. result._maxX = parsedMesh.maxX;
  43514. result._minZ = parsedMesh.minZ;
  43515. result._maxZ = parsedMesh.maxZ;
  43516. result._width = parsedMesh.width;
  43517. result._height = parsedMesh.height;
  43518. return result;
  43519. };
  43520. return GroundMesh;
  43521. }(BABYLON.Mesh));
  43522. BABYLON.GroundMesh = GroundMesh;
  43523. })(BABYLON || (BABYLON = {}));
  43524. //# sourceMappingURL=babylon.groundMesh.js.map
  43525. /// <reference path="babylon.mesh.ts" />
  43526. var BABYLON;
  43527. (function (BABYLON) {
  43528. var LinesMesh = (function (_super) {
  43529. __extends(LinesMesh, _super);
  43530. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  43531. if (parent === void 0) { parent = null; }
  43532. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  43533. _this.color = new BABYLON.Color3(1, 1, 1);
  43534. _this.alpha = 1;
  43535. _this._positionBuffer = {};
  43536. if (source) {
  43537. _this.color = source.color.clone();
  43538. _this.alpha = source.alpha;
  43539. }
  43540. _this._intersectionThreshold = 0.1;
  43541. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  43542. attributes: [BABYLON.VertexBuffer.PositionKind],
  43543. uniforms: ["worldViewProjection", "color"],
  43544. needAlphaBlending: true
  43545. });
  43546. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  43547. return _this;
  43548. }
  43549. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  43550. /**
  43551. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43552. * This margin is expressed in world space coordinates, so its value may vary.
  43553. * Default value is 0.1
  43554. * @returns the intersection Threshold value.
  43555. */
  43556. get: function () {
  43557. return this._intersectionThreshold;
  43558. },
  43559. /**
  43560. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43561. * This margin is expressed in world space coordinates, so its value may vary.
  43562. * @param value the new threshold to apply
  43563. */
  43564. set: function (value) {
  43565. if (this._intersectionThreshold === value) {
  43566. return;
  43567. }
  43568. this._intersectionThreshold = value;
  43569. if (this.geometry) {
  43570. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  43571. }
  43572. },
  43573. enumerable: true,
  43574. configurable: true
  43575. });
  43576. /**
  43577. * Returns the string "LineMesh"
  43578. */
  43579. LinesMesh.prototype.getClassName = function () {
  43580. return "LinesMesh";
  43581. };
  43582. Object.defineProperty(LinesMesh.prototype, "material", {
  43583. get: function () {
  43584. return this._colorShader;
  43585. },
  43586. enumerable: true,
  43587. configurable: true
  43588. });
  43589. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  43590. get: function () {
  43591. return false;
  43592. },
  43593. enumerable: true,
  43594. configurable: true
  43595. });
  43596. LinesMesh.prototype.createInstance = function (name) {
  43597. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  43598. return null;
  43599. };
  43600. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  43601. var engine = this.getScene().getEngine();
  43602. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  43603. // VBOs
  43604. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  43605. // Color
  43606. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  43607. return this;
  43608. };
  43609. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  43610. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  43611. return this;
  43612. }
  43613. var engine = this.getScene().getEngine();
  43614. // Draw order
  43615. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  43616. return this;
  43617. };
  43618. LinesMesh.prototype.dispose = function (doNotRecurse) {
  43619. this._colorShader.dispose();
  43620. _super.prototype.dispose.call(this, doNotRecurse);
  43621. };
  43622. /**
  43623. * Returns a new LineMesh object cloned from the current one.
  43624. */
  43625. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43626. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  43627. };
  43628. return LinesMesh;
  43629. }(BABYLON.Mesh));
  43630. BABYLON.LinesMesh = LinesMesh;
  43631. })(BABYLON || (BABYLON = {}));
  43632. //# sourceMappingURL=babylon.linesMesh.js.map
  43633. var BABYLON;
  43634. (function (BABYLON) {
  43635. var DefaultLoadingScreen = (function () {
  43636. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  43637. if (_loadingText === void 0) { _loadingText = ""; }
  43638. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  43639. var _this = this;
  43640. this._renderingCanvas = _renderingCanvas;
  43641. this._loadingText = _loadingText;
  43642. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  43643. // Resize
  43644. this._resizeLoadingUI = function () {
  43645. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  43646. _this._loadingDiv.style.position = "absolute";
  43647. _this._loadingDiv.style.left = canvasRect.left + "px";
  43648. _this._loadingDiv.style.top = canvasRect.top + "px";
  43649. _this._loadingDiv.style.width = canvasRect.width + "px";
  43650. _this._loadingDiv.style.height = canvasRect.height + "px";
  43651. };
  43652. }
  43653. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  43654. var _this = this;
  43655. if (this._loadingDiv) {
  43656. // Do not add a loading screen if there is already one
  43657. return;
  43658. }
  43659. this._loadingDiv = document.createElement("div");
  43660. this._loadingDiv.id = "babylonjsLoadingDiv";
  43661. this._loadingDiv.style.opacity = "0";
  43662. this._loadingDiv.style.transition = "opacity 1.5s ease";
  43663. // Loading text
  43664. this._loadingTextDiv = document.createElement("div");
  43665. this._loadingTextDiv.style.position = "absolute";
  43666. this._loadingTextDiv.style.left = "0";
  43667. this._loadingTextDiv.style.top = "50%";
  43668. this._loadingTextDiv.style.marginTop = "80px";
  43669. this._loadingTextDiv.style.width = "100%";
  43670. this._loadingTextDiv.style.height = "20px";
  43671. this._loadingTextDiv.style.fontFamily = "Arial";
  43672. this._loadingTextDiv.style.fontSize = "14px";
  43673. this._loadingTextDiv.style.color = "white";
  43674. this._loadingTextDiv.style.textAlign = "center";
  43675. this._loadingTextDiv.innerHTML = "Loading";
  43676. this._loadingDiv.appendChild(this._loadingTextDiv);
  43677. //set the predefined text
  43678. this._loadingTextDiv.innerHTML = this._loadingText;
  43679. // Loading img
  43680. var imgBack = new Image();
  43681. 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==";
  43682. imgBack.style.position = "absolute";
  43683. imgBack.style.left = "50%";
  43684. imgBack.style.top = "50%";
  43685. imgBack.style.marginLeft = "-50px";
  43686. imgBack.style.marginTop = "-50px";
  43687. imgBack.style.transition = "transform 1.0s ease";
  43688. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  43689. var deg = 360;
  43690. var onTransitionEnd = function () {
  43691. deg += 360;
  43692. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  43693. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  43694. };
  43695. imgBack.addEventListener("transitionend", onTransitionEnd);
  43696. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  43697. this._loadingDiv.appendChild(imgBack);
  43698. // front image
  43699. var imgFront = new Image();
  43700. 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=";
  43701. imgFront.style.position = "absolute";
  43702. imgFront.style.left = "50%";
  43703. imgFront.style.top = "50%";
  43704. imgFront.style.marginLeft = "-50px";
  43705. imgFront.style.marginTop = "-50px";
  43706. this._loadingDiv.appendChild(imgFront);
  43707. this._resizeLoadingUI();
  43708. window.addEventListener("resize", this._resizeLoadingUI);
  43709. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  43710. document.body.appendChild(this._loadingDiv);
  43711. setTimeout(function () {
  43712. _this._loadingDiv.style.opacity = "1";
  43713. imgBack.style.transform = "rotateZ(360deg)";
  43714. imgBack.style.webkitTransform = "rotateZ(360deg)";
  43715. }, 0);
  43716. };
  43717. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  43718. var _this = this;
  43719. if (!this._loadingDiv) {
  43720. return;
  43721. }
  43722. var onTransitionEnd = function () {
  43723. if (!_this._loadingDiv) {
  43724. return;
  43725. }
  43726. document.body.removeChild(_this._loadingDiv);
  43727. window.removeEventListener("resize", _this._resizeLoadingUI);
  43728. _this._loadingDiv = null;
  43729. };
  43730. this._loadingDiv.style.opacity = "0";
  43731. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  43732. };
  43733. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  43734. set: function (text) {
  43735. this._loadingText = text;
  43736. if (this._loadingTextDiv) {
  43737. this._loadingTextDiv.innerHTML = this._loadingText;
  43738. }
  43739. },
  43740. enumerable: true,
  43741. configurable: true
  43742. });
  43743. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  43744. get: function () {
  43745. return this._loadingDivBackgroundColor;
  43746. },
  43747. set: function (color) {
  43748. this._loadingDivBackgroundColor = color;
  43749. if (!this._loadingDiv) {
  43750. return;
  43751. }
  43752. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  43753. },
  43754. enumerable: true,
  43755. configurable: true
  43756. });
  43757. return DefaultLoadingScreen;
  43758. }());
  43759. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  43760. })(BABYLON || (BABYLON = {}));
  43761. //# sourceMappingURL=babylon.loadingScreen.js.map
  43762. var BABYLON;
  43763. (function (BABYLON) {
  43764. var AudioEngine = (function () {
  43765. function AudioEngine() {
  43766. this._audioContext = null;
  43767. this._audioContextInitialized = false;
  43768. this.canUseWebAudio = false;
  43769. this.WarnedWebAudioUnsupported = false;
  43770. this.unlocked = false;
  43771. this.isMP3supported = false;
  43772. this.isOGGsupported = false;
  43773. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  43774. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  43775. this.canUseWebAudio = true;
  43776. }
  43777. var audioElem = document.createElement('audio');
  43778. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  43779. this.isMP3supported = true;
  43780. }
  43781. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  43782. this.isOGGsupported = true;
  43783. }
  43784. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  43785. this._unlockiOSaudio();
  43786. }
  43787. else {
  43788. this.unlocked = true;
  43789. }
  43790. }
  43791. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  43792. get: function () {
  43793. if (!this._audioContextInitialized) {
  43794. this._initializeAudioContext();
  43795. }
  43796. return this._audioContext;
  43797. },
  43798. enumerable: true,
  43799. configurable: true
  43800. });
  43801. AudioEngine.prototype._unlockiOSaudio = function () {
  43802. var _this = this;
  43803. var unlockaudio = function () {
  43804. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  43805. var source = _this.audioContext.createBufferSource();
  43806. source.buffer = buffer;
  43807. source.connect(_this.audioContext.destination);
  43808. source.start(0);
  43809. setTimeout(function () {
  43810. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  43811. _this.unlocked = true;
  43812. window.removeEventListener('touchend', unlockaudio, false);
  43813. if (_this.onAudioUnlocked) {
  43814. _this.onAudioUnlocked();
  43815. }
  43816. }
  43817. }, 0);
  43818. };
  43819. window.addEventListener('touchend', unlockaudio, false);
  43820. };
  43821. AudioEngine.prototype._initializeAudioContext = function () {
  43822. try {
  43823. if (this.canUseWebAudio) {
  43824. this._audioContext = new AudioContext();
  43825. // create a global volume gain node
  43826. this.masterGain = this._audioContext.createGain();
  43827. this.masterGain.gain.value = 1;
  43828. this.masterGain.connect(this._audioContext.destination);
  43829. this._audioContextInitialized = true;
  43830. }
  43831. }
  43832. catch (e) {
  43833. this.canUseWebAudio = false;
  43834. BABYLON.Tools.Error("Web Audio: " + e.message);
  43835. }
  43836. };
  43837. AudioEngine.prototype.dispose = function () {
  43838. if (this.canUseWebAudio && this._audioContextInitialized) {
  43839. if (this._connectedAnalyser) {
  43840. this._connectedAnalyser.stopDebugCanvas();
  43841. this._connectedAnalyser.dispose();
  43842. this.masterGain.disconnect();
  43843. this.masterGain.connect(this._audioContext.destination);
  43844. this._connectedAnalyser = null;
  43845. }
  43846. this.masterGain.gain.value = 1;
  43847. }
  43848. this.WarnedWebAudioUnsupported = false;
  43849. };
  43850. AudioEngine.prototype.getGlobalVolume = function () {
  43851. if (this.canUseWebAudio && this._audioContextInitialized) {
  43852. return this.masterGain.gain.value;
  43853. }
  43854. else {
  43855. return -1;
  43856. }
  43857. };
  43858. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  43859. if (this.canUseWebAudio && this._audioContextInitialized) {
  43860. this.masterGain.gain.value = newVolume;
  43861. }
  43862. };
  43863. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  43864. if (this._connectedAnalyser) {
  43865. this._connectedAnalyser.stopDebugCanvas();
  43866. }
  43867. if (this.canUseWebAudio && this._audioContextInitialized) {
  43868. this._connectedAnalyser = analyser;
  43869. this.masterGain.disconnect();
  43870. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  43871. }
  43872. };
  43873. return AudioEngine;
  43874. }());
  43875. BABYLON.AudioEngine = AudioEngine;
  43876. })(BABYLON || (BABYLON = {}));
  43877. //# sourceMappingURL=babylon.audioEngine.js.map
  43878. var BABYLON;
  43879. (function (BABYLON) {
  43880. var Sound = (function () {
  43881. /**
  43882. * Create a sound and attach it to a scene
  43883. * @param name Name of your sound
  43884. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  43885. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  43886. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  43887. */
  43888. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  43889. var _this = this;
  43890. this.autoplay = false;
  43891. this.loop = false;
  43892. this.useCustomAttenuation = false;
  43893. this.spatialSound = false;
  43894. this.refDistance = 1;
  43895. this.rolloffFactor = 1;
  43896. this.maxDistance = 100;
  43897. this.distanceModel = "linear";
  43898. this._panningModel = "equalpower";
  43899. this._playbackRate = 1;
  43900. this._streaming = false;
  43901. this._startTime = 0;
  43902. this._startOffset = 0;
  43903. this._position = BABYLON.Vector3.Zero();
  43904. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  43905. this._volume = 1;
  43906. this._isLoaded = false;
  43907. this._isReadyToPlay = false;
  43908. this.isPlaying = false;
  43909. this.isPaused = false;
  43910. this._isDirectional = false;
  43911. // Used if you'd like to create a directional sound.
  43912. // If not set, the sound will be omnidirectional
  43913. this._coneInnerAngle = 360;
  43914. this._coneOuterAngle = 360;
  43915. this._coneOuterGain = 0;
  43916. this._isOutputConnected = false;
  43917. this._urlType = "Unknown";
  43918. this.name = name;
  43919. this._scene = scene;
  43920. this._readyToPlayCallback = readyToPlayCallback;
  43921. // Default custom attenuation function is a linear attenuation
  43922. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  43923. if (currentDistance < maxDistance) {
  43924. return currentVolume * (1 - currentDistance / maxDistance);
  43925. }
  43926. else {
  43927. return 0;
  43928. }
  43929. };
  43930. if (options) {
  43931. this.autoplay = options.autoplay || false;
  43932. this.loop = options.loop || false;
  43933. // if volume === 0, we need another way to check this option
  43934. if (options.volume !== undefined) {
  43935. this._volume = options.volume;
  43936. }
  43937. this.spatialSound = options.spatialSound || false;
  43938. this.maxDistance = options.maxDistance || 100;
  43939. this.useCustomAttenuation = options.useCustomAttenuation || false;
  43940. this.rolloffFactor = options.rolloffFactor || 1;
  43941. this.refDistance = options.refDistance || 1;
  43942. this.distanceModel = options.distanceModel || "linear";
  43943. this._playbackRate = options.playbackRate || 1;
  43944. this._streaming = options.streaming || false;
  43945. }
  43946. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43947. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  43948. this._soundGain.gain.value = this._volume;
  43949. this._inputAudioNode = this._soundGain;
  43950. this._ouputAudioNode = this._soundGain;
  43951. if (this.spatialSound) {
  43952. this._createSpatialParameters();
  43953. }
  43954. this._scene.mainSoundTrack.AddSound(this);
  43955. var validParameter = true;
  43956. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  43957. if (urlOrArrayBuffer) {
  43958. if (typeof (urlOrArrayBuffer) === "string")
  43959. this._urlType = "String";
  43960. if (Array.isArray(urlOrArrayBuffer))
  43961. this._urlType = "Array";
  43962. if (urlOrArrayBuffer instanceof ArrayBuffer)
  43963. this._urlType = "ArrayBuffer";
  43964. var urls = [];
  43965. var codecSupportedFound = false;
  43966. switch (this._urlType) {
  43967. case "ArrayBuffer":
  43968. if (urlOrArrayBuffer.byteLength > 0) {
  43969. codecSupportedFound = true;
  43970. this._soundLoaded(urlOrArrayBuffer);
  43971. }
  43972. break;
  43973. case "String":
  43974. urls.push(urlOrArrayBuffer);
  43975. case "Array":
  43976. if (urls.length === 0)
  43977. urls = urlOrArrayBuffer;
  43978. // If we found a supported format, we load it immediately and stop the loop
  43979. for (var i = 0; i < urls.length; i++) {
  43980. var url = urls[i];
  43981. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  43982. codecSupportedFound = true;
  43983. }
  43984. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  43985. codecSupportedFound = true;
  43986. }
  43987. if (url.indexOf(".wav", url.length - 4) !== -1) {
  43988. codecSupportedFound = true;
  43989. }
  43990. if (codecSupportedFound) {
  43991. // Loading sound using XHR2
  43992. if (!this._streaming) {
  43993. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  43994. }
  43995. else {
  43996. this._htmlAudioElement = new Audio(url);
  43997. this._htmlAudioElement.controls = false;
  43998. this._htmlAudioElement.loop = this.loop;
  43999. this._htmlAudioElement.crossOrigin = "anonymous";
  44000. this._htmlAudioElement.preload = "auto";
  44001. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  44002. _this._isReadyToPlay = true;
  44003. if (_this.autoplay) {
  44004. _this.play();
  44005. }
  44006. if (_this._readyToPlayCallback) {
  44007. _this._readyToPlayCallback();
  44008. }
  44009. });
  44010. document.body.appendChild(this._htmlAudioElement);
  44011. }
  44012. break;
  44013. }
  44014. }
  44015. break;
  44016. default:
  44017. validParameter = false;
  44018. break;
  44019. }
  44020. if (!validParameter) {
  44021. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  44022. }
  44023. else {
  44024. if (!codecSupportedFound) {
  44025. this._isReadyToPlay = true;
  44026. // Simulating a ready to play event to avoid breaking code path
  44027. if (this._readyToPlayCallback) {
  44028. window.setTimeout(function () {
  44029. _this._readyToPlayCallback();
  44030. }, 1000);
  44031. }
  44032. }
  44033. }
  44034. }
  44035. }
  44036. else {
  44037. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  44038. this._scene.mainSoundTrack.AddSound(this);
  44039. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  44040. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  44041. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  44042. }
  44043. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  44044. if (this._readyToPlayCallback) {
  44045. window.setTimeout(function () {
  44046. _this._readyToPlayCallback();
  44047. }, 1000);
  44048. }
  44049. }
  44050. }
  44051. Sound.prototype.dispose = function () {
  44052. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  44053. if (this.isPlaying) {
  44054. this.stop();
  44055. }
  44056. this._isReadyToPlay = false;
  44057. if (this.soundTrackId === -1) {
  44058. this._scene.mainSoundTrack.RemoveSound(this);
  44059. }
  44060. else {
  44061. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  44062. }
  44063. if (this._soundGain) {
  44064. this._soundGain.disconnect();
  44065. this._soundGain = null;
  44066. }
  44067. if (this._soundPanner) {
  44068. this._soundPanner.disconnect();
  44069. this._soundPanner = null;
  44070. }
  44071. if (this._soundSource) {
  44072. this._soundSource.disconnect();
  44073. this._soundSource = null;
  44074. }
  44075. this._audioBuffer = null;
  44076. if (this._htmlAudioElement) {
  44077. this._htmlAudioElement.pause();
  44078. this._htmlAudioElement.src = "";
  44079. document.body.removeChild(this._htmlAudioElement);
  44080. }
  44081. if (this._connectedMesh) {
  44082. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44083. this._connectedMesh = null;
  44084. }
  44085. }
  44086. };
  44087. Sound.prototype.isReady = function () {
  44088. return this._isReadyToPlay;
  44089. };
  44090. Sound.prototype._soundLoaded = function (audioData) {
  44091. var _this = this;
  44092. this._isLoaded = true;
  44093. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  44094. _this._audioBuffer = buffer;
  44095. _this._isReadyToPlay = true;
  44096. if (_this.autoplay) {
  44097. _this.play();
  44098. }
  44099. if (_this._readyToPlayCallback) {
  44100. _this._readyToPlayCallback();
  44101. }
  44102. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  44103. };
  44104. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  44105. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44106. this._audioBuffer = audioBuffer;
  44107. this._isReadyToPlay = true;
  44108. }
  44109. };
  44110. Sound.prototype.updateOptions = function (options) {
  44111. if (options) {
  44112. this.loop = options.loop || this.loop;
  44113. this.maxDistance = options.maxDistance || this.maxDistance;
  44114. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  44115. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  44116. this.refDistance = options.refDistance || this.refDistance;
  44117. this.distanceModel = options.distanceModel || this.distanceModel;
  44118. this._playbackRate = options.playbackRate || this._playbackRate;
  44119. this._updateSpatialParameters();
  44120. if (this.isPlaying) {
  44121. if (this._streaming) {
  44122. this._htmlAudioElement.playbackRate = this._playbackRate;
  44123. }
  44124. else {
  44125. this._soundSource.playbackRate.value = this._playbackRate;
  44126. }
  44127. }
  44128. }
  44129. };
  44130. Sound.prototype._createSpatialParameters = function () {
  44131. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44132. if (this._scene.headphone) {
  44133. this._panningModel = "HRTF";
  44134. }
  44135. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  44136. this._updateSpatialParameters();
  44137. this._soundPanner.connect(this._ouputAudioNode);
  44138. this._inputAudioNode = this._soundPanner;
  44139. }
  44140. };
  44141. Sound.prototype._updateSpatialParameters = function () {
  44142. if (this.spatialSound) {
  44143. if (this.useCustomAttenuation) {
  44144. // Tricks to disable in a way embedded Web Audio attenuation
  44145. this._soundPanner.distanceModel = "linear";
  44146. this._soundPanner.maxDistance = Number.MAX_VALUE;
  44147. this._soundPanner.refDistance = 1;
  44148. this._soundPanner.rolloffFactor = 1;
  44149. this._soundPanner.panningModel = this._panningModel;
  44150. }
  44151. else {
  44152. this._soundPanner.distanceModel = this.distanceModel;
  44153. this._soundPanner.maxDistance = this.maxDistance;
  44154. this._soundPanner.refDistance = this.refDistance;
  44155. this._soundPanner.rolloffFactor = this.rolloffFactor;
  44156. this._soundPanner.panningModel = this._panningModel;
  44157. }
  44158. }
  44159. };
  44160. Sound.prototype.switchPanningModelToHRTF = function () {
  44161. this._panningModel = "HRTF";
  44162. this._switchPanningModel();
  44163. };
  44164. Sound.prototype.switchPanningModelToEqualPower = function () {
  44165. this._panningModel = "equalpower";
  44166. this._switchPanningModel();
  44167. };
  44168. Sound.prototype._switchPanningModel = function () {
  44169. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  44170. this._soundPanner.panningModel = this._panningModel;
  44171. }
  44172. };
  44173. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  44174. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44175. if (this._isOutputConnected) {
  44176. this._ouputAudioNode.disconnect();
  44177. }
  44178. this._ouputAudioNode.connect(soundTrackAudioNode);
  44179. this._isOutputConnected = true;
  44180. }
  44181. };
  44182. /**
  44183. * Transform this sound into a directional source
  44184. * @param coneInnerAngle Size of the inner cone in degree
  44185. * @param coneOuterAngle Size of the outer cone in degree
  44186. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  44187. */
  44188. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  44189. if (coneOuterAngle < coneInnerAngle) {
  44190. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  44191. return;
  44192. }
  44193. this._coneInnerAngle = coneInnerAngle;
  44194. this._coneOuterAngle = coneOuterAngle;
  44195. this._coneOuterGain = coneOuterGain;
  44196. this._isDirectional = true;
  44197. if (this.isPlaying && this.loop) {
  44198. this.stop();
  44199. this.play();
  44200. }
  44201. };
  44202. Sound.prototype.setPosition = function (newPosition) {
  44203. this._position = newPosition;
  44204. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  44205. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  44206. }
  44207. };
  44208. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  44209. this._localDirection = newLocalDirection;
  44210. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  44211. this._updateDirection();
  44212. }
  44213. };
  44214. Sound.prototype._updateDirection = function () {
  44215. var mat = this._connectedMesh.getWorldMatrix();
  44216. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  44217. direction.normalize();
  44218. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  44219. };
  44220. Sound.prototype.updateDistanceFromListener = function () {
  44221. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  44222. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  44223. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  44224. }
  44225. };
  44226. Sound.prototype.setAttenuationFunction = function (callback) {
  44227. this._customAttenuationFunction = callback;
  44228. };
  44229. /**
  44230. * Play the sound
  44231. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  44232. * @param offset (optional) Start the sound setting it at a specific time
  44233. */
  44234. Sound.prototype.play = function (time, offset) {
  44235. var _this = this;
  44236. if (this._isReadyToPlay && this._scene.audioEnabled) {
  44237. try {
  44238. if (this._startOffset < 0) {
  44239. time = -this._startOffset;
  44240. this._startOffset = 0;
  44241. }
  44242. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  44243. if (!this._soundSource || !this._streamingSource) {
  44244. if (this.spatialSound) {
  44245. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  44246. if (this._isDirectional) {
  44247. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  44248. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  44249. this._soundPanner.coneOuterGain = this._coneOuterGain;
  44250. if (this._connectedMesh) {
  44251. this._updateDirection();
  44252. }
  44253. else {
  44254. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  44255. }
  44256. }
  44257. }
  44258. }
  44259. if (this._streaming) {
  44260. if (!this._streamingSource) {
  44261. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  44262. this._htmlAudioElement.onended = function () { _this._onended(); };
  44263. this._htmlAudioElement.playbackRate = this._playbackRate;
  44264. }
  44265. this._streamingSource.disconnect();
  44266. this._streamingSource.connect(this._inputAudioNode);
  44267. this._htmlAudioElement.play();
  44268. }
  44269. else {
  44270. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  44271. this._soundSource.buffer = this._audioBuffer;
  44272. this._soundSource.connect(this._inputAudioNode);
  44273. this._soundSource.loop = this.loop;
  44274. this._soundSource.playbackRate.value = this._playbackRate;
  44275. this._soundSource.onended = function () { _this._onended(); };
  44276. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  44277. }
  44278. this._startTime = startTime;
  44279. this.isPlaying = true;
  44280. this.isPaused = false;
  44281. }
  44282. catch (ex) {
  44283. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  44284. }
  44285. }
  44286. };
  44287. Sound.prototype._onended = function () {
  44288. this.isPlaying = false;
  44289. if (this.onended) {
  44290. this.onended();
  44291. }
  44292. };
  44293. /**
  44294. * Stop the sound
  44295. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  44296. */
  44297. Sound.prototype.stop = function (time) {
  44298. if (this.isPlaying) {
  44299. if (this._streaming) {
  44300. this._htmlAudioElement.pause();
  44301. // Test needed for Firefox or it will generate an Invalid State Error
  44302. if (this._htmlAudioElement.currentTime > 0) {
  44303. this._htmlAudioElement.currentTime = 0;
  44304. }
  44305. }
  44306. else {
  44307. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  44308. this._soundSource.stop(stopTime);
  44309. this._soundSource.onended = null;
  44310. if (!this.isPaused) {
  44311. this._startOffset = 0;
  44312. }
  44313. }
  44314. this.isPlaying = false;
  44315. }
  44316. };
  44317. Sound.prototype.pause = function () {
  44318. if (this.isPlaying) {
  44319. this.isPaused = true;
  44320. if (this._streaming) {
  44321. this._htmlAudioElement.pause();
  44322. }
  44323. else {
  44324. this.stop(0);
  44325. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  44326. }
  44327. }
  44328. };
  44329. Sound.prototype.setVolume = function (newVolume, time) {
  44330. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44331. if (time) {
  44332. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  44333. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  44334. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  44335. }
  44336. else {
  44337. this._soundGain.gain.value = newVolume;
  44338. }
  44339. }
  44340. this._volume = newVolume;
  44341. };
  44342. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  44343. this._playbackRate = newPlaybackRate;
  44344. if (this.isPlaying) {
  44345. if (this._streaming) {
  44346. this._htmlAudioElement.playbackRate = this._playbackRate;
  44347. }
  44348. else {
  44349. this._soundSource.playbackRate.value = this._playbackRate;
  44350. }
  44351. }
  44352. };
  44353. Sound.prototype.getVolume = function () {
  44354. return this._volume;
  44355. };
  44356. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  44357. var _this = this;
  44358. if (this._connectedMesh) {
  44359. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44360. this._registerFunc = null;
  44361. }
  44362. this._connectedMesh = meshToConnectTo;
  44363. if (!this.spatialSound) {
  44364. this.spatialSound = true;
  44365. this._createSpatialParameters();
  44366. if (this.isPlaying && this.loop) {
  44367. this.stop();
  44368. this.play();
  44369. }
  44370. }
  44371. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  44372. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  44373. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  44374. };
  44375. Sound.prototype.detachFromMesh = function () {
  44376. if (this._connectedMesh) {
  44377. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44378. this._registerFunc = null;
  44379. this._connectedMesh = null;
  44380. }
  44381. };
  44382. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  44383. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  44384. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  44385. this._updateDirection();
  44386. }
  44387. };
  44388. Sound.prototype.clone = function () {
  44389. var _this = this;
  44390. if (!this._streaming) {
  44391. var setBufferAndRun = function () {
  44392. if (_this._isReadyToPlay) {
  44393. clonedSound._audioBuffer = _this.getAudioBuffer();
  44394. clonedSound._isReadyToPlay = true;
  44395. if (clonedSound.autoplay) {
  44396. clonedSound.play();
  44397. }
  44398. }
  44399. else {
  44400. window.setTimeout(setBufferAndRun, 300);
  44401. }
  44402. };
  44403. var currentOptions = {
  44404. autoplay: this.autoplay, loop: this.loop,
  44405. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  44406. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  44407. refDistance: this.refDistance, distanceModel: this.distanceModel
  44408. };
  44409. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  44410. if (this.useCustomAttenuation) {
  44411. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  44412. }
  44413. clonedSound.setPosition(this._position);
  44414. clonedSound.setPlaybackRate(this._playbackRate);
  44415. setBufferAndRun();
  44416. return clonedSound;
  44417. }
  44418. else {
  44419. return null;
  44420. }
  44421. };
  44422. Sound.prototype.getAudioBuffer = function () {
  44423. return this._audioBuffer;
  44424. };
  44425. Sound.prototype.serialize = function () {
  44426. var serializationObject = {
  44427. name: this.name,
  44428. url: this.name,
  44429. autoplay: this.autoplay,
  44430. loop: this.loop,
  44431. volume: this._volume,
  44432. spatialSound: this.spatialSound,
  44433. maxDistance: this.maxDistance,
  44434. rolloffFactor: this.rolloffFactor,
  44435. refDistance: this.refDistance,
  44436. distanceModel: this.distanceModel,
  44437. playbackRate: this._playbackRate,
  44438. panningModel: this._panningModel,
  44439. soundTrackId: this.soundTrackId
  44440. };
  44441. if (this.spatialSound) {
  44442. if (this._connectedMesh)
  44443. serializationObject.connectedMeshId = this._connectedMesh.id;
  44444. serializationObject.position = this._position.asArray();
  44445. serializationObject.refDistance = this.refDistance;
  44446. serializationObject.distanceModel = this.distanceModel;
  44447. serializationObject.isDirectional = this._isDirectional;
  44448. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  44449. serializationObject.coneInnerAngle = this._coneInnerAngle;
  44450. serializationObject.coneOuterAngle = this._coneOuterAngle;
  44451. serializationObject.coneOuterGain = this._coneOuterGain;
  44452. }
  44453. return serializationObject;
  44454. };
  44455. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  44456. var soundName = parsedSound.name;
  44457. var soundUrl;
  44458. if (parsedSound.url) {
  44459. soundUrl = rootUrl + parsedSound.url;
  44460. }
  44461. else {
  44462. soundUrl = rootUrl + soundName;
  44463. }
  44464. var options = {
  44465. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  44466. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  44467. rolloffFactor: parsedSound.rolloffFactor,
  44468. refDistance: parsedSound.refDistance,
  44469. distanceModel: parsedSound.distanceModel,
  44470. playbackRate: parsedSound.playbackRate
  44471. };
  44472. var newSound;
  44473. if (!sourceSound) {
  44474. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  44475. scene._addPendingData(newSound);
  44476. }
  44477. else {
  44478. var setBufferAndRun = function () {
  44479. if (sourceSound._isReadyToPlay) {
  44480. newSound._audioBuffer = sourceSound.getAudioBuffer();
  44481. newSound._isReadyToPlay = true;
  44482. if (newSound.autoplay) {
  44483. newSound.play();
  44484. }
  44485. }
  44486. else {
  44487. window.setTimeout(setBufferAndRun, 300);
  44488. }
  44489. };
  44490. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  44491. setBufferAndRun();
  44492. }
  44493. if (parsedSound.position) {
  44494. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  44495. newSound.setPosition(soundPosition);
  44496. }
  44497. if (parsedSound.isDirectional) {
  44498. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  44499. if (parsedSound.localDirectionToMesh) {
  44500. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  44501. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  44502. }
  44503. }
  44504. if (parsedSound.connectedMeshId) {
  44505. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  44506. if (connectedMesh) {
  44507. newSound.attachToMesh(connectedMesh);
  44508. }
  44509. }
  44510. return newSound;
  44511. };
  44512. return Sound;
  44513. }());
  44514. BABYLON.Sound = Sound;
  44515. })(BABYLON || (BABYLON = {}));
  44516. //# sourceMappingURL=babylon.sound.js.map
  44517. var BABYLON;
  44518. (function (BABYLON) {
  44519. var SoundTrack = (function () {
  44520. function SoundTrack(scene, options) {
  44521. this.id = -1;
  44522. this._isMainTrack = false;
  44523. this._isInitialized = false;
  44524. this._scene = scene;
  44525. this.soundCollection = new Array();
  44526. this._options = options;
  44527. if (!this._isMainTrack) {
  44528. this._scene.soundTracks.push(this);
  44529. this.id = this._scene.soundTracks.length - 1;
  44530. }
  44531. }
  44532. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  44533. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44534. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  44535. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  44536. if (this._options) {
  44537. if (this._options.volume) {
  44538. this._outputAudioNode.gain.value = this._options.volume;
  44539. }
  44540. if (this._options.mainTrack) {
  44541. this._isMainTrack = this._options.mainTrack;
  44542. }
  44543. }
  44544. this._isInitialized = true;
  44545. }
  44546. };
  44547. SoundTrack.prototype.dispose = function () {
  44548. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44549. if (this._connectedAnalyser) {
  44550. this._connectedAnalyser.stopDebugCanvas();
  44551. }
  44552. while (this.soundCollection.length) {
  44553. this.soundCollection[0].dispose();
  44554. }
  44555. if (this._outputAudioNode) {
  44556. this._outputAudioNode.disconnect();
  44557. }
  44558. this._outputAudioNode = null;
  44559. }
  44560. };
  44561. SoundTrack.prototype.AddSound = function (sound) {
  44562. if (!this._isInitialized) {
  44563. this._initializeSoundTrackAudioGraph();
  44564. }
  44565. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44566. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  44567. }
  44568. if (sound.soundTrackId) {
  44569. if (sound.soundTrackId === -1) {
  44570. this._scene.mainSoundTrack.RemoveSound(sound);
  44571. }
  44572. else {
  44573. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  44574. }
  44575. }
  44576. this.soundCollection.push(sound);
  44577. sound.soundTrackId = this.id;
  44578. };
  44579. SoundTrack.prototype.RemoveSound = function (sound) {
  44580. var index = this.soundCollection.indexOf(sound);
  44581. if (index !== -1) {
  44582. this.soundCollection.splice(index, 1);
  44583. }
  44584. };
  44585. SoundTrack.prototype.setVolume = function (newVolume) {
  44586. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44587. this._outputAudioNode.gain.value = newVolume;
  44588. }
  44589. };
  44590. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  44591. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44592. for (var i = 0; i < this.soundCollection.length; i++) {
  44593. this.soundCollection[i].switchPanningModelToHRTF();
  44594. }
  44595. }
  44596. };
  44597. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  44598. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44599. for (var i = 0; i < this.soundCollection.length; i++) {
  44600. this.soundCollection[i].switchPanningModelToEqualPower();
  44601. }
  44602. }
  44603. };
  44604. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  44605. if (this._connectedAnalyser) {
  44606. this._connectedAnalyser.stopDebugCanvas();
  44607. }
  44608. this._connectedAnalyser = analyser;
  44609. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44610. this._outputAudioNode.disconnect();
  44611. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  44612. }
  44613. };
  44614. return SoundTrack;
  44615. }());
  44616. BABYLON.SoundTrack = SoundTrack;
  44617. })(BABYLON || (BABYLON = {}));
  44618. //# sourceMappingURL=babylon.soundtrack.js.map
  44619. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  44620. /// <reference path="..\Math\babylon.math.ts" />
  44621. var BABYLON;
  44622. (function (BABYLON) {
  44623. /**
  44624. * Special Glow Blur post process only blurring the alpha channel
  44625. * It enforces keeping the most luminous color in the color channel.
  44626. */
  44627. var GlowBlurPostProcess = (function (_super) {
  44628. __extends(GlowBlurPostProcess, _super);
  44629. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  44630. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  44631. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  44632. _this.direction = direction;
  44633. _this.blurWidth = blurWidth;
  44634. _this.onApplyObservable.add(function (effect) {
  44635. effect.setFloat2("screenSize", _this.width, _this.height);
  44636. effect.setVector2("direction", _this.direction);
  44637. effect.setFloat("blurWidth", _this.blurWidth);
  44638. });
  44639. return _this;
  44640. }
  44641. return GlowBlurPostProcess;
  44642. }(BABYLON.PostProcess));
  44643. /**
  44644. * The highlight layer Helps adding a glow effect around a mesh.
  44645. *
  44646. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  44647. * glowy meshes to your scene.
  44648. *
  44649. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  44650. */
  44651. var HighlightLayer = (function () {
  44652. /**
  44653. * Instantiates a new highlight Layer and references it to the scene..
  44654. * @param name The name of the layer
  44655. * @param scene The scene to use the layer in
  44656. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  44657. */
  44658. function HighlightLayer(name, scene, options) {
  44659. this.name = name;
  44660. this._vertexBuffers = {};
  44661. this._mainTextureDesiredSize = { width: 0, height: 0 };
  44662. this._meshes = {};
  44663. this._maxSize = 0;
  44664. this._shouldRender = false;
  44665. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  44666. this._excludedMeshes = {};
  44667. /**
  44668. * Specifies whether or not the inner glow is ACTIVE in the layer.
  44669. */
  44670. this.innerGlow = true;
  44671. /**
  44672. * Specifies whether or not the outer glow is ACTIVE in the layer.
  44673. */
  44674. this.outerGlow = true;
  44675. /**
  44676. * Specifies wether the highlight layer is enabled or not.
  44677. */
  44678. this.isEnabled = true;
  44679. /**
  44680. * An event triggered when the highlight layer has been disposed.
  44681. * @type {BABYLON.Observable}
  44682. */
  44683. this.onDisposeObservable = new BABYLON.Observable();
  44684. /**
  44685. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  44686. * @type {BABYLON.Observable}
  44687. */
  44688. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  44689. /**
  44690. * An event triggered when the highlight layer is being blurred.
  44691. * @type {BABYLON.Observable}
  44692. */
  44693. this.onBeforeBlurObservable = new BABYLON.Observable();
  44694. /**
  44695. * An event triggered when the highlight layer has been blurred.
  44696. * @type {BABYLON.Observable}
  44697. */
  44698. this.onAfterBlurObservable = new BABYLON.Observable();
  44699. /**
  44700. * An event triggered when the glowing blurred texture is being merged in the scene.
  44701. * @type {BABYLON.Observable}
  44702. */
  44703. this.onBeforeComposeObservable = new BABYLON.Observable();
  44704. /**
  44705. * An event triggered when the glowing blurred texture has been merged in the scene.
  44706. * @type {BABYLON.Observable}
  44707. */
  44708. this.onAfterComposeObservable = new BABYLON.Observable();
  44709. /**
  44710. * An event triggered when the highlight layer changes its size.
  44711. * @type {BABYLON.Observable}
  44712. */
  44713. this.onSizeChangedObservable = new BABYLON.Observable();
  44714. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44715. var engine = scene.getEngine();
  44716. this._engine = engine;
  44717. this._maxSize = this._engine.getCaps().maxTextureSize;
  44718. this._scene.highlightLayers.push(this);
  44719. // Warn on stencil.
  44720. if (!this._engine.isStencilEnable) {
  44721. 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 }");
  44722. }
  44723. // Adapt options
  44724. this._options = options || {
  44725. mainTextureRatio: 0.25,
  44726. blurTextureSizeRatio: 0.5,
  44727. blurHorizontalSize: 1,
  44728. blurVerticalSize: 1,
  44729. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  44730. };
  44731. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  44732. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  44733. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  44734. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  44735. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  44736. // VBO
  44737. var vertices = [];
  44738. vertices.push(1, 1);
  44739. vertices.push(-1, 1);
  44740. vertices.push(-1, -1);
  44741. vertices.push(1, -1);
  44742. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  44743. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  44744. // Indices
  44745. var indices = [];
  44746. indices.push(0);
  44747. indices.push(1);
  44748. indices.push(2);
  44749. indices.push(0);
  44750. indices.push(2);
  44751. indices.push(3);
  44752. this._indexBuffer = engine.createIndexBuffer(indices);
  44753. // Effect
  44754. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  44755. // Render target
  44756. this.setMainTextureSize();
  44757. // Create Textures and post processes
  44758. this.createTextureAndPostProcesses();
  44759. }
  44760. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  44761. /**
  44762. * Gets the horizontal size of the blur.
  44763. */
  44764. get: function () {
  44765. return this._horizontalBlurPostprocess.blurWidth;
  44766. },
  44767. /**
  44768. * Specifies the horizontal size of the blur.
  44769. */
  44770. set: function (value) {
  44771. this._horizontalBlurPostprocess.blurWidth = value;
  44772. },
  44773. enumerable: true,
  44774. configurable: true
  44775. });
  44776. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  44777. /**
  44778. * Gets the vertical size of the blur.
  44779. */
  44780. get: function () {
  44781. return this._verticalBlurPostprocess.blurWidth;
  44782. },
  44783. /**
  44784. * Specifies the vertical size of the blur.
  44785. */
  44786. set: function (value) {
  44787. this._verticalBlurPostprocess.blurWidth = value;
  44788. },
  44789. enumerable: true,
  44790. configurable: true
  44791. });
  44792. Object.defineProperty(HighlightLayer.prototype, "camera", {
  44793. /**
  44794. * Gets the camera attached to the layer.
  44795. */
  44796. get: function () {
  44797. return this._options.camera;
  44798. },
  44799. enumerable: true,
  44800. configurable: true
  44801. });
  44802. /**
  44803. * Creates the render target textures and post processes used in the highlight layer.
  44804. */
  44805. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  44806. var _this = this;
  44807. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  44808. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  44809. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  44810. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  44811. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  44812. width: this._mainTextureDesiredSize.width,
  44813. height: this._mainTextureDesiredSize.height
  44814. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  44815. this._mainTexture.activeCamera = this._options.camera;
  44816. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44817. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44818. this._mainTexture.anisotropicFilteringLevel = 1;
  44819. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44820. this._mainTexture.renderParticles = false;
  44821. this._mainTexture.renderList = null;
  44822. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  44823. width: blurTextureWidth,
  44824. height: blurTextureHeight
  44825. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  44826. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44827. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44828. this._blurTexture.anisotropicFilteringLevel = 16;
  44829. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  44830. this._blurTexture.renderParticles = false;
  44831. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  44832. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  44833. effect.setTexture("textureSampler", _this._mainTexture);
  44834. });
  44835. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  44836. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  44837. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  44838. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  44839. });
  44840. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  44841. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  44842. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  44843. });
  44844. }
  44845. else {
  44846. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  44847. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  44848. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  44849. });
  44850. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  44851. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  44852. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  44853. });
  44854. }
  44855. this._mainTexture.onAfterUnbindObservable.add(function () {
  44856. _this.onBeforeBlurObservable.notifyObservers(_this);
  44857. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  44858. _this.onAfterBlurObservable.notifyObservers(_this);
  44859. });
  44860. // Custom render function
  44861. var renderSubMesh = function (subMesh) {
  44862. var mesh = subMesh.getRenderingMesh();
  44863. var scene = _this._scene;
  44864. var engine = scene.getEngine();
  44865. // Culling
  44866. engine.setState(subMesh.getMaterial().backFaceCulling);
  44867. // Managing instances
  44868. var batch = mesh._getInstancesRenderList(subMesh._id);
  44869. if (batch.mustReturn) {
  44870. return;
  44871. }
  44872. // Excluded Mesh
  44873. if (_this._excludedMeshes[mesh.uniqueId]) {
  44874. return;
  44875. }
  44876. ;
  44877. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44878. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  44879. var material = subMesh.getMaterial();
  44880. var emissiveTexture = null;
  44881. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  44882. emissiveTexture = material.emissiveTexture;
  44883. }
  44884. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  44885. engine.enableEffect(_this._glowMapGenerationEffect);
  44886. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  44887. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  44888. if (highlightLayerMesh) {
  44889. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  44890. }
  44891. else {
  44892. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  44893. }
  44894. // Alpha test
  44895. if (material && material.needAlphaTesting()) {
  44896. var alphaTexture = material.getAlphaTestTexture();
  44897. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  44898. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  44899. }
  44900. // Glow emissive only
  44901. if (emissiveTexture) {
  44902. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  44903. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  44904. }
  44905. // Bones
  44906. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44907. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44908. }
  44909. // Draw
  44910. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  44911. }
  44912. else {
  44913. // Need to reset refresh rate of the shadowMap
  44914. _this._mainTexture.resetRefreshCounter();
  44915. }
  44916. };
  44917. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  44918. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  44919. var index;
  44920. for (index = 0; index < opaqueSubMeshes.length; index++) {
  44921. renderSubMesh(opaqueSubMeshes.data[index]);
  44922. }
  44923. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  44924. renderSubMesh(alphaTestSubMeshes.data[index]);
  44925. }
  44926. for (index = 0; index < transparentSubMeshes.length; index++) {
  44927. renderSubMesh(transparentSubMeshes.data[index]);
  44928. }
  44929. };
  44930. this._mainTexture.onClearObservable.add(function (engine) {
  44931. engine.clear(HighlightLayer.neutralColor, true, true, true);
  44932. });
  44933. };
  44934. /**
  44935. * Checks for the readiness of the element composing the layer.
  44936. * @param subMesh the mesh to check for
  44937. * @param useInstances specify wether or not to use instances to render the mesh
  44938. * @param emissiveTexture the associated emissive texture used to generate the glow
  44939. * @return true if ready otherwise, false
  44940. */
  44941. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  44942. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  44943. return false;
  44944. }
  44945. var defines = [];
  44946. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44947. var mesh = subMesh.getMesh();
  44948. var material = subMesh.getMaterial();
  44949. var uv1 = false;
  44950. var uv2 = false;
  44951. // Alpha test
  44952. if (material && material.needAlphaTesting()) {
  44953. var alphaTexture = material.getAlphaTestTexture();
  44954. if (alphaTexture) {
  44955. defines.push("#define ALPHATEST");
  44956. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  44957. alphaTexture.coordinatesIndex === 1) {
  44958. defines.push("#define DIFFUSEUV2");
  44959. uv2 = true;
  44960. }
  44961. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44962. defines.push("#define DIFFUSEUV1");
  44963. uv1 = true;
  44964. }
  44965. }
  44966. }
  44967. // Emissive
  44968. if (emissiveTexture) {
  44969. defines.push("#define EMISSIVE");
  44970. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  44971. emissiveTexture.coordinatesIndex === 1) {
  44972. defines.push("#define EMISSIVEUV2");
  44973. uv2 = true;
  44974. }
  44975. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44976. defines.push("#define EMISSIVEUV1");
  44977. uv1 = true;
  44978. }
  44979. }
  44980. if (uv1) {
  44981. attribs.push(BABYLON.VertexBuffer.UVKind);
  44982. defines.push("#define UV1");
  44983. }
  44984. if (uv2) {
  44985. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44986. defines.push("#define UV2");
  44987. }
  44988. // Bones
  44989. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44990. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44991. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44992. if (mesh.numBoneInfluencers > 4) {
  44993. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44994. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44995. }
  44996. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44997. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44998. }
  44999. else {
  45000. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45001. }
  45002. // Instances
  45003. if (useInstances) {
  45004. defines.push("#define INSTANCES");
  45005. attribs.push("world0");
  45006. attribs.push("world1");
  45007. attribs.push("world2");
  45008. attribs.push("world3");
  45009. }
  45010. // Get correct effect
  45011. var join = defines.join("\n");
  45012. if (this._cachedDefines !== join) {
  45013. this._cachedDefines = join;
  45014. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  45015. }
  45016. return this._glowMapGenerationEffect.isReady();
  45017. };
  45018. /**
  45019. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  45020. */
  45021. HighlightLayer.prototype.render = function () {
  45022. var currentEffect = this._glowMapMergeEffect;
  45023. // Check
  45024. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  45025. return;
  45026. var engine = this._scene.getEngine();
  45027. this.onBeforeComposeObservable.notifyObservers(this);
  45028. // Render
  45029. engine.enableEffect(currentEffect);
  45030. engine.setState(false);
  45031. // Cache
  45032. var previousStencilBuffer = engine.getStencilBuffer();
  45033. var previousStencilFunction = engine.getStencilFunction();
  45034. var previousStencilMask = engine.getStencilMask();
  45035. var previousAlphaMode = engine.getAlphaMode();
  45036. // Texture
  45037. currentEffect.setTexture("textureSampler", this._blurTexture);
  45038. // VBOs
  45039. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  45040. // Draw order
  45041. engine.setAlphaMode(this._options.alphaBlendingMode);
  45042. engine.setStencilMask(0x00);
  45043. engine.setStencilBuffer(true);
  45044. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  45045. if (this.outerGlow) {
  45046. currentEffect.setFloat("offset", 0);
  45047. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  45048. engine.draw(true, 0, 6);
  45049. }
  45050. if (this.innerGlow) {
  45051. currentEffect.setFloat("offset", 1);
  45052. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  45053. engine.draw(true, 0, 6);
  45054. }
  45055. // Restore Cache
  45056. engine.setStencilFunction(previousStencilFunction);
  45057. engine.setStencilMask(previousStencilMask);
  45058. engine.setAlphaMode(previousAlphaMode);
  45059. engine.setStencilBuffer(previousStencilBuffer);
  45060. this.onAfterComposeObservable.notifyObservers(this);
  45061. // Handle size changes.
  45062. var size = this._mainTexture.getSize();
  45063. this.setMainTextureSize();
  45064. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  45065. // Recreate RTT and post processes on size change.
  45066. this.onSizeChangedObservable.notifyObservers(this);
  45067. this.disposeTextureAndPostProcesses();
  45068. this.createTextureAndPostProcesses();
  45069. }
  45070. };
  45071. /**
  45072. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  45073. * @param mesh The mesh to exclude from the highlight layer
  45074. */
  45075. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  45076. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  45077. if (!meshExcluded) {
  45078. this._excludedMeshes[mesh.uniqueId] = {
  45079. mesh: mesh,
  45080. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  45081. mesh.getEngine().setStencilBuffer(false);
  45082. }),
  45083. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  45084. mesh.getEngine().setStencilBuffer(true);
  45085. }),
  45086. };
  45087. }
  45088. };
  45089. /**
  45090. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  45091. * @param mesh The mesh to highlight
  45092. */
  45093. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  45094. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  45095. if (meshExcluded) {
  45096. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  45097. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  45098. }
  45099. this._excludedMeshes[mesh.uniqueId] = undefined;
  45100. };
  45101. /**
  45102. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  45103. * @param mesh The mesh to highlight
  45104. * @param color The color of the highlight
  45105. * @param glowEmissiveOnly Extract the glow from the emissive texture
  45106. */
  45107. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  45108. var _this = this;
  45109. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  45110. var meshHighlight = this._meshes[mesh.uniqueId];
  45111. if (meshHighlight) {
  45112. meshHighlight.color = color;
  45113. }
  45114. else {
  45115. this._meshes[mesh.uniqueId] = {
  45116. mesh: mesh,
  45117. color: color,
  45118. // Lambda required for capture due to Observable this context
  45119. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  45120. if (_this._excludedMeshes[mesh.uniqueId]) {
  45121. _this.defaultStencilReference(mesh);
  45122. }
  45123. else {
  45124. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  45125. }
  45126. }),
  45127. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  45128. glowEmissiveOnly: glowEmissiveOnly
  45129. };
  45130. }
  45131. this._shouldRender = true;
  45132. };
  45133. /**
  45134. * Remove a mesh from the highlight layer in order to make it stop glowing.
  45135. * @param mesh The mesh to highlight
  45136. */
  45137. HighlightLayer.prototype.removeMesh = function (mesh) {
  45138. var meshHighlight = this._meshes[mesh.uniqueId];
  45139. if (meshHighlight) {
  45140. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  45141. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  45142. }
  45143. this._meshes[mesh.uniqueId] = undefined;
  45144. this._shouldRender = false;
  45145. for (var meshHighlightToCheck in this._meshes) {
  45146. if (meshHighlightToCheck) {
  45147. this._shouldRender = true;
  45148. break;
  45149. }
  45150. }
  45151. };
  45152. /**
  45153. * Returns true if the layer contains information to display, otherwise false.
  45154. */
  45155. HighlightLayer.prototype.shouldRender = function () {
  45156. return this.isEnabled && this._shouldRender;
  45157. };
  45158. /**
  45159. * Sets the main texture desired size which is the closest power of two
  45160. * of the engine canvas size.
  45161. */
  45162. HighlightLayer.prototype.setMainTextureSize = function () {
  45163. if (this._options.mainTextureFixedSize) {
  45164. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  45165. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  45166. }
  45167. else {
  45168. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  45169. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  45170. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  45171. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  45172. }
  45173. };
  45174. /**
  45175. * Force the stencil to the normal expected value for none glowing parts
  45176. */
  45177. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  45178. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  45179. };
  45180. /**
  45181. * Dispose only the render target textures and post process.
  45182. */
  45183. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  45184. this._blurTexture.dispose();
  45185. this._mainTexture.dispose();
  45186. this._downSamplePostprocess.dispose();
  45187. this._horizontalBlurPostprocess.dispose();
  45188. this._verticalBlurPostprocess.dispose();
  45189. };
  45190. /**
  45191. * Dispose the highlight layer and free resources.
  45192. */
  45193. HighlightLayer.prototype.dispose = function () {
  45194. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  45195. if (vertexBuffer) {
  45196. vertexBuffer.dispose();
  45197. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  45198. }
  45199. if (this._indexBuffer) {
  45200. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45201. this._indexBuffer = null;
  45202. }
  45203. // Clean textures and post processes
  45204. this.disposeTextureAndPostProcesses();
  45205. // Clean mesh references
  45206. for (var id in this._meshes) {
  45207. var meshHighlight = this._meshes[id];
  45208. if (meshHighlight && meshHighlight.mesh) {
  45209. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  45210. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  45211. }
  45212. }
  45213. this._meshes = null;
  45214. for (var id in this._excludedMeshes) {
  45215. var meshHighlight = this._excludedMeshes[id];
  45216. if (meshHighlight) {
  45217. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  45218. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  45219. }
  45220. }
  45221. this._excludedMeshes = null;
  45222. // Remove from scene
  45223. var index = this._scene.highlightLayers.indexOf(this, 0);
  45224. if (index > -1) {
  45225. this._scene.highlightLayers.splice(index, 1);
  45226. }
  45227. // Callback
  45228. this.onDisposeObservable.notifyObservers(this);
  45229. this.onDisposeObservable.clear();
  45230. this.onBeforeRenderMainTextureObservable.clear();
  45231. this.onBeforeBlurObservable.clear();
  45232. this.onBeforeComposeObservable.clear();
  45233. this.onAfterComposeObservable.clear();
  45234. this.onSizeChangedObservable.clear();
  45235. };
  45236. return HighlightLayer;
  45237. }());
  45238. /**
  45239. * The neutral color used during the preparation of the glow effect.
  45240. * This is black by default as the blend operation is a blend operation.
  45241. */
  45242. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  45243. /**
  45244. * Stencil value used for glowing meshes.
  45245. */
  45246. HighlightLayer.glowingMeshStencilReference = 0x02;
  45247. /**
  45248. * Stencil value used for the other meshes in the scene.
  45249. */
  45250. HighlightLayer.normalMeshStencilReference = 0x01;
  45251. BABYLON.HighlightLayer = HighlightLayer;
  45252. })(BABYLON || (BABYLON = {}));
  45253. //# sourceMappingURL=babylon.highlightlayer.js.map
  45254. var BABYLON;
  45255. (function (BABYLON) {
  45256. var SIMDVector3 = (function () {
  45257. function SIMDVector3() {
  45258. }
  45259. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  45260. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  45261. };
  45262. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  45263. var m = transformation.m;
  45264. var m0 = SIMD.Float32x4.load(m, 0);
  45265. var m1 = SIMD.Float32x4.load(m, 4);
  45266. var m2 = SIMD.Float32x4.load(m, 8);
  45267. var m3 = SIMD.Float32x4.load(m, 12);
  45268. 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));
  45269. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  45270. result.x = SIMD.Float32x4.extractLane(r, 0);
  45271. result.y = SIMD.Float32x4.extractLane(r, 1);
  45272. result.z = SIMD.Float32x4.extractLane(r, 2);
  45273. };
  45274. return SIMDVector3;
  45275. }());
  45276. var SIMDMatrix = (function () {
  45277. function SIMDMatrix() {
  45278. }
  45279. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  45280. var tm = this.m;
  45281. var om = other.m;
  45282. var m0 = SIMD.Float32x4.load(om, 0);
  45283. var m1 = SIMD.Float32x4.load(om, 4);
  45284. var m2 = SIMD.Float32x4.load(om, 8);
  45285. var m3 = SIMD.Float32x4.load(om, 12);
  45286. for (var i = 0; i < 16; i += 4) {
  45287. 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)))));
  45288. }
  45289. return this;
  45290. };
  45291. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  45292. var src = this.m;
  45293. var dest = other.m;
  45294. // Load the 4 rows
  45295. var src0 = SIMD.Float32x4.load(src, 0);
  45296. var src1 = SIMD.Float32x4.load(src, 4);
  45297. var src2 = SIMD.Float32x4.load(src, 8);
  45298. var src3 = SIMD.Float32x4.load(src, 12);
  45299. // Transpose the source matrix. Sort of. Not a true transpose operation
  45300. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  45301. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  45302. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  45303. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  45304. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  45305. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  45306. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  45307. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  45308. // This is a true transposition, but it will lead to an incorrect result
  45309. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  45310. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  45311. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  45312. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  45313. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  45314. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  45315. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  45316. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  45317. // ----
  45318. tmp1 = SIMD.Float32x4.mul(row2, row3);
  45319. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45320. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  45321. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  45322. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45323. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  45324. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  45325. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  45326. // ----
  45327. tmp1 = SIMD.Float32x4.mul(row1, row2);
  45328. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45329. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  45330. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  45331. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45332. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  45333. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  45334. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  45335. // ----
  45336. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  45337. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45338. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  45339. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  45340. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  45341. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45342. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  45343. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  45344. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  45345. // ----
  45346. tmp1 = SIMD.Float32x4.mul(row0, row1);
  45347. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45348. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  45349. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  45350. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45351. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  45352. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  45353. // ----
  45354. tmp1 = SIMD.Float32x4.mul(row0, row3);
  45355. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45356. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  45357. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  45358. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45359. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  45360. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  45361. // ----
  45362. tmp1 = SIMD.Float32x4.mul(row0, row2);
  45363. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45364. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  45365. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  45366. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45367. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  45368. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  45369. // Compute determinant
  45370. var det = SIMD.Float32x4.mul(row0, minor0);
  45371. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  45372. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  45373. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  45374. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  45375. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  45376. // These shuffles aren't necessary if the faulty transposition is done
  45377. // up at the top of this function.
  45378. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  45379. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  45380. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  45381. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  45382. // Compute final values by multiplying with 1/det
  45383. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  45384. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  45385. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  45386. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  45387. return this;
  45388. };
  45389. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  45390. var out = result.m;
  45391. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  45392. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  45393. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  45394. // cc.kmVec3Subtract(f, pCenter, pEye);
  45395. var f = SIMD.Float32x4.sub(center, eye);
  45396. // cc.kmVec3Normalize(f, f);
  45397. var tmp = SIMD.Float32x4.mul(f, f);
  45398. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  45399. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  45400. // cc.kmVec3Assign(up, pUp);
  45401. // cc.kmVec3Normalize(up, up);
  45402. tmp = SIMD.Float32x4.mul(up, up);
  45403. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  45404. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  45405. // cc.kmVec3Cross(s, f, up);
  45406. 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)));
  45407. // cc.kmVec3Normalize(s, s);
  45408. tmp = SIMD.Float32x4.mul(s, s);
  45409. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  45410. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  45411. // cc.kmVec3Cross(u, s, f);
  45412. 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)));
  45413. // cc.kmVec3Normalize(s, s);
  45414. tmp = SIMD.Float32x4.mul(s, s);
  45415. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  45416. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  45417. var zero = SIMD.Float32x4.splat(0.0);
  45418. s = SIMD.Float32x4.neg(s);
  45419. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  45420. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  45421. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  45422. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  45423. 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);
  45424. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  45425. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  45426. 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)))));
  45427. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  45428. 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)))));
  45429. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  45430. 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)))));
  45431. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  45432. 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)))));
  45433. };
  45434. return SIMDMatrix;
  45435. }());
  45436. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  45437. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  45438. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  45439. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  45440. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  45441. var SIMDHelper = (function () {
  45442. function SIMDHelper() {
  45443. }
  45444. Object.defineProperty(SIMDHelper, "IsEnabled", {
  45445. get: function () {
  45446. return SIMDHelper._isEnabled;
  45447. },
  45448. enumerable: true,
  45449. configurable: true
  45450. });
  45451. SIMDHelper.DisableSIMD = function () {
  45452. // Replace functions
  45453. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  45454. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  45455. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  45456. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  45457. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  45458. SIMDHelper._isEnabled = false;
  45459. };
  45460. SIMDHelper.EnableSIMD = function () {
  45461. if (self.SIMD === undefined) {
  45462. return;
  45463. }
  45464. // check if polyfills needed
  45465. if (!self.Math.fround) {
  45466. self.Math.fround = (function (array) { return function (x) {
  45467. return array[0] = x, array[0];
  45468. }; })(new Float32Array(1));
  45469. }
  45470. if (!self.Math.imul) {
  45471. self.Math.imul = function (a, b) {
  45472. var ah = (a >>> 16) & 0xffff;
  45473. var al = a & 0xffff;
  45474. var bh = (b >>> 16) & 0xffff;
  45475. var bl = b & 0xffff;
  45476. // the shift by 0 fixes the sign on the high part
  45477. // the final |0 converts the unsigned value into a signed value
  45478. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  45479. };
  45480. }
  45481. // Replace functions
  45482. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  45483. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  45484. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  45485. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  45486. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  45487. SIMDHelper._isEnabled = true;
  45488. };
  45489. return SIMDHelper;
  45490. }());
  45491. SIMDHelper._isEnabled = false;
  45492. BABYLON.SIMDHelper = SIMDHelper;
  45493. })(BABYLON || (BABYLON = {}));
  45494. //# sourceMappingURL=babylon.math.SIMD.js.map
  45495. var BABYLON;
  45496. (function (BABYLON) {
  45497. /**
  45498. * This class describe a rectangle that were added to the map.
  45499. * You have access to its coordinates either in pixel or normalized (UV)
  45500. */
  45501. var PackedRect = (function () {
  45502. function PackedRect(root, parent, pos, size) {
  45503. this._pos = pos;
  45504. this._size = size;
  45505. this._root = root;
  45506. this._parent = parent;
  45507. this._contentSize = null;
  45508. this._bottomNode = null;
  45509. this._leftNode = null;
  45510. this._initialSize = null;
  45511. this._rightNode = null;
  45512. }
  45513. Object.defineProperty(PackedRect.prototype, "pos", {
  45514. /**
  45515. * @returns the position of this node into the map
  45516. */
  45517. get: function () {
  45518. return this._pos;
  45519. },
  45520. enumerable: true,
  45521. configurable: true
  45522. });
  45523. Object.defineProperty(PackedRect.prototype, "contentSize", {
  45524. /**
  45525. * @returns the size of the rectangle this node handles
  45526. */
  45527. get: function () {
  45528. return this._contentSize;
  45529. },
  45530. enumerable: true,
  45531. configurable: true
  45532. });
  45533. /**
  45534. * Retrieve the inner position (considering the margin) and stores it into the res object
  45535. * @param res must be a valid Vector2 that will contain the inner position after this call
  45536. */
  45537. PackedRect.prototype.getInnerPosToRef = function (res) {
  45538. var m = this._root._margin;
  45539. res.x = this._pos.x + m;
  45540. res.y = this._pos.y + m;
  45541. };
  45542. /**
  45543. * Retrieve the inner size (considering the margin) and stores it into the res object
  45544. * @param res must be a valid Size that will contain the inner size after this call
  45545. */
  45546. PackedRect.prototype.getInnerSizeToRef = function (res) {
  45547. var m = this._root._margin;
  45548. res.width = this._contentSize.width - (m * 2);
  45549. res.height = this._contentSize.height - (m * 2);
  45550. };
  45551. Object.defineProperty(PackedRect.prototype, "UVs", {
  45552. /**
  45553. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  45554. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  45555. */
  45556. get: function () {
  45557. if (!this._contentSize) {
  45558. throw new Error("Can't compute UVs for this object because it's nor allocated");
  45559. }
  45560. return this.getUVsForCustomSize(this._contentSize);
  45561. },
  45562. enumerable: true,
  45563. configurable: true
  45564. });
  45565. /**
  45566. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  45567. * and then using only a part of the PackRect.
  45568. * This method will return the UVs for this part by given the custom size of what you really use
  45569. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  45570. */
  45571. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  45572. var mainWidth = this._root._size.width;
  45573. var mainHeight = this._root._size.height;
  45574. var margin = this._root._margin;
  45575. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  45576. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  45577. var uvs = new Array();
  45578. uvs.push(topLeft);
  45579. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  45580. uvs.push(rightBottom);
  45581. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  45582. return uvs;
  45583. };
  45584. /**
  45585. * Free this rectangle from the map.
  45586. * Call this method when you no longer need the rectangle to be in the map.
  45587. */
  45588. PackedRect.prototype.freeContent = function () {
  45589. if (!this.contentSize) {
  45590. return;
  45591. }
  45592. this._contentSize = null;
  45593. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  45594. this.attemptDefrag();
  45595. };
  45596. Object.defineProperty(PackedRect.prototype, "isUsed", {
  45597. get: function () {
  45598. return this._contentSize != null || this._leftNode != null;
  45599. },
  45600. enumerable: true,
  45601. configurable: true
  45602. });
  45603. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  45604. var node = this.findNode(contentSize);
  45605. // Not enough space...
  45606. if (!node) {
  45607. return null;
  45608. }
  45609. node.splitNode(contentSize);
  45610. return node;
  45611. };
  45612. PackedRect.prototype.findNode = function (size) {
  45613. var resNode = null;
  45614. var margin = this._root._margin * 2;
  45615. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  45616. if (this.isUsed) {
  45617. if (this._leftNode) {
  45618. resNode = this._leftNode.findNode(size);
  45619. }
  45620. if (!resNode && this._rightNode) {
  45621. resNode = this._rightNode.findNode(size);
  45622. }
  45623. if (!resNode && this._bottomNode) {
  45624. resNode = this._bottomNode.findNode(size);
  45625. }
  45626. }
  45627. else if (this._initialSize) {
  45628. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  45629. resNode = this;
  45630. }
  45631. else {
  45632. return null;
  45633. }
  45634. }
  45635. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  45636. resNode = this;
  45637. }
  45638. return resNode;
  45639. };
  45640. PackedRect.prototype.splitNode = function (contentSize) {
  45641. var cs = PackedRect.TpsSize;
  45642. var margin = this._root._margin * 2;
  45643. cs.copyFrom(contentSize);
  45644. cs.width += margin;
  45645. cs.height += margin;
  45646. // 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)
  45647. if (!this._contentSize && this._initialSize) {
  45648. this._contentSize = cs.clone();
  45649. 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));
  45650. return this._leftNode.splitNode(contentSize);
  45651. }
  45652. else {
  45653. this._contentSize = cs.clone();
  45654. this._initialSize = cs.clone();
  45655. if (cs.width !== this._size.width) {
  45656. 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));
  45657. }
  45658. if (cs.height !== this._size.height) {
  45659. 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));
  45660. }
  45661. return this;
  45662. }
  45663. };
  45664. PackedRect.prototype.attemptDefrag = function () {
  45665. if (!this.isUsed && this.isRecursiveFree) {
  45666. this.clearNode();
  45667. if (this._parent) {
  45668. this._parent.attemptDefrag();
  45669. }
  45670. }
  45671. };
  45672. PackedRect.prototype.clearNode = function () {
  45673. this._initialSize = null;
  45674. this._rightNode = null;
  45675. this._bottomNode = null;
  45676. };
  45677. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  45678. get: function () {
  45679. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  45680. },
  45681. enumerable: true,
  45682. configurable: true
  45683. });
  45684. PackedRect.prototype.evalFreeSize = function (size) {
  45685. var levelSize = 0;
  45686. if (!this.isUsed) {
  45687. var margin = this._root._margin;
  45688. var is = this._initialSize;
  45689. if (is) {
  45690. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  45691. }
  45692. else {
  45693. var size_1 = this._size;
  45694. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  45695. }
  45696. }
  45697. if (this._rightNode) {
  45698. levelSize += this._rightNode.evalFreeSize(0);
  45699. }
  45700. if (this._bottomNode) {
  45701. levelSize += this._bottomNode.evalFreeSize(0);
  45702. }
  45703. return levelSize + size;
  45704. };
  45705. return PackedRect;
  45706. }());
  45707. PackedRect.TpsSize = BABYLON.Size.Zero();
  45708. BABYLON.PackedRect = PackedRect;
  45709. /**
  45710. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  45711. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  45712. * 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.
  45713. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  45714. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  45715. */
  45716. var RectPackingMap = (function (_super) {
  45717. __extends(RectPackingMap, _super);
  45718. /**
  45719. * Create an instance of the object with a dimension using the given size
  45720. * @param size The dimension of the rectangle that will contain all the sub ones.
  45721. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  45722. */
  45723. function RectPackingMap(size, margin) {
  45724. if (margin === void 0) { margin = 0; }
  45725. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  45726. _this._margin = margin;
  45727. _this._root = _this;
  45728. return _this;
  45729. }
  45730. /**
  45731. * Add a rectangle, finding the best location to store it into the map
  45732. * @param size the dimension of the rectangle to store
  45733. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  45734. */
  45735. RectPackingMap.prototype.addRect = function (size) {
  45736. var node = this.findAndSplitNode(size);
  45737. return node;
  45738. };
  45739. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  45740. /**
  45741. * Return the current space free normalized between [0;1]
  45742. * @returns {}
  45743. */
  45744. get: function () {
  45745. var freeSize = 0;
  45746. freeSize = this.evalFreeSize(freeSize);
  45747. return freeSize / (this._size.width * this._size.height);
  45748. },
  45749. enumerable: true,
  45750. configurable: true
  45751. });
  45752. return RectPackingMap;
  45753. }(PackedRect));
  45754. BABYLON.RectPackingMap = RectPackingMap;
  45755. })(BABYLON || (BABYLON = {}));
  45756. //# sourceMappingURL=babylon.rectPackingMap.js.map
  45757. var BABYLON;
  45758. (function (BABYLON) {
  45759. var DynamicFloatArrayElementInfo = (function () {
  45760. function DynamicFloatArrayElementInfo() {
  45761. }
  45762. return DynamicFloatArrayElementInfo;
  45763. }());
  45764. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  45765. /**
  45766. * 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.
  45767. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  45768. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  45769. * 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.
  45770. * 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.
  45771. * 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".
  45772. */
  45773. var DynamicFloatArray = (function () {
  45774. /**
  45775. * Construct an instance of the dynamic float array
  45776. * @param stride size of one element in float (i.e. not bytes!)
  45777. * @param initialElementCount the number of available entries at construction
  45778. */
  45779. function DynamicFloatArray(stride, initialElementCount) {
  45780. this.compareValueOffset = null;
  45781. this.sortingAscending = true;
  45782. this._stride = stride;
  45783. this.buffer = new Float32Array(stride * initialElementCount);
  45784. this._lastUsed = 0;
  45785. this._firstFree = 0;
  45786. this._allEntries = new Array(initialElementCount);
  45787. this._freeEntries = new Array(initialElementCount);
  45788. for (var i = 0; i < initialElementCount; i++) {
  45789. var element = new DynamicFloatArrayElementInfo();
  45790. element.offset = i * stride;
  45791. this._allEntries[i] = element;
  45792. this._freeEntries[initialElementCount - i - 1] = element;
  45793. }
  45794. }
  45795. /**
  45796. * Allocate an element in the array.
  45797. * @return the element info instance that contains the offset into the main buffer of the element's location.
  45798. * Beware, this offset may change when you call pack()
  45799. */
  45800. DynamicFloatArray.prototype.allocElement = function () {
  45801. if (this._freeEntries.length === 0) {
  45802. this._growBuffer();
  45803. }
  45804. var el = this._freeEntries.pop();
  45805. this._lastUsed = Math.max(el.offset, this._lastUsed);
  45806. if (el.offset === this._firstFree) {
  45807. if (this._freeEntries.length > 0) {
  45808. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  45809. }
  45810. else {
  45811. this._firstFree += this._stride;
  45812. }
  45813. }
  45814. return el;
  45815. };
  45816. /**
  45817. * Free the element corresponding to the given element info
  45818. * @param elInfo the element that describe the allocated element
  45819. */
  45820. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  45821. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  45822. this._freeEntries.push(elInfo);
  45823. };
  45824. /**
  45825. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  45826. * 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().
  45827. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  45828. */
  45829. DynamicFloatArray.prototype.pack = function () {
  45830. // no free slot? no need to pack
  45831. if (this._freeEntries.length === 0) {
  45832. return this.buffer;
  45833. }
  45834. // If the buffer is already packed the last used will always be lower than the first free
  45835. // 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.
  45836. if (this._lastUsed < this._firstFree) {
  45837. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  45838. return elementsBuffer_1;
  45839. }
  45840. var s = this._stride;
  45841. // 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
  45842. var lastFree = new DynamicFloatArrayElementInfo();
  45843. lastFree.offset = this.totalElementCount * s;
  45844. this._freeEntries.push(lastFree);
  45845. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  45846. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  45847. var firstFreeSlotOffset = sortedFree[0].offset;
  45848. var freeZoneSize = 1;
  45849. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  45850. var prevOffset = sortedFree[0].offset;
  45851. for (var i = 1; i < sortedFree.length; i++) {
  45852. // 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
  45853. if (firstFreeSlotOffset >= occupiedZoneSize) {
  45854. break;
  45855. }
  45856. var curFree = sortedFree[i];
  45857. var curOffset = curFree.offset;
  45858. // Compute the distance between this offset and the previous
  45859. var distance = curOffset - prevOffset;
  45860. // If the distance is the stride size, they are adjacent, it good, move to the next
  45861. if (distance === s) {
  45862. // Free zone is one element bigger
  45863. ++freeZoneSize;
  45864. // as we're about to iterate to the next, the cur becomes the previous...
  45865. prevOffset = curOffset;
  45866. continue;
  45867. }
  45868. // Distance is bigger, which means there's x element between the previous free and this one
  45869. var usedRange = (distance / s) - 1;
  45870. // Two cases the free zone is smaller than the data to move or bigger
  45871. // Copy what can fit in the free zone
  45872. var curMoveOffset = curOffset - s;
  45873. var copyCount = Math.min(freeZoneSize, usedRange);
  45874. for (var j = 0; j < copyCount; j++) {
  45875. var freeI = firstFreeSlotOffset / s;
  45876. var curI = curMoveOffset / s;
  45877. var moveEl = sortedAll[curI];
  45878. this._moveElement(moveEl, firstFreeSlotOffset);
  45879. var replacedEl = sortedAll[freeI];
  45880. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  45881. replacedEl.offset = curMoveOffset;
  45882. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  45883. sortedAll[freeI] = moveEl;
  45884. sortedAll[curI] = replacedEl;
  45885. curMoveOffset -= s;
  45886. firstFreeSlotOffset += s;
  45887. }
  45888. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  45889. if (freeZoneSize <= usedRange) {
  45890. firstFreeSlotOffset = curMoveOffset + s;
  45891. freeZoneSize = 1 + copyCount;
  45892. }
  45893. else {
  45894. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  45895. }
  45896. // as we're about to iterate to the next, the cur becomes the previous...
  45897. prevOffset = curOffset;
  45898. }
  45899. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  45900. this._lastUsed = firstFreeSlotOffset - s;
  45901. this._firstFree = firstFreeSlotOffset;
  45902. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  45903. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  45904. this._allEntries = sortedAll;
  45905. return elementsBuffer;
  45906. };
  45907. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  45908. for (var i = 0; i < this._stride; i++) {
  45909. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  45910. }
  45911. element.offset = destOffset;
  45912. };
  45913. DynamicFloatArray.prototype._growBuffer = function () {
  45914. // Allocate the new buffer with 50% more entries, copy the content of the current one
  45915. var newElCount = Math.floor(this.totalElementCount * 1.5);
  45916. var newBuffer = new Float32Array(newElCount * this._stride);
  45917. newBuffer.set(this.buffer);
  45918. var curCount = this.totalElementCount;
  45919. var addedCount = newElCount - this.totalElementCount;
  45920. for (var i = 0; i < addedCount; i++) {
  45921. var element = new DynamicFloatArrayElementInfo();
  45922. element.offset = (curCount + i) * this.stride;
  45923. this._allEntries.push(element);
  45924. this._freeEntries[addedCount - i - 1] = element;
  45925. }
  45926. this._firstFree = curCount * this.stride;
  45927. this.buffer = newBuffer;
  45928. };
  45929. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  45930. /**
  45931. * Get the total count of entries that can fit in the current buffer
  45932. * @returns the elements count
  45933. */
  45934. get: function () {
  45935. return this._allEntries.length;
  45936. },
  45937. enumerable: true,
  45938. configurable: true
  45939. });
  45940. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  45941. /**
  45942. * Get the count of free entries that can still be allocated without resizing the buffer
  45943. * @returns the free elements count
  45944. */
  45945. get: function () {
  45946. return this._freeEntries.length;
  45947. },
  45948. enumerable: true,
  45949. configurable: true
  45950. });
  45951. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  45952. /**
  45953. * Get the count of allocated elements
  45954. * @returns the allocated elements count
  45955. */
  45956. get: function () {
  45957. return this._allEntries.length - this._freeEntries.length;
  45958. },
  45959. enumerable: true,
  45960. configurable: true
  45961. });
  45962. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  45963. /**
  45964. * Return the size of one element in float
  45965. * @returns the size in float
  45966. */
  45967. get: function () {
  45968. return this._stride;
  45969. },
  45970. enumerable: true,
  45971. configurable: true
  45972. });
  45973. DynamicFloatArray.prototype.sort = function () {
  45974. var _this = this;
  45975. if (!this.compareValueOffset) {
  45976. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  45977. }
  45978. var count = this.usedElementCount;
  45979. // Do we have to (re)create the sort table?
  45980. if (!this._sortTable || this._sortTable.length < count) {
  45981. // 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...
  45982. var newCount = Math.min(this.totalElementCount, count * 2);
  45983. this._sortTable = new Array(newCount);
  45984. }
  45985. if (!this._sortedTable || this._sortedTable.length !== count) {
  45986. this._sortedTable = new Array(count);
  45987. }
  45988. // Because, you know...
  45989. this.pack();
  45990. //let stride = this.stride;
  45991. //for (let i = 0; i < count; i++) {
  45992. // let si = this._sortTable[i];
  45993. // if (!si) {
  45994. // si = new SortInfo();
  45995. // this._sortTable[i] = si;
  45996. // }
  45997. // si.entry = this._allEntries[i];
  45998. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  45999. // si.swapedOffset = null;
  46000. // this._sortedTable[i] = si;
  46001. //}
  46002. var curOffset = 0;
  46003. var stride = this.stride;
  46004. for (var i = 0; i < count; i++, curOffset += stride) {
  46005. var si = this._sortTable[i];
  46006. if (!si) {
  46007. si = new SortInfo();
  46008. this._sortTable[i] = si;
  46009. }
  46010. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  46011. si.offset = curOffset;
  46012. si.swapedOffset = null;
  46013. this._sortedTable[i] = si;
  46014. }
  46015. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  46016. if (this.sortingAscending) {
  46017. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  46018. }
  46019. else {
  46020. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  46021. }
  46022. var swapElements = function (src, dst) {
  46023. for (var i = 0; i < stride; i++) {
  46024. var tps = _this.buffer[dst + i];
  46025. _this.buffer[dst + i] = _this.buffer[src + i];
  46026. _this.buffer[src + i] = tps;
  46027. }
  46028. };
  46029. // 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:
  46030. // 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),
  46031. // and I still want something with a good algorithm complexity.
  46032. // 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,
  46033. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  46034. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  46035. // 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
  46036. // until we find a SortInfo object without a swapedOffset which means we got the right location
  46037. // 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
  46038. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  46039. for (var i = 0; i < count; i++) {
  46040. // Get the element to move
  46041. var sourceSI = this._sortedTable[i];
  46042. var destSI = this._sortTable[i];
  46043. var sourceOff = sourceSI.offset;
  46044. // If the source changed location, find the new one
  46045. if (sourceSI.swapedOffset) {
  46046. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  46047. var curSI = sourceSI;
  46048. while (curSI.swapedOffset) {
  46049. curSI = this._sortTable[curSI.swapedOffset / stride];
  46050. }
  46051. // Finally get the right location
  46052. sourceOff = curSI.offset;
  46053. }
  46054. // Tag the element being replaced with its new location
  46055. destSI.swapedOffset = sourceOff;
  46056. // Swap elements (only if needed)
  46057. if (sourceOff !== destSI.offset) {
  46058. swapElements(sourceOff, destSI.offset);
  46059. }
  46060. // Update the offset in the corresponding DFAE
  46061. //sourceSI.entry.offset = destSI.entry.offset;
  46062. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  46063. }
  46064. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  46065. return true;
  46066. };
  46067. return DynamicFloatArray;
  46068. }());
  46069. BABYLON.DynamicFloatArray = DynamicFloatArray;
  46070. var SortInfo = (function () {
  46071. function SortInfo() {
  46072. this.compareData = this.offset = this.swapedOffset = null;
  46073. }
  46074. return SortInfo;
  46075. }());
  46076. })(BABYLON || (BABYLON = {}));
  46077. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  46078. var BABYLON;
  46079. (function (BABYLON) {
  46080. var MapTexture = (function (_super) {
  46081. __extends(MapTexture, _super);
  46082. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  46083. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46084. if (useMipMap === void 0) { useMipMap = false; }
  46085. if (margin === void 0) { margin = 0; }
  46086. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  46087. _this.name = name;
  46088. _this._size = size;
  46089. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46090. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46091. // Create the rectPackMap that will allocate portion of the texture
  46092. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  46093. // Create the texture that will store the content
  46094. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  46095. return _this;
  46096. }
  46097. /**
  46098. * Allocate a rectangle of a given size in the texture map
  46099. * @param size the size of the rectangle to allocation
  46100. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  46101. */
  46102. MapTexture.prototype.allocateRect = function (size) {
  46103. return this._rectPackingMap.addRect(size);
  46104. };
  46105. /**
  46106. * Free a given rectangle from the texture map
  46107. * @param rectInfo the instance corresponding to the rect to free.
  46108. */
  46109. MapTexture.prototype.freeRect = function (rectInfo) {
  46110. if (rectInfo) {
  46111. rectInfo.freeContent();
  46112. }
  46113. };
  46114. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  46115. /**
  46116. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  46117. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  46118. * @returns {}
  46119. */
  46120. get: function () {
  46121. return this._rectPackingMap.freeSpace;
  46122. },
  46123. enumerable: true,
  46124. configurable: true
  46125. });
  46126. /**
  46127. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  46128. * 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.
  46129. * Don't forget to call unbindTexture when you're done rendering
  46130. * @param rect the zone to render to
  46131. * @param clear true to clear the portion's color/depth data
  46132. */
  46133. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  46134. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  46135. };
  46136. /**
  46137. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  46138. * 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.
  46139. * Don't forget to call unbindTexture when you're done rendering
  46140. * @param pos the position into the texture
  46141. * @param size the portion to fit the clip space to
  46142. * @param clear true to clear the portion's color/depth data
  46143. */
  46144. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  46145. var engine = this.getScene().getEngine();
  46146. engine.bindFramebuffer(this._texture);
  46147. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  46148. if (clear) {
  46149. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  46150. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  46151. }
  46152. };
  46153. /**
  46154. * Unbind the texture map from the rendering engine.
  46155. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  46156. * @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.
  46157. */
  46158. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  46159. // Dump ?
  46160. if (dumpForDebug) {
  46161. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  46162. }
  46163. var engine = this.getScene().getEngine();
  46164. if (this._replacedViewport) {
  46165. engine.setViewport(this._replacedViewport);
  46166. this._replacedViewport = null;
  46167. }
  46168. engine.unBindFramebuffer(this._texture);
  46169. };
  46170. Object.defineProperty(MapTexture.prototype, "canRescale", {
  46171. get: function () {
  46172. return false;
  46173. },
  46174. enumerable: true,
  46175. configurable: true
  46176. });
  46177. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  46178. // Anyway, there's not much point to use this method for this kind of texture I guess
  46179. MapTexture.prototype.clone = function () {
  46180. return null;
  46181. };
  46182. return MapTexture;
  46183. }(BABYLON.Texture));
  46184. BABYLON.MapTexture = MapTexture;
  46185. })(BABYLON || (BABYLON = {}));
  46186. //# sourceMappingURL=babylon.mapTexture.js.map
  46187. var BABYLON;
  46188. (function (BABYLON) {
  46189. var ShaderMaterial = (function (_super) {
  46190. __extends(ShaderMaterial, _super);
  46191. function ShaderMaterial(name, scene, shaderPath, options) {
  46192. var _this = _super.call(this, name, scene) || this;
  46193. _this._textures = {};
  46194. _this._textureArrays = {};
  46195. _this._floats = {};
  46196. _this._floatsArrays = {};
  46197. _this._colors3 = {};
  46198. _this._colors4 = {};
  46199. _this._vectors2 = {};
  46200. _this._vectors3 = {};
  46201. _this._vectors4 = {};
  46202. _this._matrices = {};
  46203. _this._matrices3x3 = {};
  46204. _this._matrices2x2 = {};
  46205. _this._vectors3Arrays = {};
  46206. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46207. _this._shaderPath = shaderPath;
  46208. options.needAlphaBlending = options.needAlphaBlending || false;
  46209. options.needAlphaTesting = options.needAlphaTesting || false;
  46210. options.attributes = options.attributes || ["position", "normal", "uv"];
  46211. options.uniforms = options.uniforms || ["worldViewProjection"];
  46212. options.samplers = options.samplers || [];
  46213. options.defines = options.defines || [];
  46214. _this._options = options;
  46215. return _this;
  46216. }
  46217. ShaderMaterial.prototype.getClassName = function () {
  46218. return "ShaderMaterial";
  46219. };
  46220. ShaderMaterial.prototype.needAlphaBlending = function () {
  46221. return this._options.needAlphaBlending;
  46222. };
  46223. ShaderMaterial.prototype.needAlphaTesting = function () {
  46224. return this._options.needAlphaTesting;
  46225. };
  46226. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46227. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46228. this._options.uniforms.push(uniformName);
  46229. }
  46230. };
  46231. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46232. if (this._options.samplers.indexOf(name) === -1) {
  46233. this._options.samplers.push(name);
  46234. }
  46235. this._textures[name] = texture;
  46236. return this;
  46237. };
  46238. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  46239. if (this._options.samplers.indexOf(name) === -1) {
  46240. this._options.samplers.push(name);
  46241. }
  46242. this._checkUniform(name);
  46243. this._textureArrays[name] = textures;
  46244. return this;
  46245. };
  46246. ShaderMaterial.prototype.setFloat = function (name, value) {
  46247. this._checkUniform(name);
  46248. this._floats[name] = value;
  46249. return this;
  46250. };
  46251. ShaderMaterial.prototype.setFloats = function (name, value) {
  46252. this._checkUniform(name);
  46253. this._floatsArrays[name] = value;
  46254. return this;
  46255. };
  46256. ShaderMaterial.prototype.setColor3 = function (name, value) {
  46257. this._checkUniform(name);
  46258. this._colors3[name] = value;
  46259. return this;
  46260. };
  46261. ShaderMaterial.prototype.setColor4 = function (name, value) {
  46262. this._checkUniform(name);
  46263. this._colors4[name] = value;
  46264. return this;
  46265. };
  46266. ShaderMaterial.prototype.setVector2 = function (name, value) {
  46267. this._checkUniform(name);
  46268. this._vectors2[name] = value;
  46269. return this;
  46270. };
  46271. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46272. this._checkUniform(name);
  46273. this._vectors3[name] = value;
  46274. return this;
  46275. };
  46276. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46277. this._checkUniform(name);
  46278. this._vectors4[name] = value;
  46279. return this;
  46280. };
  46281. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46282. this._checkUniform(name);
  46283. this._matrices[name] = value;
  46284. return this;
  46285. };
  46286. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46287. this._checkUniform(name);
  46288. this._matrices3x3[name] = value;
  46289. return this;
  46290. };
  46291. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46292. this._checkUniform(name);
  46293. this._matrices2x2[name] = value;
  46294. return this;
  46295. };
  46296. ShaderMaterial.prototype.setArray3 = function (name, value) {
  46297. this._checkUniform(name);
  46298. this._vectors3Arrays[name] = value;
  46299. return this;
  46300. };
  46301. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  46302. if (!mesh) {
  46303. return true;
  46304. }
  46305. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  46306. return false;
  46307. }
  46308. return false;
  46309. };
  46310. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46311. var scene = this.getScene();
  46312. var engine = scene.getEngine();
  46313. if (!this.checkReadyOnEveryCall) {
  46314. if (this._renderId === scene.getRenderId()) {
  46315. if (this._checkCache(scene, mesh, useInstances)) {
  46316. return true;
  46317. }
  46318. }
  46319. }
  46320. // Instances
  46321. var defines = [];
  46322. var fallbacks = new BABYLON.EffectFallbacks();
  46323. if (useInstances) {
  46324. defines.push("#define INSTANCES");
  46325. }
  46326. for (var index = 0; index < this._options.defines.length; index++) {
  46327. defines.push(this._options.defines[index]);
  46328. }
  46329. // Bones
  46330. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  46331. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46332. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46333. fallbacks.addCPUSkinningFallback(0, mesh);
  46334. }
  46335. // Textures
  46336. for (var name in this._textures) {
  46337. if (!this._textures[name].isReady()) {
  46338. return false;
  46339. }
  46340. }
  46341. // Alpha test
  46342. if (engine.getAlphaTesting()) {
  46343. defines.push("#define ALPHATEST");
  46344. }
  46345. var previousEffect = this._effect;
  46346. var join = defines.join("\n");
  46347. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  46348. if (!this._effect.isReady()) {
  46349. return false;
  46350. }
  46351. if (previousEffect !== this._effect) {
  46352. scene.resetCachedMaterial();
  46353. }
  46354. this._renderId = scene.getRenderId();
  46355. return true;
  46356. };
  46357. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46358. var scene = this.getScene();
  46359. if (this._options.uniforms.indexOf("world") !== -1) {
  46360. this._effect.setMatrix("world", world);
  46361. }
  46362. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46363. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46364. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46365. }
  46366. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46367. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46368. }
  46369. };
  46370. ShaderMaterial.prototype.bind = function (world, mesh) {
  46371. // Std values
  46372. this.bindOnlyWorldMatrix(world);
  46373. if (this.getScene().getCachedMaterial() !== this) {
  46374. if (this._options.uniforms.indexOf("view") !== -1) {
  46375. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46376. }
  46377. if (this._options.uniforms.indexOf("projection") !== -1) {
  46378. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46379. }
  46380. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46381. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46382. }
  46383. // Bones
  46384. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46385. var name;
  46386. // Texture
  46387. for (name in this._textures) {
  46388. this._effect.setTexture(name, this._textures[name]);
  46389. }
  46390. // Texture arrays
  46391. for (name in this._textureArrays) {
  46392. this._effect.setTextureArray(name, this._textureArrays[name]);
  46393. }
  46394. // Float
  46395. for (name in this._floats) {
  46396. this._effect.setFloat(name, this._floats[name]);
  46397. }
  46398. // Float s
  46399. for (name in this._floatsArrays) {
  46400. this._effect.setArray(name, this._floatsArrays[name]);
  46401. }
  46402. // Color3
  46403. for (name in this._colors3) {
  46404. this._effect.setColor3(name, this._colors3[name]);
  46405. }
  46406. // Color4
  46407. for (name in this._colors4) {
  46408. var color = this._colors4[name];
  46409. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46410. }
  46411. // Vector2
  46412. for (name in this._vectors2) {
  46413. this._effect.setVector2(name, this._vectors2[name]);
  46414. }
  46415. // Vector3
  46416. for (name in this._vectors3) {
  46417. this._effect.setVector3(name, this._vectors3[name]);
  46418. }
  46419. // Vector4
  46420. for (name in this._vectors4) {
  46421. this._effect.setVector4(name, this._vectors4[name]);
  46422. }
  46423. // Matrix
  46424. for (name in this._matrices) {
  46425. this._effect.setMatrix(name, this._matrices[name]);
  46426. }
  46427. // Matrix 3x3
  46428. for (name in this._matrices3x3) {
  46429. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  46430. }
  46431. // Matrix 2x2
  46432. for (name in this._matrices2x2) {
  46433. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  46434. }
  46435. // Vector3Array
  46436. for (name in this._vectors3Arrays) {
  46437. this._effect.setArray3(name, this._vectors3Arrays[name]);
  46438. }
  46439. }
  46440. _super.prototype.bind.call(this, world, mesh);
  46441. };
  46442. ShaderMaterial.prototype.clone = function (name) {
  46443. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  46444. return newShaderMaterial;
  46445. };
  46446. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46447. if (forceDisposeTextures) {
  46448. var name;
  46449. for (name in this._textures) {
  46450. this._textures[name].dispose();
  46451. }
  46452. for (name in this._textureArrays) {
  46453. var array = this._textureArrays[name];
  46454. for (var index = 0; index < array.length; index++) {
  46455. array[index].dispose();
  46456. }
  46457. }
  46458. }
  46459. this._textures = {};
  46460. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46461. };
  46462. ShaderMaterial.prototype.serialize = function () {
  46463. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46464. serializationObject.customType = "BABYLON.ShaderMaterial";
  46465. serializationObject.options = this._options;
  46466. serializationObject.shaderPath = this._shaderPath;
  46467. var name;
  46468. // Texture
  46469. serializationObject.textures = {};
  46470. for (name in this._textures) {
  46471. serializationObject.textures[name] = this._textures[name].serialize();
  46472. }
  46473. // Texture arrays
  46474. serializationObject.textureArrays = {};
  46475. for (name in this._textureArrays) {
  46476. serializationObject.textureArrays[name] = [];
  46477. var array = this._textureArrays[name];
  46478. for (var index = 0; index < array.length; index++) {
  46479. serializationObject.textureArrays[name].push(array[index].serialize());
  46480. }
  46481. }
  46482. // Float
  46483. serializationObject.floats = {};
  46484. for (name in this._floats) {
  46485. serializationObject.floats[name] = this._floats[name];
  46486. }
  46487. // Float s
  46488. serializationObject.floatArrays = {};
  46489. for (name in this._floatsArrays) {
  46490. serializationObject.floatArrays[name] = this._floatsArrays[name];
  46491. }
  46492. // Color3
  46493. serializationObject.colors3 = {};
  46494. for (name in this._colors3) {
  46495. serializationObject.colors3[name] = this._colors3[name].asArray();
  46496. }
  46497. // Color4
  46498. serializationObject.colors4 = {};
  46499. for (name in this._colors4) {
  46500. serializationObject.colors4[name] = this._colors4[name].asArray();
  46501. }
  46502. // Vector2
  46503. serializationObject.vectors2 = {};
  46504. for (name in this._vectors2) {
  46505. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  46506. }
  46507. // Vector3
  46508. serializationObject.vectors3 = {};
  46509. for (name in this._vectors3) {
  46510. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  46511. }
  46512. // Vector4
  46513. serializationObject.vectors4 = {};
  46514. for (name in this._vectors4) {
  46515. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  46516. }
  46517. // Matrix
  46518. serializationObject.matrices = {};
  46519. for (name in this._matrices) {
  46520. serializationObject.matrices[name] = this._matrices[name].asArray();
  46521. }
  46522. // Matrix 3x3
  46523. serializationObject.matrices3x3 = {};
  46524. for (name in this._matrices3x3) {
  46525. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  46526. }
  46527. // Matrix 2x2
  46528. serializationObject.matrices2x2 = {};
  46529. for (name in this._matrices2x2) {
  46530. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  46531. }
  46532. // Vector3Array
  46533. serializationObject.vectors3Arrays = {};
  46534. for (name in this._vectors3Arrays) {
  46535. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  46536. }
  46537. return serializationObject;
  46538. };
  46539. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  46540. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  46541. var name;
  46542. // Texture
  46543. for (name in source.textures) {
  46544. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  46545. }
  46546. // Texture arrays
  46547. for (name in source.textureArrays) {
  46548. var array = source.textureArrays[name];
  46549. var textureArray = new Array();
  46550. for (var index = 0; index < array.length; index++) {
  46551. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  46552. }
  46553. material.setTextureArray(name, textureArray);
  46554. }
  46555. // Float
  46556. for (name in source.floats) {
  46557. material.setFloat(name, source.floats[name]);
  46558. }
  46559. // Float s
  46560. for (name in source.floatsArrays) {
  46561. material.setFloats(name, source.floatsArrays[name]);
  46562. }
  46563. // Color3
  46564. for (name in source.colors3) {
  46565. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  46566. }
  46567. // Color4
  46568. for (name in source.colors4) {
  46569. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  46570. }
  46571. // Vector2
  46572. for (name in source.vectors2) {
  46573. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  46574. }
  46575. // Vector3
  46576. for (name in source.vectors3) {
  46577. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  46578. }
  46579. // Vector4
  46580. for (name in source.vectors4) {
  46581. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  46582. }
  46583. // Matrix
  46584. for (name in source.matrices) {
  46585. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  46586. }
  46587. // Matrix 3x3
  46588. for (name in source.matrices3x3) {
  46589. material.setMatrix3x3(name, source.matrices3x3[name]);
  46590. }
  46591. // Matrix 2x2
  46592. for (name in source.matrices2x2) {
  46593. material.setMatrix2x2(name, source.matrices2x2[name]);
  46594. }
  46595. // Vector3Array
  46596. for (name in source.vectors3Arrays) {
  46597. material.setArray3(name, source.vectors3Arrays[name]);
  46598. }
  46599. return material;
  46600. };
  46601. return ShaderMaterial;
  46602. }(BABYLON.Material));
  46603. BABYLON.ShaderMaterial = ShaderMaterial;
  46604. })(BABYLON || (BABYLON = {}));
  46605. //# sourceMappingURL=babylon.shaderMaterial.js.map
  46606. var BABYLON;
  46607. (function (BABYLON) {
  46608. var Internals;
  46609. (function (Internals) {
  46610. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  46611. // All values and structures referenced from:
  46612. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  46613. var DDS_MAGIC = 0x20534444;
  46614. 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;
  46615. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  46616. 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;
  46617. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  46618. function FourCCToInt32(value) {
  46619. return value.charCodeAt(0) +
  46620. (value.charCodeAt(1) << 8) +
  46621. (value.charCodeAt(2) << 16) +
  46622. (value.charCodeAt(3) << 24);
  46623. }
  46624. function Int32ToFourCC(value) {
  46625. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  46626. }
  46627. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  46628. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  46629. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  46630. var headerLengthInt = 31; // The header length in 32 bit ints
  46631. // Offsets into the header array
  46632. var off_magic = 0;
  46633. var off_size = 1;
  46634. var off_flags = 2;
  46635. var off_height = 3;
  46636. var off_width = 4;
  46637. var off_mipmapCount = 7;
  46638. var off_pfFlags = 20;
  46639. var off_pfFourCC = 21;
  46640. var off_RGBbpp = 22;
  46641. var off_RMask = 23;
  46642. var off_GMask = 24;
  46643. var off_BMask = 25;
  46644. var off_AMask = 26;
  46645. var off_caps1 = 27;
  46646. var off_caps2 = 28;
  46647. ;
  46648. var DDSTools = (function () {
  46649. function DDSTools() {
  46650. }
  46651. DDSTools.GetDDSInfo = function (arrayBuffer) {
  46652. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  46653. var mipmapCount = 1;
  46654. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  46655. mipmapCount = Math.max(1, header[off_mipmapCount]);
  46656. }
  46657. return {
  46658. width: header[off_width],
  46659. height: header[off_height],
  46660. mipmapCount: mipmapCount,
  46661. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  46662. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  46663. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  46664. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  46665. };
  46666. };
  46667. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  46668. var byteArray = new Uint8Array(dataLength);
  46669. var srcData = new Uint8Array(arrayBuffer);
  46670. var index = 0;
  46671. for (var y = height - 1; y >= 0; y--) {
  46672. for (var x = 0; x < width; x++) {
  46673. var srcPos = dataOffset + (x + y * width) * 4;
  46674. byteArray[index + 2] = srcData[srcPos];
  46675. byteArray[index + 1] = srcData[srcPos + 1];
  46676. byteArray[index] = srcData[srcPos + 2];
  46677. byteArray[index + 3] = srcData[srcPos + 3];
  46678. index += 4;
  46679. }
  46680. }
  46681. return byteArray;
  46682. };
  46683. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  46684. var byteArray = new Uint8Array(dataLength);
  46685. var srcData = new Uint8Array(arrayBuffer);
  46686. var index = 0;
  46687. for (var y = height - 1; y >= 0; y--) {
  46688. for (var x = 0; x < width; x++) {
  46689. var srcPos = dataOffset + (x + y * width) * 3;
  46690. byteArray[index + 2] = srcData[srcPos];
  46691. byteArray[index + 1] = srcData[srcPos + 1];
  46692. byteArray[index] = srcData[srcPos + 2];
  46693. index += 3;
  46694. }
  46695. }
  46696. return byteArray;
  46697. };
  46698. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  46699. var byteArray = new Uint8Array(dataLength);
  46700. var srcData = new Uint8Array(arrayBuffer);
  46701. var index = 0;
  46702. for (var y = height - 1; y >= 0; y--) {
  46703. for (var x = 0; x < width; x++) {
  46704. var srcPos = dataOffset + (x + y * width);
  46705. byteArray[index] = srcData[srcPos];
  46706. index++;
  46707. }
  46708. }
  46709. return byteArray;
  46710. };
  46711. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  46712. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  46713. if (header[off_magic] != DDS_MAGIC) {
  46714. BABYLON.Tools.Error("Invalid magic number in DDS header");
  46715. return;
  46716. }
  46717. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  46718. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  46719. return;
  46720. }
  46721. if (info.isFourCC) {
  46722. fourCC = header[off_pfFourCC];
  46723. switch (fourCC) {
  46724. case FOURCC_DXT1:
  46725. blockBytes = 8;
  46726. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  46727. break;
  46728. case FOURCC_DXT3:
  46729. blockBytes = 16;
  46730. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  46731. break;
  46732. case FOURCC_DXT5:
  46733. blockBytes = 16;
  46734. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  46735. break;
  46736. default:
  46737. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  46738. return;
  46739. }
  46740. }
  46741. mipmapCount = 1;
  46742. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  46743. mipmapCount = Math.max(1, header[off_mipmapCount]);
  46744. }
  46745. var bpp = header[off_RGBbpp];
  46746. for (var face = 0; face < faces; face++) {
  46747. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  46748. width = header[off_width];
  46749. height = header[off_height];
  46750. dataOffset = header[off_size] + 4;
  46751. for (i = 0; i < mipmapCount; ++i) {
  46752. if (info.isRGB) {
  46753. if (bpp === 24) {
  46754. dataLength = width * height * 3;
  46755. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  46756. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  46757. }
  46758. else {
  46759. dataLength = width * height * 4;
  46760. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  46761. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  46762. }
  46763. }
  46764. else if (info.isLuminance) {
  46765. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  46766. var unpaddedRowSize = width;
  46767. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  46768. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  46769. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  46770. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  46771. }
  46772. else {
  46773. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  46774. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  46775. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  46776. }
  46777. dataOffset += dataLength;
  46778. width *= 0.5;
  46779. height *= 0.5;
  46780. width = Math.max(1.0, width);
  46781. height = Math.max(1.0, height);
  46782. }
  46783. }
  46784. };
  46785. return DDSTools;
  46786. }());
  46787. Internals.DDSTools = DDSTools;
  46788. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46789. })(BABYLON || (BABYLON = {}));
  46790. //# sourceMappingURL=babylon.tools.dds.js.map
  46791. var BABYLON;
  46792. (function (BABYLON) {
  46793. var Internals;
  46794. (function (Internals) {
  46795. /**
  46796. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  46797. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  46798. */
  46799. var KhronosTextureContainer = (function () {
  46800. /**
  46801. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  46802. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  46803. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  46804. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  46805. */
  46806. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  46807. this.arrayBuffer = arrayBuffer;
  46808. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  46809. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  46810. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  46811. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  46812. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  46813. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  46814. BABYLON.Tools.Error("texture missing KTX identifier");
  46815. return;
  46816. }
  46817. // load the reset of the header in native 32 bit int
  46818. var header = new Int32Array(this.arrayBuffer, 12, 13);
  46819. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  46820. var oppositeEndianess = header[0] === 0x01020304;
  46821. // read all the header elements in order they exist in the file, without modification (sans endainness)
  46822. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  46823. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  46824. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  46825. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  46826. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  46827. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  46828. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  46829. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  46830. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  46831. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  46832. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  46833. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  46834. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  46835. if (this.glType !== 0) {
  46836. BABYLON.Tools.Error("only compressed formats currently supported");
  46837. return;
  46838. }
  46839. else {
  46840. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  46841. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  46842. }
  46843. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  46844. BABYLON.Tools.Error("only 2D textures currently supported");
  46845. return;
  46846. }
  46847. if (this.numberOfArrayElements !== 0) {
  46848. BABYLON.Tools.Error("texture arrays not currently supported");
  46849. return;
  46850. }
  46851. if (this.numberOfFaces !== facesExpected) {
  46852. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  46853. return;
  46854. }
  46855. // we now have a completely validated file, so could use existence of loadType as success
  46856. // would need to make this more elaborate & adjust checks above to support more than one load type
  46857. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  46858. }
  46859. // not as fast hardware based, but will probably never need to use
  46860. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  46861. return ((val & 0xFF) << 24)
  46862. | ((val & 0xFF00) << 8)
  46863. | ((val >> 8) & 0xFF00)
  46864. | ((val >> 24) & 0xFF);
  46865. };
  46866. /**
  46867. * It is assumed that the texture has already been created & is currently bound
  46868. */
  46869. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  46870. switch (this.loadType) {
  46871. case KhronosTextureContainer.COMPRESSED_2D:
  46872. this._upload2DCompressedLevels(gl, loadMipmaps);
  46873. break;
  46874. case KhronosTextureContainer.TEX_2D:
  46875. case KhronosTextureContainer.COMPRESSED_3D:
  46876. case KhronosTextureContainer.TEX_3D:
  46877. }
  46878. };
  46879. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  46880. // initialize width & height for level 1
  46881. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  46882. var width = this.pixelWidth;
  46883. var height = this.pixelHeight;
  46884. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  46885. for (var level = 0; level < mipmapCount; level++) {
  46886. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  46887. for (var face = 0; face < this.numberOfFaces; face++) {
  46888. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  46889. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  46890. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  46891. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  46892. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  46893. }
  46894. width = Math.max(1.0, width * 0.5);
  46895. height = Math.max(1.0, height * 0.5);
  46896. }
  46897. };
  46898. return KhronosTextureContainer;
  46899. }());
  46900. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  46901. // load types
  46902. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  46903. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  46904. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  46905. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  46906. Internals.KhronosTextureContainer = KhronosTextureContainer;
  46907. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46908. })(BABYLON || (BABYLON = {}));
  46909. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  46910. var BABYLON;
  46911. (function (BABYLON) {
  46912. var CannonJSPlugin = (function () {
  46913. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  46914. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  46915. if (iterations === void 0) { iterations = 10; }
  46916. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  46917. this.name = "CannonJSPlugin";
  46918. this._physicsMaterials = [];
  46919. this._fixedTimeStep = 1 / 60;
  46920. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  46921. this._currentCollisionGroup = 2;
  46922. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  46923. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  46924. this._tmpPosition = BABYLON.Vector3.Zero();
  46925. this._tmpQuaternion = new BABYLON.Quaternion();
  46926. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  46927. this._tmpDeltaRotation = new BABYLON.Quaternion();
  46928. this._tmpUnityRotation = new BABYLON.Quaternion();
  46929. if (!this.isSupported()) {
  46930. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  46931. return;
  46932. }
  46933. this.world = new CANNON.World();
  46934. this.world.broadphase = new CANNON.NaiveBroadphase();
  46935. this.world.solver.iterations = iterations;
  46936. }
  46937. CannonJSPlugin.prototype.setGravity = function (gravity) {
  46938. this.world.gravity.copy(gravity);
  46939. };
  46940. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  46941. this._fixedTimeStep = timeStep;
  46942. };
  46943. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  46944. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  46945. };
  46946. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  46947. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  46948. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  46949. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  46950. };
  46951. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  46952. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  46953. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  46954. impostor.physicsBody.applyForce(impulse, worldPoint);
  46955. };
  46956. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  46957. //parent-child relationship. Does this impostor has a parent impostor?
  46958. if (impostor.parent) {
  46959. if (impostor.physicsBody) {
  46960. this.removePhysicsBody(impostor);
  46961. //TODO is that needed?
  46962. impostor.forceUpdate();
  46963. }
  46964. return;
  46965. }
  46966. //should a new body be created for this impostor?
  46967. if (impostor.isBodyInitRequired()) {
  46968. var shape = this._createShape(impostor);
  46969. //unregister events, if body is being changed
  46970. var oldBody = impostor.physicsBody;
  46971. if (oldBody) {
  46972. this.removePhysicsBody(impostor);
  46973. }
  46974. //create the body and material
  46975. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  46976. var bodyCreationObject = {
  46977. mass: impostor.getParam("mass"),
  46978. material: material
  46979. };
  46980. // A simple extend, in case native options were used.
  46981. var nativeOptions = impostor.getParam("nativeOptions");
  46982. for (var key in nativeOptions) {
  46983. if (nativeOptions.hasOwnProperty(key)) {
  46984. bodyCreationObject[key] = nativeOptions[key];
  46985. }
  46986. }
  46987. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  46988. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  46989. this.world.addEventListener("preStep", impostor.beforeStep);
  46990. this.world.addEventListener("postStep", impostor.afterStep);
  46991. impostor.physicsBody.addShape(shape);
  46992. this.world.add(impostor.physicsBody);
  46993. //try to keep the body moving in the right direction by taking old properties.
  46994. //Should be tested!
  46995. if (oldBody) {
  46996. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  46997. impostor.physicsBody[param].copy(oldBody[param]);
  46998. });
  46999. }
  47000. this._processChildMeshes(impostor);
  47001. }
  47002. //now update the body's transformation
  47003. this._updatePhysicsBodyTransformation(impostor);
  47004. };
  47005. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  47006. var _this = this;
  47007. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  47008. if (meshChildren.length) {
  47009. var processMesh = function (localPosition, mesh) {
  47010. var childImpostor = mesh.getPhysicsImpostor();
  47011. if (childImpostor) {
  47012. var parent = childImpostor.parent;
  47013. if (parent !== mainImpostor) {
  47014. var localPosition = mesh.position;
  47015. if (childImpostor.physicsBody) {
  47016. _this.removePhysicsBody(childImpostor);
  47017. childImpostor.physicsBody = null;
  47018. }
  47019. childImpostor.parent = mainImpostor;
  47020. childImpostor.resetUpdateFlags();
  47021. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  47022. //Add the mass of the children.
  47023. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  47024. }
  47025. }
  47026. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  47027. };
  47028. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  47029. }
  47030. };
  47031. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  47032. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  47033. this.world.removeEventListener("preStep", impostor.beforeStep);
  47034. this.world.removeEventListener("postStep", impostor.afterStep);
  47035. this.world.remove(impostor.physicsBody);
  47036. };
  47037. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  47038. var mainBody = impostorJoint.mainImpostor.physicsBody;
  47039. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  47040. if (!mainBody || !connectedBody) {
  47041. return;
  47042. }
  47043. var constraint;
  47044. var jointData = impostorJoint.joint.jointData;
  47045. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  47046. var constraintData = {
  47047. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  47048. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  47049. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  47050. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  47051. maxForce: jointData.nativeParams.maxForce,
  47052. collideConnected: !!jointData.collision
  47053. };
  47054. switch (impostorJoint.joint.type) {
  47055. case BABYLON.PhysicsJoint.HingeJoint:
  47056. case BABYLON.PhysicsJoint.Hinge2Joint:
  47057. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  47058. break;
  47059. case BABYLON.PhysicsJoint.DistanceJoint:
  47060. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  47061. break;
  47062. case BABYLON.PhysicsJoint.SpringJoint:
  47063. var springData = jointData;
  47064. constraint = new CANNON.Spring(mainBody, connectedBody, {
  47065. restLength: springData.length,
  47066. stiffness: springData.stiffness,
  47067. damping: springData.damping,
  47068. localAnchorA: constraintData.pivotA,
  47069. localAnchorB: constraintData.pivotB
  47070. });
  47071. break;
  47072. case BABYLON.PhysicsJoint.LockJoint:
  47073. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  47074. break;
  47075. case BABYLON.PhysicsJoint.PointToPointJoint:
  47076. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  47077. default:
  47078. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  47079. break;
  47080. }
  47081. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  47082. constraint.collideConnected = !!jointData.collision;
  47083. impostorJoint.joint.physicsJoint = constraint;
  47084. //don't add spring as constraint, as it is not one.
  47085. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  47086. this.world.addConstraint(constraint);
  47087. }
  47088. else {
  47089. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  47090. constraint.applyForce();
  47091. });
  47092. }
  47093. };
  47094. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  47095. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  47096. };
  47097. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  47098. var index;
  47099. var mat;
  47100. for (index = 0; index < this._physicsMaterials.length; index++) {
  47101. mat = this._physicsMaterials[index];
  47102. if (mat.friction === friction && mat.restitution === restitution) {
  47103. return mat;
  47104. }
  47105. }
  47106. var currentMat = new CANNON.Material(name);
  47107. currentMat.friction = friction;
  47108. currentMat.restitution = restitution;
  47109. this._physicsMaterials.push(currentMat);
  47110. return currentMat;
  47111. };
  47112. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  47113. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  47114. };
  47115. CannonJSPlugin.prototype._createShape = function (impostor) {
  47116. var object = impostor.object;
  47117. var returnValue;
  47118. var extendSize = impostor.getObjectExtendSize();
  47119. switch (impostor.type) {
  47120. case BABYLON.PhysicsImpostor.SphereImpostor:
  47121. var radiusX = extendSize.x;
  47122. var radiusY = extendSize.y;
  47123. var radiusZ = extendSize.z;
  47124. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  47125. break;
  47126. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  47127. case BABYLON.PhysicsImpostor.CylinderImpostor:
  47128. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  47129. break;
  47130. case BABYLON.PhysicsImpostor.BoxImpostor:
  47131. var box = extendSize.scale(0.5);
  47132. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  47133. break;
  47134. case BABYLON.PhysicsImpostor.PlaneImpostor:
  47135. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  47136. returnValue = new CANNON.Plane();
  47137. break;
  47138. case BABYLON.PhysicsImpostor.MeshImpostor:
  47139. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  47140. var rawFaces = object.getIndices ? object.getIndices() : [];
  47141. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  47142. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  47143. break;
  47144. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  47145. returnValue = this._createHeightmap(object);
  47146. break;
  47147. case BABYLON.PhysicsImpostor.ParticleImpostor:
  47148. returnValue = new CANNON.Particle();
  47149. break;
  47150. }
  47151. return returnValue;
  47152. };
  47153. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  47154. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47155. var matrix = [];
  47156. //For now pointDepth will not be used and will be automatically calculated.
  47157. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  47158. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  47159. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  47160. var elementSize = dim * 2 / arraySize;
  47161. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  47162. for (var i = 0; i < pos.length; i = i + 3) {
  47163. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  47164. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  47165. var y = pos[i + 1] + minY;
  47166. if (!matrix[x]) {
  47167. matrix[x] = [];
  47168. }
  47169. if (!matrix[x][z]) {
  47170. matrix[x][z] = y;
  47171. }
  47172. matrix[x][z] = Math.max(y, matrix[x][z]);
  47173. }
  47174. for (var x = 0; x <= arraySize; ++x) {
  47175. if (!matrix[x]) {
  47176. var loc = 1;
  47177. while (!matrix[(x + loc) % arraySize]) {
  47178. loc++;
  47179. }
  47180. matrix[x] = matrix[(x + loc) % arraySize].slice();
  47181. //console.log("missing x", x);
  47182. }
  47183. for (var z = 0; z <= arraySize; ++z) {
  47184. if (!matrix[x][z]) {
  47185. var loc = 1;
  47186. var newValue;
  47187. while (newValue === undefined) {
  47188. newValue = matrix[x][(z + loc++) % arraySize];
  47189. }
  47190. matrix[x][z] = newValue;
  47191. }
  47192. }
  47193. }
  47194. var shape = new CANNON.Heightfield(matrix, {
  47195. elementSize: elementSize
  47196. });
  47197. //For future reference, needed for body transformation
  47198. shape.minY = minY;
  47199. return shape;
  47200. };
  47201. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  47202. var object = impostor.object;
  47203. //make sure it is updated...
  47204. object.computeWorldMatrix && object.computeWorldMatrix(true);
  47205. // The delta between the mesh position and the mesh bounding box center
  47206. var center = impostor.getObjectCenter();
  47207. var extendSize = impostor.getObjectExtendSize();
  47208. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  47209. this._tmpPosition.copyFrom(center);
  47210. var quaternion = object.rotationQuaternion;
  47211. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  47212. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  47213. //-90 DEG in X, precalculated
  47214. quaternion = quaternion.multiply(this._minus90X);
  47215. //Invert! (Precalculated, 90 deg in X)
  47216. //No need to clone. this will never change.
  47217. impostor.setDeltaRotation(this._plus90X);
  47218. }
  47219. //If it is a heightfield, if should be centered.
  47220. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  47221. var mesh = object;
  47222. //calculate the correct body position:
  47223. var rotationQuaternion = mesh.rotationQuaternion;
  47224. mesh.rotationQuaternion = this._tmpUnityRotation;
  47225. mesh.computeWorldMatrix(true);
  47226. //get original center with no rotation
  47227. var c = center.clone();
  47228. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  47229. //rotation is back
  47230. mesh.rotationQuaternion = rotationQuaternion;
  47231. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  47232. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  47233. mesh.setPivotMatrix(p);
  47234. mesh.computeWorldMatrix(true);
  47235. //calculate the translation
  47236. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  47237. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  47238. //add it inverted to the delta
  47239. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  47240. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  47241. mesh.setPivotMatrix(oldPivot);
  47242. mesh.computeWorldMatrix(true);
  47243. }
  47244. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  47245. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  47246. this._tmpPosition.copyFrom(object.position);
  47247. }
  47248. impostor.setDeltaPosition(this._tmpDeltaPosition);
  47249. //Now update the impostor object
  47250. impostor.physicsBody.position.copy(this._tmpPosition);
  47251. impostor.physicsBody.quaternion.copy(quaternion);
  47252. };
  47253. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  47254. impostor.object.position.copyFrom(impostor.physicsBody.position);
  47255. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  47256. };
  47257. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  47258. impostor.physicsBody.position.copy(newPosition);
  47259. impostor.physicsBody.quaternion.copy(newRotation);
  47260. };
  47261. CannonJSPlugin.prototype.isSupported = function () {
  47262. return window.CANNON !== undefined;
  47263. };
  47264. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  47265. impostor.physicsBody.velocity.copy(velocity);
  47266. };
  47267. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  47268. impostor.physicsBody.angularVelocity.copy(velocity);
  47269. };
  47270. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  47271. var v = impostor.physicsBody.velocity;
  47272. if (!v)
  47273. return null;
  47274. return new BABYLON.Vector3(v.x, v.y, v.z);
  47275. };
  47276. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  47277. var v = impostor.physicsBody.angularVelocity;
  47278. if (!v)
  47279. return null;
  47280. return new BABYLON.Vector3(v.x, v.y, v.z);
  47281. };
  47282. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  47283. impostor.physicsBody.mass = mass;
  47284. impostor.physicsBody.updateMassProperties();
  47285. };
  47286. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  47287. impostor.physicsBody.sleep();
  47288. };
  47289. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  47290. impostor.physicsBody.wakeUp();
  47291. };
  47292. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  47293. joint.physicsJoint.distance = maxDistance;
  47294. };
  47295. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  47296. if (!motorIndex) {
  47297. joint.physicsJoint.enableMotor();
  47298. }
  47299. };
  47300. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  47301. if (!motorIndex) {
  47302. joint.physicsJoint.disableMotor();
  47303. }
  47304. };
  47305. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  47306. if (!motorIndex) {
  47307. joint.physicsJoint.enableMotor();
  47308. joint.physicsJoint.setMotorSpeed(speed);
  47309. if (maxForce) {
  47310. this.setLimit(joint, maxForce);
  47311. }
  47312. }
  47313. };
  47314. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  47315. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  47316. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  47317. };
  47318. CannonJSPlugin.prototype.dispose = function () {
  47319. //nothing to do, actually.
  47320. };
  47321. return CannonJSPlugin;
  47322. }());
  47323. BABYLON.CannonJSPlugin = CannonJSPlugin;
  47324. })(BABYLON || (BABYLON = {}));
  47325. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  47326. var BABYLON;
  47327. (function (BABYLON) {
  47328. var OimoJSPlugin = (function () {
  47329. function OimoJSPlugin(iterations) {
  47330. this.name = "OimoJSPlugin";
  47331. this._tmpImpostorsArray = [];
  47332. this._tmpPositionVector = BABYLON.Vector3.Zero();
  47333. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  47334. this.world.worldscale(1);
  47335. this.world.clear();
  47336. //making sure no stats are calculated
  47337. this.world.isNoStat = true;
  47338. }
  47339. OimoJSPlugin.prototype.setGravity = function (gravity) {
  47340. this.world.gravity.copy(gravity);
  47341. };
  47342. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  47343. this.world.timeStep = timeStep;
  47344. };
  47345. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  47346. var _this = this;
  47347. impostors.forEach(function (impostor) {
  47348. impostor.beforeStep();
  47349. });
  47350. this.world.step();
  47351. impostors.forEach(function (impostor) {
  47352. impostor.afterStep();
  47353. //update the ordered impostors array
  47354. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  47355. });
  47356. //check for collisions
  47357. var contact = this.world.contacts;
  47358. while (contact !== null) {
  47359. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  47360. contact = contact.next;
  47361. continue;
  47362. }
  47363. //is this body colliding with any other? get the impostor
  47364. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  47365. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  47366. if (!mainImpostor || !collidingImpostor) {
  47367. contact = contact.next;
  47368. continue;
  47369. }
  47370. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  47371. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  47372. contact = contact.next;
  47373. }
  47374. };
  47375. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  47376. var mass = impostor.physicsBody.massInfo.mass;
  47377. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  47378. };
  47379. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  47380. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  47381. this.applyImpulse(impostor, force, contactPoint);
  47382. };
  47383. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  47384. var _this = this;
  47385. //parent-child relationship. Does this impostor has a parent impostor?
  47386. if (impostor.parent) {
  47387. if (impostor.physicsBody) {
  47388. this.removePhysicsBody(impostor);
  47389. //TODO is that needed?
  47390. impostor.forceUpdate();
  47391. }
  47392. return;
  47393. }
  47394. if (impostor.isBodyInitRequired()) {
  47395. var bodyConfig = {
  47396. name: impostor.uniqueId,
  47397. //Oimo must have mass, also for static objects.
  47398. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  47399. size: [],
  47400. type: [],
  47401. pos: [],
  47402. rot: [],
  47403. move: impostor.getParam("mass") !== 0,
  47404. //Supporting older versions of Oimo
  47405. world: this.world
  47406. };
  47407. var impostors = [impostor];
  47408. var addToArray = function (parent) {
  47409. if (!parent.getChildMeshes)
  47410. return;
  47411. parent.getChildMeshes().forEach(function (m) {
  47412. if (m.physicsImpostor) {
  47413. impostors.push(m.physicsImpostor);
  47414. m.physicsImpostor._init();
  47415. }
  47416. });
  47417. };
  47418. addToArray(impostor.object);
  47419. var checkWithEpsilon_1 = function (value) {
  47420. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  47421. };
  47422. impostors.forEach(function (i) {
  47423. //get the correct bounding box
  47424. var oldQuaternion = i.object.rotationQuaternion;
  47425. var rot = new OIMO.Euler().setFromQuaternion({
  47426. x: impostor.object.rotationQuaternion.x,
  47427. y: impostor.object.rotationQuaternion.y,
  47428. z: impostor.object.rotationQuaternion.z,
  47429. s: impostor.object.rotationQuaternion.w
  47430. });
  47431. var extendSize = i.getObjectExtendSize();
  47432. if (i === impostor) {
  47433. var center = impostor.getObjectCenter();
  47434. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  47435. //Can also use Array.prototype.push.apply
  47436. bodyConfig.pos.push(center.x);
  47437. bodyConfig.pos.push(center.y);
  47438. bodyConfig.pos.push(center.z);
  47439. //tmp solution
  47440. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  47441. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  47442. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  47443. }
  47444. else {
  47445. bodyConfig.pos.push(i.object.position.x);
  47446. bodyConfig.pos.push(i.object.position.y);
  47447. bodyConfig.pos.push(i.object.position.z);
  47448. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  47449. bodyConfig.rot.push(0);
  47450. bodyConfig.rot.push(0);
  47451. bodyConfig.rot.push(0);
  47452. }
  47453. // register mesh
  47454. switch (i.type) {
  47455. case BABYLON.PhysicsImpostor.ParticleImpostor:
  47456. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  47457. case BABYLON.PhysicsImpostor.SphereImpostor:
  47458. var radiusX = extendSize.x;
  47459. var radiusY = extendSize.y;
  47460. var radiusZ = extendSize.z;
  47461. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  47462. bodyConfig.type.push('sphere');
  47463. //due to the way oimo works with compounds, add 3 times
  47464. bodyConfig.size.push(size);
  47465. bodyConfig.size.push(size);
  47466. bodyConfig.size.push(size);
  47467. break;
  47468. case BABYLON.PhysicsImpostor.CylinderImpostor:
  47469. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  47470. var sizeY = checkWithEpsilon_1(extendSize.y);
  47471. bodyConfig.type.push('cylinder');
  47472. bodyConfig.size.push(sizeX);
  47473. bodyConfig.size.push(sizeY);
  47474. //due to the way oimo works with compounds, add one more value.
  47475. bodyConfig.size.push(sizeY);
  47476. break;
  47477. case BABYLON.PhysicsImpostor.PlaneImpostor:
  47478. case BABYLON.PhysicsImpostor.BoxImpostor:
  47479. default:
  47480. var sizeX = checkWithEpsilon_1(extendSize.x);
  47481. var sizeY = checkWithEpsilon_1(extendSize.y);
  47482. var sizeZ = checkWithEpsilon_1(extendSize.z);
  47483. bodyConfig.type.push('box');
  47484. bodyConfig.size.push(sizeX);
  47485. bodyConfig.size.push(sizeY);
  47486. bodyConfig.size.push(sizeZ);
  47487. break;
  47488. }
  47489. //actually not needed, but hey...
  47490. i.object.rotationQuaternion = oldQuaternion;
  47491. });
  47492. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  47493. }
  47494. else {
  47495. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  47496. }
  47497. impostor.setDeltaPosition(this._tmpPositionVector);
  47498. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  47499. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  47500. };
  47501. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  47502. //impostor.physicsBody.dispose();
  47503. //Same as : (older oimo versions)
  47504. this.world.removeRigidBody(impostor.physicsBody);
  47505. };
  47506. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  47507. var mainBody = impostorJoint.mainImpostor.physicsBody;
  47508. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  47509. if (!mainBody || !connectedBody) {
  47510. return;
  47511. }
  47512. var jointData = impostorJoint.joint.jointData;
  47513. var options = jointData.nativeParams || {};
  47514. var type;
  47515. var nativeJointData = {
  47516. body1: mainBody,
  47517. body2: connectedBody,
  47518. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  47519. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  47520. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  47521. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  47522. min: options.min,
  47523. max: options.max,
  47524. collision: options.collision || jointData.collision,
  47525. spring: options.spring,
  47526. //supporting older version of Oimo
  47527. world: this.world
  47528. };
  47529. switch (impostorJoint.joint.type) {
  47530. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  47531. type = "jointBall";
  47532. break;
  47533. case BABYLON.PhysicsJoint.SpringJoint:
  47534. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  47535. var springData = jointData;
  47536. nativeJointData.min = springData.length || nativeJointData.min;
  47537. //Max should also be set, just make sure it is at least min
  47538. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  47539. case BABYLON.PhysicsJoint.DistanceJoint:
  47540. type = "jointDistance";
  47541. nativeJointData.max = jointData.maxDistance;
  47542. break;
  47543. case BABYLON.PhysicsJoint.PrismaticJoint:
  47544. type = "jointPrisme";
  47545. break;
  47546. case BABYLON.PhysicsJoint.SliderJoint:
  47547. type = "jointSlide";
  47548. break;
  47549. case BABYLON.PhysicsJoint.WheelJoint:
  47550. type = "jointWheel";
  47551. break;
  47552. case BABYLON.PhysicsJoint.HingeJoint:
  47553. default:
  47554. type = "jointHinge";
  47555. break;
  47556. }
  47557. nativeJointData.type = type;
  47558. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  47559. };
  47560. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  47561. //Bug in Oimo prevents us from disposing a joint in the playground
  47562. //joint.joint.physicsJoint.dispose();
  47563. //So we will bruteforce it!
  47564. try {
  47565. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  47566. }
  47567. catch (e) {
  47568. BABYLON.Tools.Warn(e);
  47569. }
  47570. };
  47571. OimoJSPlugin.prototype.isSupported = function () {
  47572. return OIMO !== undefined;
  47573. };
  47574. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  47575. if (!impostor.physicsBody.sleeping) {
  47576. //TODO check that
  47577. if (impostor.physicsBody.shapes.next) {
  47578. var parentShape = this._getLastShape(impostor.physicsBody);
  47579. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  47580. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  47581. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  47582. }
  47583. else {
  47584. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  47585. }
  47586. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  47587. impostor.object.rotationQuaternion.normalize();
  47588. }
  47589. };
  47590. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  47591. var body = impostor.physicsBody;
  47592. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  47593. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  47594. body.syncShapes();
  47595. body.awake();
  47596. };
  47597. OimoJSPlugin.prototype._getLastShape = function (body) {
  47598. var lastShape = body.shapes;
  47599. while (lastShape.next) {
  47600. lastShape = lastShape.next;
  47601. }
  47602. return lastShape;
  47603. };
  47604. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  47605. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  47606. };
  47607. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  47608. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  47609. };
  47610. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  47611. var v = impostor.physicsBody.linearVelocity;
  47612. if (!v)
  47613. return null;
  47614. return new BABYLON.Vector3(v.x, v.y, v.z);
  47615. };
  47616. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  47617. var v = impostor.physicsBody.angularVelocity;
  47618. if (!v)
  47619. return null;
  47620. return new BABYLON.Vector3(v.x, v.y, v.z);
  47621. };
  47622. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  47623. var staticBody = mass === 0;
  47624. //this will actually set the body's density and not its mass.
  47625. //But this is how oimo treats the mass variable.
  47626. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  47627. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  47628. };
  47629. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  47630. impostor.physicsBody.sleep();
  47631. };
  47632. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  47633. impostor.physicsBody.awake();
  47634. };
  47635. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  47636. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  47637. if (minDistance !== void 0) {
  47638. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  47639. }
  47640. };
  47641. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  47642. //TODO separate rotational and transational motors.
  47643. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  47644. if (motor) {
  47645. motor.setMotor(speed, maxForce);
  47646. }
  47647. };
  47648. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  47649. //TODO separate rotational and transational motors.
  47650. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  47651. if (motor) {
  47652. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  47653. }
  47654. };
  47655. OimoJSPlugin.prototype.dispose = function () {
  47656. this.world.clear();
  47657. };
  47658. return OimoJSPlugin;
  47659. }());
  47660. BABYLON.OimoJSPlugin = OimoJSPlugin;
  47661. })(BABYLON || (BABYLON = {}));
  47662. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  47663. var BABYLON;
  47664. (function (BABYLON) {
  47665. var DisplayPassPostProcess = (function (_super) {
  47666. __extends(DisplayPassPostProcess, _super);
  47667. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  47668. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  47669. }
  47670. return DisplayPassPostProcess;
  47671. }(BABYLON.PostProcess));
  47672. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  47673. })(BABYLON || (BABYLON = {}));
  47674. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  47675. var BABYLON;
  47676. (function (BABYLON) {
  47677. var SimplificationSettings = (function () {
  47678. function SimplificationSettings(quality, distance, optimizeMesh) {
  47679. this.quality = quality;
  47680. this.distance = distance;
  47681. this.optimizeMesh = optimizeMesh;
  47682. }
  47683. return SimplificationSettings;
  47684. }());
  47685. BABYLON.SimplificationSettings = SimplificationSettings;
  47686. var SimplificationQueue = (function () {
  47687. function SimplificationQueue() {
  47688. this.running = false;
  47689. this._simplificationArray = [];
  47690. }
  47691. SimplificationQueue.prototype.addTask = function (task) {
  47692. this._simplificationArray.push(task);
  47693. };
  47694. SimplificationQueue.prototype.executeNext = function () {
  47695. var task = this._simplificationArray.pop();
  47696. if (task) {
  47697. this.running = true;
  47698. this.runSimplification(task);
  47699. }
  47700. else {
  47701. this.running = false;
  47702. }
  47703. };
  47704. SimplificationQueue.prototype.runSimplification = function (task) {
  47705. var _this = this;
  47706. if (task.parallelProcessing) {
  47707. //parallel simplifier
  47708. task.settings.forEach(function (setting) {
  47709. var simplifier = _this.getSimplifier(task);
  47710. simplifier.simplify(setting, function (newMesh) {
  47711. task.mesh.addLODLevel(setting.distance, newMesh);
  47712. newMesh.isVisible = true;
  47713. //check if it is the last
  47714. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  47715. //all done, run the success callback.
  47716. task.successCallback();
  47717. }
  47718. _this.executeNext();
  47719. });
  47720. });
  47721. }
  47722. else {
  47723. //single simplifier.
  47724. var simplifier = this.getSimplifier(task);
  47725. var runDecimation = function (setting, callback) {
  47726. simplifier.simplify(setting, function (newMesh) {
  47727. task.mesh.addLODLevel(setting.distance, newMesh);
  47728. newMesh.isVisible = true;
  47729. //run the next quality level
  47730. callback();
  47731. });
  47732. };
  47733. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  47734. runDecimation(task.settings[loop.index], function () {
  47735. loop.executeNext();
  47736. });
  47737. }, function () {
  47738. //execution ended, run the success callback.
  47739. if (task.successCallback) {
  47740. task.successCallback();
  47741. }
  47742. _this.executeNext();
  47743. });
  47744. }
  47745. };
  47746. SimplificationQueue.prototype.getSimplifier = function (task) {
  47747. switch (task.simplificationType) {
  47748. case SimplificationType.QUADRATIC:
  47749. default:
  47750. return new QuadraticErrorSimplification(task.mesh);
  47751. }
  47752. };
  47753. return SimplificationQueue;
  47754. }());
  47755. BABYLON.SimplificationQueue = SimplificationQueue;
  47756. /**
  47757. * The implemented types of simplification.
  47758. * At the moment only Quadratic Error Decimation is implemented.
  47759. */
  47760. var SimplificationType;
  47761. (function (SimplificationType) {
  47762. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  47763. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  47764. var DecimationTriangle = (function () {
  47765. function DecimationTriangle(vertices) {
  47766. this.vertices = vertices;
  47767. this.error = new Array(4);
  47768. this.deleted = false;
  47769. this.isDirty = false;
  47770. this.deletePending = false;
  47771. this.borderFactor = 0;
  47772. }
  47773. return DecimationTriangle;
  47774. }());
  47775. BABYLON.DecimationTriangle = DecimationTriangle;
  47776. var DecimationVertex = (function () {
  47777. function DecimationVertex(position, id) {
  47778. this.position = position;
  47779. this.id = id;
  47780. this.isBorder = true;
  47781. this.q = new QuadraticMatrix();
  47782. this.triangleCount = 0;
  47783. this.triangleStart = 0;
  47784. this.originalOffsets = [];
  47785. }
  47786. DecimationVertex.prototype.updatePosition = function (newPosition) {
  47787. this.position.copyFrom(newPosition);
  47788. };
  47789. return DecimationVertex;
  47790. }());
  47791. BABYLON.DecimationVertex = DecimationVertex;
  47792. var QuadraticMatrix = (function () {
  47793. function QuadraticMatrix(data) {
  47794. this.data = new Array(10);
  47795. for (var i = 0; i < 10; ++i) {
  47796. if (data && data[i]) {
  47797. this.data[i] = data[i];
  47798. }
  47799. else {
  47800. this.data[i] = 0;
  47801. }
  47802. }
  47803. }
  47804. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  47805. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  47806. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  47807. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  47808. return det;
  47809. };
  47810. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  47811. for (var i = 0; i < 10; ++i) {
  47812. this.data[i] += matrix.data[i];
  47813. }
  47814. };
  47815. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  47816. for (var i = 0; i < 10; ++i) {
  47817. this.data[i] += data[i];
  47818. }
  47819. };
  47820. QuadraticMatrix.prototype.add = function (matrix) {
  47821. var m = new QuadraticMatrix();
  47822. for (var i = 0; i < 10; ++i) {
  47823. m.data[i] = this.data[i] + matrix.data[i];
  47824. }
  47825. return m;
  47826. };
  47827. QuadraticMatrix.FromData = function (a, b, c, d) {
  47828. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  47829. };
  47830. //returning an array to avoid garbage collection
  47831. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  47832. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  47833. };
  47834. return QuadraticMatrix;
  47835. }());
  47836. BABYLON.QuadraticMatrix = QuadraticMatrix;
  47837. var Reference = (function () {
  47838. function Reference(vertexId, triangleId) {
  47839. this.vertexId = vertexId;
  47840. this.triangleId = triangleId;
  47841. }
  47842. return Reference;
  47843. }());
  47844. BABYLON.Reference = Reference;
  47845. /**
  47846. * An implementation of the Quadratic Error simplification algorithm.
  47847. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  47848. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  47849. * @author RaananW
  47850. */
  47851. var QuadraticErrorSimplification = (function () {
  47852. function QuadraticErrorSimplification(_mesh) {
  47853. this._mesh = _mesh;
  47854. this.initialized = false;
  47855. this.syncIterations = 5000;
  47856. this.aggressiveness = 7;
  47857. this.decimationIterations = 100;
  47858. this.boundingBoxEpsilon = BABYLON.Epsilon;
  47859. }
  47860. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  47861. var _this = this;
  47862. this.initDecimatedMesh();
  47863. //iterating through the submeshes array, one after the other.
  47864. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  47865. _this.initWithMesh(loop.index, function () {
  47866. _this.runDecimation(settings, loop.index, function () {
  47867. loop.executeNext();
  47868. });
  47869. }, settings.optimizeMesh);
  47870. }, function () {
  47871. setTimeout(function () {
  47872. successCallback(_this._reconstructedMesh);
  47873. }, 0);
  47874. });
  47875. };
  47876. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  47877. var _this = this;
  47878. var gCount = 0;
  47879. triangle.vertices.forEach(function (vertex) {
  47880. var count = 0;
  47881. var vPos = vertex.position;
  47882. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  47883. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  47884. ++count;
  47885. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  47886. ++count;
  47887. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  47888. ++count;
  47889. if (count > 1) {
  47890. ++gCount;
  47891. }
  47892. ;
  47893. });
  47894. if (gCount > 1) {
  47895. console.log(triangle, gCount);
  47896. }
  47897. return gCount > 1;
  47898. };
  47899. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  47900. var _this = this;
  47901. var targetCount = ~~(this.triangles.length * settings.quality);
  47902. var deletedTriangles = 0;
  47903. var triangleCount = this.triangles.length;
  47904. var iterationFunction = function (iteration, callback) {
  47905. setTimeout(function () {
  47906. if (iteration % 5 === 0) {
  47907. _this.updateMesh(iteration === 0);
  47908. }
  47909. for (var i = 0; i < _this.triangles.length; ++i) {
  47910. _this.triangles[i].isDirty = false;
  47911. }
  47912. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  47913. var trianglesIterator = function (i) {
  47914. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  47915. var t = _this.triangles[tIdx];
  47916. if (!t)
  47917. return;
  47918. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  47919. return;
  47920. }
  47921. for (var j = 0; j < 3; ++j) {
  47922. if (t.error[j] < threshold) {
  47923. var deleted0 = [];
  47924. var deleted1 = [];
  47925. var v0 = t.vertices[j];
  47926. var v1 = t.vertices[(j + 1) % 3];
  47927. if (v0.isBorder || v1.isBorder)
  47928. continue;
  47929. var p = BABYLON.Vector3.Zero();
  47930. var n = BABYLON.Vector3.Zero();
  47931. var uv = BABYLON.Vector2.Zero();
  47932. var color = new BABYLON.Color4(0, 0, 0, 1);
  47933. _this.calculateError(v0, v1, p, n, uv, color);
  47934. var delTr = [];
  47935. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  47936. continue;
  47937. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  47938. continue;
  47939. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  47940. continue;
  47941. var uniqueArray = [];
  47942. delTr.forEach(function (deletedT) {
  47943. if (uniqueArray.indexOf(deletedT) === -1) {
  47944. deletedT.deletePending = true;
  47945. uniqueArray.push(deletedT);
  47946. }
  47947. });
  47948. if (uniqueArray.length % 2 !== 0) {
  47949. continue;
  47950. }
  47951. v0.q = v1.q.add(v0.q);
  47952. v0.updatePosition(p);
  47953. var tStart = _this.references.length;
  47954. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  47955. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  47956. var tCount = _this.references.length - tStart;
  47957. if (tCount <= v0.triangleCount) {
  47958. if (tCount) {
  47959. for (var c = 0; c < tCount; c++) {
  47960. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  47961. }
  47962. }
  47963. }
  47964. else {
  47965. v0.triangleStart = tStart;
  47966. }
  47967. v0.triangleCount = tCount;
  47968. break;
  47969. }
  47970. }
  47971. };
  47972. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  47973. }, 0);
  47974. };
  47975. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  47976. if (triangleCount - deletedTriangles <= targetCount)
  47977. loop.breakLoop();
  47978. else {
  47979. iterationFunction(loop.index, function () {
  47980. loop.executeNext();
  47981. });
  47982. }
  47983. }, function () {
  47984. setTimeout(function () {
  47985. //reconstruct this part of the mesh
  47986. _this.reconstructMesh(submeshIndex);
  47987. successCallback();
  47988. }, 0);
  47989. });
  47990. };
  47991. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  47992. var _this = this;
  47993. this.vertices = [];
  47994. this.triangles = [];
  47995. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47996. var indices = this._mesh.getIndices();
  47997. var submesh = this._mesh.subMeshes[submeshIndex];
  47998. var findInVertices = function (positionToSearch) {
  47999. if (optimizeMesh) {
  48000. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  48001. if (_this.vertices[ii].position.equals(positionToSearch)) {
  48002. return _this.vertices[ii];
  48003. }
  48004. }
  48005. }
  48006. return null;
  48007. };
  48008. var vertexReferences = [];
  48009. var vertexInit = function (i) {
  48010. var offset = i + submesh.verticesStart;
  48011. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  48012. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  48013. vertex.originalOffsets.push(offset);
  48014. if (vertex.id === _this.vertices.length) {
  48015. _this.vertices.push(vertex);
  48016. }
  48017. vertexReferences.push(vertex.id);
  48018. };
  48019. //var totalVertices = mesh.getTotalVertices();
  48020. var totalVertices = submesh.verticesCount;
  48021. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  48022. var indicesInit = function (i) {
  48023. var offset = (submesh.indexStart / 3) + i;
  48024. var pos = (offset * 3);
  48025. var i0 = indices[pos + 0];
  48026. var i1 = indices[pos + 1];
  48027. var i2 = indices[pos + 2];
  48028. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  48029. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  48030. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  48031. var triangle = new DecimationTriangle([v0, v1, v2]);
  48032. triangle.originalOffset = pos;
  48033. _this.triangles.push(triangle);
  48034. };
  48035. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  48036. _this.init(callback);
  48037. });
  48038. });
  48039. };
  48040. QuadraticErrorSimplification.prototype.init = function (callback) {
  48041. var _this = this;
  48042. var triangleInit1 = function (i) {
  48043. var t = _this.triangles[i];
  48044. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  48045. for (var j = 0; j < 3; j++) {
  48046. 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))));
  48047. }
  48048. };
  48049. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  48050. var triangleInit2 = function (i) {
  48051. var t = _this.triangles[i];
  48052. for (var j = 0; j < 3; ++j) {
  48053. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  48054. }
  48055. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  48056. };
  48057. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  48058. _this.initialized = true;
  48059. callback();
  48060. });
  48061. });
  48062. };
  48063. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  48064. var newTriangles = [];
  48065. var i;
  48066. for (i = 0; i < this.vertices.length; ++i) {
  48067. this.vertices[i].triangleCount = 0;
  48068. }
  48069. var t;
  48070. var j;
  48071. for (i = 0; i < this.triangles.length; ++i) {
  48072. if (!this.triangles[i].deleted) {
  48073. t = this.triangles[i];
  48074. for (j = 0; j < 3; ++j) {
  48075. t.vertices[j].triangleCount = 1;
  48076. }
  48077. newTriangles.push(t);
  48078. }
  48079. }
  48080. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  48081. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  48082. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  48083. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  48084. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48085. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48086. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48087. var vertexCount = 0;
  48088. for (i = 0; i < this.vertices.length; ++i) {
  48089. var vertex = this.vertices[i];
  48090. vertex.id = vertexCount;
  48091. if (vertex.triangleCount) {
  48092. vertex.originalOffsets.forEach(function (originalOffset) {
  48093. newPositionData.push(vertex.position.x);
  48094. newPositionData.push(vertex.position.y);
  48095. newPositionData.push(vertex.position.z);
  48096. newNormalData.push(normalData[originalOffset * 3]);
  48097. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  48098. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  48099. if (uvs && uvs.length) {
  48100. newUVsData.push(uvs[(originalOffset * 2)]);
  48101. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  48102. }
  48103. else if (colorsData && colorsData.length) {
  48104. newColorsData.push(colorsData[(originalOffset * 4)]);
  48105. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  48106. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  48107. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  48108. }
  48109. ++vertexCount;
  48110. });
  48111. }
  48112. }
  48113. var startingIndex = this._reconstructedMesh.getTotalIndices();
  48114. var startingVertex = this._reconstructedMesh.getTotalVertices();
  48115. var submeshesArray = this._reconstructedMesh.subMeshes;
  48116. this._reconstructedMesh.subMeshes = [];
  48117. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  48118. var originalIndices = this._mesh.getIndices();
  48119. for (i = 0; i < newTriangles.length; ++i) {
  48120. t = newTriangles[i]; //now get the new referencing point for each vertex
  48121. [0, 1, 2].forEach(function (idx) {
  48122. var id = originalIndices[t.originalOffset + idx];
  48123. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  48124. if (offset < 0)
  48125. offset = 0;
  48126. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  48127. });
  48128. }
  48129. //overwriting the old vertex buffers and indices.
  48130. this._reconstructedMesh.setIndices(newIndicesArray);
  48131. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  48132. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  48133. if (newUVsData.length > 0)
  48134. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  48135. if (newColorsData.length > 0)
  48136. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  48137. //create submesh
  48138. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  48139. if (submeshIndex > 0) {
  48140. this._reconstructedMesh.subMeshes = [];
  48141. submeshesArray.forEach(function (submesh) {
  48142. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  48143. });
  48144. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  48145. }
  48146. };
  48147. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  48148. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  48149. this._reconstructedMesh.material = this._mesh.material;
  48150. this._reconstructedMesh.parent = this._mesh.parent;
  48151. this._reconstructedMesh.isVisible = false;
  48152. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  48153. };
  48154. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  48155. for (var i = 0; i < vertex1.triangleCount; ++i) {
  48156. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  48157. if (t.deleted)
  48158. continue;
  48159. var s = this.references[vertex1.triangleStart + i].vertexId;
  48160. var v1 = t.vertices[(s + 1) % 3];
  48161. var v2 = t.vertices[(s + 2) % 3];
  48162. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  48163. deletedArray[i] = true;
  48164. delTr.push(t);
  48165. continue;
  48166. }
  48167. var d1 = v1.position.subtract(point);
  48168. d1 = d1.normalize();
  48169. var d2 = v2.position.subtract(point);
  48170. d2 = d2.normalize();
  48171. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  48172. return true;
  48173. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  48174. deletedArray[i] = false;
  48175. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  48176. return true;
  48177. }
  48178. return false;
  48179. };
  48180. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  48181. var newDeleted = deletedTriangles;
  48182. for (var i = 0; i < vertex.triangleCount; ++i) {
  48183. var ref = this.references[vertex.triangleStart + i];
  48184. var t = this.triangles[ref.triangleId];
  48185. if (t.deleted)
  48186. continue;
  48187. if (deletedArray[i] && t.deletePending) {
  48188. t.deleted = true;
  48189. newDeleted++;
  48190. continue;
  48191. }
  48192. t.vertices[ref.vertexId] = origVertex;
  48193. t.isDirty = true;
  48194. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  48195. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  48196. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  48197. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  48198. this.references.push(ref);
  48199. }
  48200. return newDeleted;
  48201. };
  48202. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  48203. for (var i = 0; i < this.vertices.length; ++i) {
  48204. var vCount = [];
  48205. var vId = [];
  48206. var v = this.vertices[i];
  48207. var j;
  48208. for (j = 0; j < v.triangleCount; ++j) {
  48209. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  48210. for (var ii = 0; ii < 3; ii++) {
  48211. var ofs = 0;
  48212. var vv = triangle.vertices[ii];
  48213. while (ofs < vCount.length) {
  48214. if (vId[ofs] === vv.id)
  48215. break;
  48216. ++ofs;
  48217. }
  48218. if (ofs === vCount.length) {
  48219. vCount.push(1);
  48220. vId.push(vv.id);
  48221. }
  48222. else {
  48223. vCount[ofs]++;
  48224. }
  48225. }
  48226. }
  48227. for (j = 0; j < vCount.length; ++j) {
  48228. if (vCount[j] === 1) {
  48229. this.vertices[vId[j]].isBorder = true;
  48230. }
  48231. else {
  48232. this.vertices[vId[j]].isBorder = false;
  48233. }
  48234. }
  48235. }
  48236. };
  48237. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  48238. if (identifyBorders === void 0) { identifyBorders = false; }
  48239. var i;
  48240. if (!identifyBorders) {
  48241. var newTrianglesVector = [];
  48242. for (i = 0; i < this.triangles.length; ++i) {
  48243. if (!this.triangles[i].deleted) {
  48244. newTrianglesVector.push(this.triangles[i]);
  48245. }
  48246. }
  48247. this.triangles = newTrianglesVector;
  48248. }
  48249. for (i = 0; i < this.vertices.length; ++i) {
  48250. this.vertices[i].triangleCount = 0;
  48251. this.vertices[i].triangleStart = 0;
  48252. }
  48253. var t;
  48254. var j;
  48255. var v;
  48256. for (i = 0; i < this.triangles.length; ++i) {
  48257. t = this.triangles[i];
  48258. for (j = 0; j < 3; ++j) {
  48259. v = t.vertices[j];
  48260. v.triangleCount++;
  48261. }
  48262. }
  48263. var tStart = 0;
  48264. for (i = 0; i < this.vertices.length; ++i) {
  48265. this.vertices[i].triangleStart = tStart;
  48266. tStart += this.vertices[i].triangleCount;
  48267. this.vertices[i].triangleCount = 0;
  48268. }
  48269. var newReferences = new Array(this.triangles.length * 3);
  48270. for (i = 0; i < this.triangles.length; ++i) {
  48271. t = this.triangles[i];
  48272. for (j = 0; j < 3; ++j) {
  48273. v = t.vertices[j];
  48274. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  48275. v.triangleCount++;
  48276. }
  48277. }
  48278. this.references = newReferences;
  48279. if (identifyBorders) {
  48280. this.identifyBorder();
  48281. }
  48282. };
  48283. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  48284. var x = point.x;
  48285. var y = point.y;
  48286. var z = point.z;
  48287. 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
  48288. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  48289. };
  48290. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  48291. var q = vertex1.q.add(vertex2.q);
  48292. var border = vertex1.isBorder && vertex2.isBorder;
  48293. var error = 0;
  48294. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  48295. if (qDet !== 0 && !border) {
  48296. if (!pointResult) {
  48297. pointResult = BABYLON.Vector3.Zero();
  48298. }
  48299. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  48300. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  48301. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  48302. error = this.vertexError(q, pointResult);
  48303. }
  48304. else {
  48305. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  48306. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  48307. var error1 = this.vertexError(q, vertex1.position);
  48308. var error2 = this.vertexError(q, vertex2.position);
  48309. var error3 = this.vertexError(q, p3);
  48310. error = Math.min(error1, error2, error3);
  48311. if (error === error1) {
  48312. if (pointResult) {
  48313. pointResult.copyFrom(vertex1.position);
  48314. }
  48315. }
  48316. else if (error === error2) {
  48317. if (pointResult) {
  48318. pointResult.copyFrom(vertex2.position);
  48319. }
  48320. }
  48321. else {
  48322. if (pointResult) {
  48323. pointResult.copyFrom(p3);
  48324. }
  48325. }
  48326. }
  48327. return error;
  48328. };
  48329. return QuadraticErrorSimplification;
  48330. }());
  48331. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  48332. })(BABYLON || (BABYLON = {}));
  48333. //# sourceMappingURL=babylon.meshSimplification.js.map
  48334. var BABYLON;
  48335. (function (BABYLON) {
  48336. var serializedGeometries = [];
  48337. var serializeGeometry = function (geometry, serializationGeometries) {
  48338. if (serializedGeometries[geometry.id]) {
  48339. return;
  48340. }
  48341. if (geometry.doNotSerialize) {
  48342. return;
  48343. }
  48344. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  48345. serializationGeometries.boxes.push(geometry.serialize());
  48346. }
  48347. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  48348. serializationGeometries.spheres.push(geometry.serialize());
  48349. }
  48350. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  48351. serializationGeometries.cylinders.push(geometry.serialize());
  48352. }
  48353. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  48354. serializationGeometries.toruses.push(geometry.serialize());
  48355. }
  48356. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  48357. serializationGeometries.grounds.push(geometry.serialize());
  48358. }
  48359. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  48360. serializationGeometries.planes.push(geometry.serialize());
  48361. }
  48362. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  48363. serializationGeometries.torusKnots.push(geometry.serialize());
  48364. }
  48365. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  48366. throw new Error("Unknown primitive type");
  48367. }
  48368. else {
  48369. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  48370. }
  48371. serializedGeometries[geometry.id] = true;
  48372. };
  48373. var serializeMesh = function (mesh, serializationScene) {
  48374. var serializationObject = {};
  48375. // Geometry
  48376. var geometry = mesh._geometry;
  48377. if (geometry) {
  48378. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  48379. // 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
  48380. serializeGeometry(geometry, serializationScene.geometries);
  48381. }
  48382. }
  48383. // Custom
  48384. if (mesh.serialize) {
  48385. mesh.serialize(serializationObject);
  48386. }
  48387. return serializationObject;
  48388. };
  48389. var finalizeSingleMesh = function (mesh, serializationObject) {
  48390. //only works if the mesh is already loaded
  48391. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  48392. //serialize material
  48393. if (mesh.material) {
  48394. if (mesh.material instanceof BABYLON.StandardMaterial) {
  48395. serializationObject.materials = serializationObject.materials || [];
  48396. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  48397. serializationObject.materials.push(mesh.material.serialize());
  48398. }
  48399. }
  48400. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  48401. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  48402. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  48403. serializationObject.multiMaterials.push(mesh.material.serialize());
  48404. }
  48405. }
  48406. }
  48407. //serialize geometry
  48408. var geometry = mesh._geometry;
  48409. if (geometry) {
  48410. if (!serializationObject.geometries) {
  48411. serializationObject.geometries = {};
  48412. serializationObject.geometries.boxes = [];
  48413. serializationObject.geometries.spheres = [];
  48414. serializationObject.geometries.cylinders = [];
  48415. serializationObject.geometries.toruses = [];
  48416. serializationObject.geometries.grounds = [];
  48417. serializationObject.geometries.planes = [];
  48418. serializationObject.geometries.torusKnots = [];
  48419. serializationObject.geometries.vertexData = [];
  48420. }
  48421. serializeGeometry(geometry, serializationObject.geometries);
  48422. }
  48423. // Skeletons
  48424. if (mesh.skeleton) {
  48425. serializationObject.skeletons = serializationObject.skeletons || [];
  48426. serializationObject.skeletons.push(mesh.skeleton.serialize());
  48427. }
  48428. //serialize the actual mesh
  48429. serializationObject.meshes = serializationObject.meshes || [];
  48430. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  48431. }
  48432. };
  48433. var SceneSerializer = (function () {
  48434. function SceneSerializer() {
  48435. }
  48436. SceneSerializer.ClearCache = function () {
  48437. serializedGeometries = [];
  48438. };
  48439. SceneSerializer.Serialize = function (scene) {
  48440. var serializationObject = {};
  48441. SceneSerializer.ClearCache();
  48442. // Scene
  48443. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  48444. serializationObject.autoClear = scene.autoClear;
  48445. serializationObject.clearColor = scene.clearColor.asArray();
  48446. serializationObject.ambientColor = scene.ambientColor.asArray();
  48447. serializationObject.gravity = scene.gravity.asArray();
  48448. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  48449. serializationObject.workerCollisions = scene.workerCollisions;
  48450. // Fog
  48451. if (scene.fogMode && scene.fogMode !== 0) {
  48452. serializationObject.fogMode = scene.fogMode;
  48453. serializationObject.fogColor = scene.fogColor.asArray();
  48454. serializationObject.fogStart = scene.fogStart;
  48455. serializationObject.fogEnd = scene.fogEnd;
  48456. serializationObject.fogDensity = scene.fogDensity;
  48457. }
  48458. //Physics
  48459. if (scene.isPhysicsEnabled()) {
  48460. serializationObject.physicsEnabled = true;
  48461. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  48462. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  48463. }
  48464. // Metadata
  48465. if (scene.metadata) {
  48466. serializationObject.metadata = scene.metadata;
  48467. }
  48468. // Lights
  48469. serializationObject.lights = [];
  48470. var index;
  48471. var light;
  48472. for (index = 0; index < scene.lights.length; index++) {
  48473. light = scene.lights[index];
  48474. if (!light.doNotSerialize) {
  48475. serializationObject.lights.push(light.serialize());
  48476. }
  48477. }
  48478. // Cameras
  48479. serializationObject.cameras = [];
  48480. for (index = 0; index < scene.cameras.length; index++) {
  48481. var camera = scene.cameras[index];
  48482. if (!camera.doNotSerialize) {
  48483. serializationObject.cameras.push(camera.serialize());
  48484. }
  48485. }
  48486. if (scene.activeCamera) {
  48487. serializationObject.activeCameraID = scene.activeCamera.id;
  48488. }
  48489. // Animations
  48490. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  48491. // Materials
  48492. serializationObject.materials = [];
  48493. serializationObject.multiMaterials = [];
  48494. var material;
  48495. for (index = 0; index < scene.materials.length; index++) {
  48496. material = scene.materials[index];
  48497. if (!material.doNotSerialize) {
  48498. serializationObject.materials.push(material.serialize());
  48499. }
  48500. }
  48501. // MultiMaterials
  48502. serializationObject.multiMaterials = [];
  48503. for (index = 0; index < scene.multiMaterials.length; index++) {
  48504. var multiMaterial = scene.multiMaterials[index];
  48505. serializationObject.multiMaterials.push(multiMaterial.serialize());
  48506. }
  48507. // Skeletons
  48508. serializationObject.skeletons = [];
  48509. for (index = 0; index < scene.skeletons.length; index++) {
  48510. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  48511. }
  48512. // Geometries
  48513. serializationObject.geometries = {};
  48514. serializationObject.geometries.boxes = [];
  48515. serializationObject.geometries.spheres = [];
  48516. serializationObject.geometries.cylinders = [];
  48517. serializationObject.geometries.toruses = [];
  48518. serializationObject.geometries.grounds = [];
  48519. serializationObject.geometries.planes = [];
  48520. serializationObject.geometries.torusKnots = [];
  48521. serializationObject.geometries.vertexData = [];
  48522. serializedGeometries = [];
  48523. var geometries = scene.getGeometries();
  48524. for (index = 0; index < geometries.length; index++) {
  48525. var geometry = geometries[index];
  48526. if (geometry.isReady()) {
  48527. serializeGeometry(geometry, serializationObject.geometries);
  48528. }
  48529. }
  48530. // Meshes
  48531. serializationObject.meshes = [];
  48532. for (index = 0; index < scene.meshes.length; index++) {
  48533. var abstractMesh = scene.meshes[index];
  48534. if (abstractMesh instanceof BABYLON.Mesh) {
  48535. var mesh = abstractMesh;
  48536. if (!mesh.doNotSerialize) {
  48537. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  48538. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  48539. }
  48540. }
  48541. }
  48542. }
  48543. // Particles Systems
  48544. serializationObject.particleSystems = [];
  48545. for (index = 0; index < scene.particleSystems.length; index++) {
  48546. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  48547. }
  48548. // Lens flares
  48549. serializationObject.lensFlareSystems = [];
  48550. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  48551. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  48552. }
  48553. // Shadows
  48554. serializationObject.shadowGenerators = [];
  48555. for (index = 0; index < scene.lights.length; index++) {
  48556. light = scene.lights[index];
  48557. var shadowGenerator = light.getShadowGenerator();
  48558. // Only support serialization for official generator so far.
  48559. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  48560. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  48561. }
  48562. }
  48563. // Action Manager
  48564. if (scene.actionManager) {
  48565. serializationObject.actions = scene.actionManager.serialize("scene");
  48566. }
  48567. // Audio
  48568. serializationObject.sounds = [];
  48569. for (index = 0; index < scene.soundTracks.length; index++) {
  48570. var soundtrack = scene.soundTracks[index];
  48571. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  48572. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  48573. }
  48574. }
  48575. return serializationObject;
  48576. };
  48577. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  48578. if (withParents === void 0) { withParents = false; }
  48579. if (withChildren === void 0) { withChildren = false; }
  48580. var serializationObject = {};
  48581. SceneSerializer.ClearCache();
  48582. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  48583. if (withParents || withChildren) {
  48584. //deliberate for loop! not for each, appended should be processed as well.
  48585. for (var i = 0; i < toSerialize.length; ++i) {
  48586. if (withChildren) {
  48587. toSerialize[i].getDescendants().forEach(function (node) {
  48588. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  48589. toSerialize.push(node);
  48590. }
  48591. });
  48592. }
  48593. //make sure the array doesn't contain the object already
  48594. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  48595. toSerialize.push(toSerialize[i].parent);
  48596. }
  48597. }
  48598. }
  48599. toSerialize.forEach(function (mesh) {
  48600. finalizeSingleMesh(mesh, serializationObject);
  48601. });
  48602. return serializationObject;
  48603. };
  48604. return SceneSerializer;
  48605. }());
  48606. BABYLON.SceneSerializer = SceneSerializer;
  48607. })(BABYLON || (BABYLON = {}));
  48608. //# sourceMappingURL=babylon.sceneSerializer.js.map
  48609. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  48610. // Huge respect for a such great lib.
  48611. // Earcut license:
  48612. // Copyright (c) 2016, Mapbox
  48613. //
  48614. // Permission to use, copy, modify, and/or distribute this software for any purpose
  48615. // with or without fee is hereby granted, provided that the above copyright notice
  48616. // and this permission notice appear in all copies.
  48617. //
  48618. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  48619. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  48620. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  48621. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  48622. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  48623. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  48624. // THIS SOFTWARE.
  48625. var Earcut;
  48626. (function (Earcut) {
  48627. /**
  48628. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  48629. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  48630. * @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).
  48631. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  48632. */
  48633. function earcut(data, holeIndices, dim) {
  48634. dim = dim || 2;
  48635. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  48636. if (!outerNode)
  48637. return triangles;
  48638. var minX, minY, maxX, maxY, x, y, size;
  48639. if (hasHoles)
  48640. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  48641. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  48642. if (data.length > 80 * dim) {
  48643. minX = maxX = data[0];
  48644. minY = maxY = data[1];
  48645. for (var i = dim; i < outerLen; i += dim) {
  48646. x = data[i];
  48647. y = data[i + 1];
  48648. if (x < minX)
  48649. minX = x;
  48650. if (y < minY)
  48651. minY = y;
  48652. if (x > maxX)
  48653. maxX = x;
  48654. if (y > maxY)
  48655. maxY = y;
  48656. }
  48657. // minX, minY and size are later used to transform coords into integers for z-order calculation
  48658. size = Math.max(maxX - minX, maxY - minY);
  48659. }
  48660. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  48661. return triangles;
  48662. }
  48663. Earcut.earcut = earcut;
  48664. // create a circular doubly linked list from polygon points in the specified winding order
  48665. function linkedList(data, start, end, dim, clockwise) {
  48666. var i, last;
  48667. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  48668. for (i = start; i < end; i += dim)
  48669. last = insertNode(i, data[i], data[i + 1], last);
  48670. }
  48671. else {
  48672. for (i = end - dim; i >= start; i -= dim)
  48673. last = insertNode(i, data[i], data[i + 1], last);
  48674. }
  48675. if (last && equals(last, last.next)) {
  48676. removeNode(last);
  48677. last = last.next;
  48678. }
  48679. return last;
  48680. }
  48681. // eliminate colinear or duplicate points
  48682. function filterPoints(start, end) {
  48683. if (!start)
  48684. return start;
  48685. if (!end)
  48686. end = start;
  48687. var p = start, again;
  48688. do {
  48689. again = false;
  48690. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  48691. removeNode(p);
  48692. p = end = p.prev;
  48693. if (p === p.next)
  48694. return null;
  48695. again = true;
  48696. }
  48697. else {
  48698. p = p.next;
  48699. }
  48700. } while (again || p !== end);
  48701. return end;
  48702. }
  48703. // main ear slicing loop which triangulates a polygon (given as a linked list)
  48704. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  48705. if (!ear)
  48706. return;
  48707. // interlink polygon nodes in z-order
  48708. if (!pass && size)
  48709. indexCurve(ear, minX, minY, size);
  48710. var stop = ear, prev, next;
  48711. // iterate through ears, slicing them one by one
  48712. while (ear.prev !== ear.next) {
  48713. prev = ear.prev;
  48714. next = ear.next;
  48715. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  48716. // cut off the triangle
  48717. triangles.push(prev.i / dim);
  48718. triangles.push(ear.i / dim);
  48719. triangles.push(next.i / dim);
  48720. removeNode(ear);
  48721. // skipping the next vertice leads to less sliver triangles
  48722. ear = next.next;
  48723. stop = next.next;
  48724. continue;
  48725. }
  48726. ear = next;
  48727. // if we looped through the whole remaining polygon and can't find any more ears
  48728. if (ear === stop) {
  48729. // try filtering points and slicing again
  48730. if (!pass) {
  48731. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  48732. // if this didn't work, try curing all small self-intersections locally
  48733. }
  48734. else if (pass === 1) {
  48735. ear = cureLocalIntersections(ear, triangles, dim);
  48736. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  48737. // as a last resort, try splitting the remaining polygon into two
  48738. }
  48739. else if (pass === 2) {
  48740. splitEarcut(ear, triangles, dim, minX, minY, size);
  48741. }
  48742. break;
  48743. }
  48744. }
  48745. }
  48746. // check whether a polygon node forms a valid ear with adjacent nodes
  48747. function isEar(ear) {
  48748. var a = ear.prev, b = ear, c = ear.next;
  48749. if (area(a, b, c) >= 0)
  48750. return false; // reflex, can't be an ear
  48751. // now make sure we don't have other points inside the potential ear
  48752. var p = ear.next.next;
  48753. while (p !== ear.prev) {
  48754. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  48755. area(p.prev, p, p.next) >= 0)
  48756. return false;
  48757. p = p.next;
  48758. }
  48759. return true;
  48760. }
  48761. function isEarHashed(ear, minX, minY, size) {
  48762. var a = ear.prev, b = ear, c = ear.next;
  48763. if (area(a, b, c) >= 0)
  48764. return false; // reflex, can't be an ear
  48765. // triangle bbox; min & max are calculated like this for speed
  48766. 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);
  48767. // z-order range for the current triangle bbox;
  48768. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  48769. // first look for points inside the triangle in increasing z-order
  48770. var p = ear.nextZ;
  48771. while (p && p.z <= maxZ) {
  48772. if (p !== ear.prev &&
  48773. p !== ear.next &&
  48774. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  48775. area(p.prev, p, p.next) >= 0)
  48776. return false;
  48777. p = p.nextZ;
  48778. }
  48779. // then look for points in decreasing z-order
  48780. p = ear.prevZ;
  48781. while (p && p.z >= minZ) {
  48782. if (p !== ear.prev &&
  48783. p !== ear.next &&
  48784. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  48785. area(p.prev, p, p.next) >= 0)
  48786. return false;
  48787. p = p.prevZ;
  48788. }
  48789. return true;
  48790. }
  48791. // go through all polygon nodes and cure small local self-intersections
  48792. function cureLocalIntersections(start, triangles, dim) {
  48793. var p = start;
  48794. do {
  48795. var a = p.prev, b = p.next.next;
  48796. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  48797. triangles.push(a.i / dim);
  48798. triangles.push(p.i / dim);
  48799. triangles.push(b.i / dim);
  48800. // remove two nodes involved
  48801. removeNode(p);
  48802. removeNode(p.next);
  48803. p = start = b;
  48804. }
  48805. p = p.next;
  48806. } while (p !== start);
  48807. return p;
  48808. }
  48809. // try splitting polygon into two and triangulate them independently
  48810. function splitEarcut(start, triangles, dim, minX, minY, size) {
  48811. // look for a valid diagonal that divides the polygon into two
  48812. var a = start;
  48813. do {
  48814. var b = a.next.next;
  48815. while (b !== a.prev) {
  48816. if (a.i !== b.i && isValidDiagonal(a, b)) {
  48817. // split the polygon in two by the diagonal
  48818. var c = splitPolygon(a, b);
  48819. // filter colinear points around the cuts
  48820. a = filterPoints(a, a.next);
  48821. c = filterPoints(c, c.next);
  48822. // run earcut on each half
  48823. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  48824. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  48825. return;
  48826. }
  48827. b = b.next;
  48828. }
  48829. a = a.next;
  48830. } while (a !== start);
  48831. }
  48832. // link every hole into the outer loop, producing a single-ring polygon without holes
  48833. function eliminateHoles(data, holeIndices, outerNode, dim) {
  48834. var queue = [], i, len, start, end, list;
  48835. for (i = 0, len = holeIndices.length; i < len; i++) {
  48836. start = holeIndices[i] * dim;
  48837. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  48838. list = linkedList(data, start, end, dim, false);
  48839. if (list === list.next)
  48840. list.steiner = true;
  48841. queue.push(getLeftmost(list));
  48842. }
  48843. queue.sort(compareX);
  48844. // process holes from left to right
  48845. for (i = 0; i < queue.length; i++) {
  48846. eliminateHole(queue[i], outerNode);
  48847. outerNode = filterPoints(outerNode, outerNode.next);
  48848. }
  48849. return outerNode;
  48850. }
  48851. function compareX(a, b) {
  48852. return a.x - b.x;
  48853. }
  48854. // find a bridge between vertices that connects hole with an outer ring and and link it
  48855. function eliminateHole(hole, outerNode) {
  48856. outerNode = findHoleBridge(hole, outerNode);
  48857. if (outerNode) {
  48858. var b = splitPolygon(outerNode, hole);
  48859. filterPoints(b, b.next);
  48860. }
  48861. }
  48862. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  48863. function findHoleBridge(hole, outerNode) {
  48864. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  48865. // find a segment intersected by a ray from the hole's leftmost point to the left;
  48866. // segment's endpoint with lesser x will be potential connection point
  48867. do {
  48868. if (hy <= p.y && hy >= p.next.y) {
  48869. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  48870. if (x <= hx && x > qx) {
  48871. qx = x;
  48872. if (x === hx) {
  48873. if (hy === p.y)
  48874. return p;
  48875. if (hy === p.next.y)
  48876. return p.next;
  48877. }
  48878. m = p.x < p.next.x ? p : p.next;
  48879. }
  48880. }
  48881. p = p.next;
  48882. } while (p !== outerNode);
  48883. if (!m)
  48884. return null;
  48885. if (hx === qx)
  48886. return m.prev; // hole touches outer segment; pick lower endpoint
  48887. // look for points inside the triangle of hole point, segment intersection and endpoint;
  48888. // if there are no points found, we have a valid connection;
  48889. // otherwise choose the point of the minimum angle with the ray as connection point
  48890. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  48891. p = m.next;
  48892. while (p !== stop) {
  48893. if (hx >= p.x &&
  48894. p.x >= mx &&
  48895. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  48896. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  48897. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  48898. m = p;
  48899. tanMin = tan;
  48900. }
  48901. }
  48902. p = p.next;
  48903. }
  48904. return m;
  48905. }
  48906. // interlink polygon nodes in z-order
  48907. function indexCurve(start, minX, minY, size) {
  48908. var p = start;
  48909. do {
  48910. if (p.z === null)
  48911. p.z = zOrder(p.x, p.y, minX, minY, size);
  48912. p.prevZ = p.prev;
  48913. p.nextZ = p.next;
  48914. p = p.next;
  48915. } while (p !== start);
  48916. p.prevZ.nextZ = null;
  48917. p.prevZ = null;
  48918. sortLinked(p);
  48919. }
  48920. // Simon Tatham's linked list merge sort algorithm
  48921. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  48922. function sortLinked(list) {
  48923. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  48924. do {
  48925. p = list;
  48926. list = null;
  48927. tail = null;
  48928. numMerges = 0;
  48929. while (p) {
  48930. numMerges++;
  48931. q = p;
  48932. pSize = 0;
  48933. for (i = 0; i < inSize; i++) {
  48934. pSize++;
  48935. q = q.nextZ;
  48936. if (!q)
  48937. break;
  48938. }
  48939. qSize = inSize;
  48940. while (pSize > 0 || (qSize > 0 && q)) {
  48941. if (pSize === 0) {
  48942. e = q;
  48943. q = q.nextZ;
  48944. qSize--;
  48945. }
  48946. else if (qSize === 0 || !q) {
  48947. e = p;
  48948. p = p.nextZ;
  48949. pSize--;
  48950. }
  48951. else if (p.z <= q.z) {
  48952. e = p;
  48953. p = p.nextZ;
  48954. pSize--;
  48955. }
  48956. else {
  48957. e = q;
  48958. q = q.nextZ;
  48959. qSize--;
  48960. }
  48961. if (tail)
  48962. tail.nextZ = e;
  48963. else
  48964. list = e;
  48965. e.prevZ = tail;
  48966. tail = e;
  48967. }
  48968. p = q;
  48969. }
  48970. tail.nextZ = null;
  48971. inSize *= 2;
  48972. } while (numMerges > 1);
  48973. return list;
  48974. }
  48975. // z-order of a point given coords and size of the data bounding box
  48976. function zOrder(x, y, minX, minY, size) {
  48977. // coords are transformed into non-negative 15-bit integer range
  48978. x = 32767 * (x - minX) / size;
  48979. y = 32767 * (y - minY) / size;
  48980. x = (x | (x << 8)) & 0x00FF00FF;
  48981. x = (x | (x << 4)) & 0x0F0F0F0F;
  48982. x = (x | (x << 2)) & 0x33333333;
  48983. x = (x | (x << 1)) & 0x55555555;
  48984. y = (y | (y << 8)) & 0x00FF00FF;
  48985. y = (y | (y << 4)) & 0x0F0F0F0F;
  48986. y = (y | (y << 2)) & 0x33333333;
  48987. y = (y | (y << 1)) & 0x55555555;
  48988. return x | (y << 1);
  48989. }
  48990. // find the leftmost node of a polygon ring
  48991. function getLeftmost(start) {
  48992. var p = start, leftmost = start;
  48993. do {
  48994. if (p.x < leftmost.x)
  48995. leftmost = p;
  48996. p = p.next;
  48997. } while (p !== start);
  48998. return leftmost;
  48999. }
  49000. // check if a point lies within a convex triangle
  49001. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  49002. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  49003. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  49004. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  49005. }
  49006. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  49007. function isValidDiagonal(a, b) {
  49008. return a.next.i !== b.i &&
  49009. a.prev.i !== b.i &&
  49010. !intersectsPolygon(a, b) &&
  49011. locallyInside(a, b) &&
  49012. locallyInside(b, a) &&
  49013. middleInside(a, b);
  49014. }
  49015. // signed area of a triangle
  49016. function area(p, q, r) {
  49017. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  49018. }
  49019. // check if two points are equal
  49020. function equals(p1, p2) {
  49021. return p1.x === p2.x && p1.y === p2.y;
  49022. }
  49023. // check if two segments intersect
  49024. function intersects(p1, q1, p2, q2) {
  49025. if ((equals(p1, q1) && equals(p2, q2)) ||
  49026. (equals(p1, q2) && equals(p2, q1)))
  49027. return true;
  49028. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  49029. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  49030. }
  49031. // check if a polygon diagonal intersects any polygon segments
  49032. function intersectsPolygon(a, b) {
  49033. var p = a;
  49034. do {
  49035. if (p.i !== a.i &&
  49036. p.next.i !== a.i &&
  49037. p.i !== b.i &&
  49038. p.next.i !== b.i &&
  49039. intersects(p, p.next, a, b))
  49040. return true;
  49041. p = p.next;
  49042. } while (p !== a);
  49043. return false;
  49044. }
  49045. // check if a polygon diagonal is locally inside the polygon
  49046. function locallyInside(a, b) {
  49047. return area(a.prev, a, a.next) < 0
  49048. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  49049. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  49050. }
  49051. // check if the middle point of a polygon diagonal is inside the polygon
  49052. function middleInside(a, b) {
  49053. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  49054. do {
  49055. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  49056. inside = !inside;
  49057. p = p.next;
  49058. } while (p !== a);
  49059. return inside;
  49060. }
  49061. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  49062. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  49063. function splitPolygon(a, b) {
  49064. 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;
  49065. a.next = b;
  49066. b.prev = a;
  49067. a2.next = an;
  49068. an.prev = a2;
  49069. b2.next = a2;
  49070. a2.prev = b2;
  49071. bp.next = b2;
  49072. b2.prev = bp;
  49073. return b2;
  49074. }
  49075. // create a node and optionally link it with previous one (in a circular doubly linked list)
  49076. function insertNode(i, x, y, last) {
  49077. var p = new Node(i, x, y);
  49078. if (!last) {
  49079. p.prev = p;
  49080. p.next = p;
  49081. }
  49082. else {
  49083. p.next = last.next;
  49084. p.prev = last;
  49085. last.next.prev = p;
  49086. last.next = p;
  49087. }
  49088. return p;
  49089. }
  49090. function removeNode(p) {
  49091. p.next.prev = p.prev;
  49092. p.prev.next = p.next;
  49093. if (p.prevZ)
  49094. p.prevZ.nextZ = p.nextZ;
  49095. if (p.nextZ)
  49096. p.nextZ.prevZ = p.prevZ;
  49097. }
  49098. function Node(i, x, y) {
  49099. // vertice index in coordinates array
  49100. this.i = i;
  49101. // vertex coordinates
  49102. this.x = x;
  49103. this.y = y;
  49104. // previous and next vertice nodes in a polygon ring
  49105. this.prev = null;
  49106. this.next = null;
  49107. // z-order curve value
  49108. this.z = null;
  49109. // previous and next nodes in z-order
  49110. this.prevZ = null;
  49111. this.nextZ = null;
  49112. // indicates whether this is a steiner point
  49113. this.steiner = false;
  49114. }
  49115. /**
  49116. * return a percentage difference between the polygon area and its triangulation area;
  49117. * used to verify correctness of triangulation
  49118. */
  49119. function deviation(data, holeIndices, dim, triangles) {
  49120. var hasHoles = holeIndices && holeIndices.length;
  49121. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  49122. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  49123. if (hasHoles) {
  49124. for (var i = 0, len = holeIndices.length; i < len; i++) {
  49125. var start = holeIndices[i] * dim;
  49126. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  49127. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  49128. }
  49129. }
  49130. var trianglesArea = 0;
  49131. for (i = 0; i < triangles.length; i += 3) {
  49132. var a = triangles[i] * dim;
  49133. var b = triangles[i + 1] * dim;
  49134. var c = triangles[i + 2] * dim;
  49135. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  49136. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  49137. }
  49138. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  49139. }
  49140. Earcut.deviation = deviation;
  49141. ;
  49142. function signedArea(data, start, end, dim) {
  49143. var sum = 0;
  49144. for (var i = start, j = end - dim; i < end; i += dim) {
  49145. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  49146. j = i;
  49147. }
  49148. return sum;
  49149. }
  49150. /**
  49151. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  49152. */
  49153. function flatten(data) {
  49154. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  49155. for (var i = 0; i < data.length; i++) {
  49156. for (var j = 0; j < data[i].length; j++) {
  49157. for (var d = 0; d < dim; d++)
  49158. result.vertices.push(data[i][j][d]);
  49159. }
  49160. if (i > 0) {
  49161. holeIndex += data[i - 1].length;
  49162. result.holes.push(holeIndex);
  49163. }
  49164. }
  49165. return result;
  49166. }
  49167. Earcut.flatten = flatten;
  49168. ;
  49169. })(Earcut || (Earcut = {}));
  49170. //# sourceMappingURL=babylon.earcut.js.map
  49171. var BABYLON;
  49172. (function (BABYLON) {
  49173. // Unique ID when we import meshes from Babylon to CSG
  49174. var currentCSGMeshId = 0;
  49175. // # class Vertex
  49176. // Represents a vertex of a polygon. Use your own vertex class instead of this
  49177. // one to provide additional features like texture coordinates and vertex
  49178. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  49179. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  49180. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  49181. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  49182. // is not used anywhere else.
  49183. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  49184. var Vertex = (function () {
  49185. function Vertex(pos, normal, uv) {
  49186. this.pos = pos;
  49187. this.normal = normal;
  49188. this.uv = uv;
  49189. }
  49190. Vertex.prototype.clone = function () {
  49191. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  49192. };
  49193. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  49194. // orientation of a polygon is flipped.
  49195. Vertex.prototype.flip = function () {
  49196. this.normal = this.normal.scale(-1);
  49197. };
  49198. // Create a new vertex between this vertex and `other` by linearly
  49199. // interpolating all properties using a parameter of `t`. Subclasses should
  49200. // override this to interpolate additional properties.
  49201. Vertex.prototype.interpolate = function (other, t) {
  49202. 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));
  49203. };
  49204. return Vertex;
  49205. }());
  49206. // # class Plane
  49207. // Represents a plane in 3D space.
  49208. var Plane = (function () {
  49209. function Plane(normal, w) {
  49210. this.normal = normal;
  49211. this.w = w;
  49212. }
  49213. Plane.FromPoints = function (a, b, c) {
  49214. var v0 = c.subtract(a);
  49215. var v1 = b.subtract(a);
  49216. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  49217. return null;
  49218. }
  49219. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  49220. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  49221. };
  49222. Plane.prototype.clone = function () {
  49223. return new Plane(this.normal.clone(), this.w);
  49224. };
  49225. Plane.prototype.flip = function () {
  49226. this.normal.scaleInPlace(-1);
  49227. this.w = -this.w;
  49228. };
  49229. // Split `polygon` by this plane if needed, then put the polygon or polygon
  49230. // fragments in the appropriate lists. Coplanar polygons go into either
  49231. // `coplanarFront` or `coplanarBack` depending on their orientation with
  49232. // respect to this plane. Polygons in front or in back of this plane go into
  49233. // either `front` or `back`.
  49234. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  49235. var COPLANAR = 0;
  49236. var FRONT = 1;
  49237. var BACK = 2;
  49238. var SPANNING = 3;
  49239. // Classify each point as well as the entire polygon into one of the above
  49240. // four classes.
  49241. var polygonType = 0;
  49242. var types = [];
  49243. var i;
  49244. var t;
  49245. for (i = 0; i < polygon.vertices.length; i++) {
  49246. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  49247. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  49248. polygonType |= type;
  49249. types.push(type);
  49250. }
  49251. // Put the polygon in the correct list, splitting it when necessary.
  49252. switch (polygonType) {
  49253. case COPLANAR:
  49254. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  49255. break;
  49256. case FRONT:
  49257. front.push(polygon);
  49258. break;
  49259. case BACK:
  49260. back.push(polygon);
  49261. break;
  49262. case SPANNING:
  49263. var f = [], b = [];
  49264. for (i = 0; i < polygon.vertices.length; i++) {
  49265. var j = (i + 1) % polygon.vertices.length;
  49266. var ti = types[i], tj = types[j];
  49267. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  49268. if (ti !== BACK)
  49269. f.push(vi);
  49270. if (ti !== FRONT)
  49271. b.push(ti !== BACK ? vi.clone() : vi);
  49272. if ((ti | tj) === SPANNING) {
  49273. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  49274. var v = vi.interpolate(vj, t);
  49275. f.push(v);
  49276. b.push(v.clone());
  49277. }
  49278. }
  49279. var poly;
  49280. if (f.length >= 3) {
  49281. poly = new Polygon(f, polygon.shared);
  49282. if (poly.plane)
  49283. front.push(poly);
  49284. }
  49285. if (b.length >= 3) {
  49286. poly = new Polygon(b, polygon.shared);
  49287. if (poly.plane)
  49288. back.push(poly);
  49289. }
  49290. break;
  49291. }
  49292. };
  49293. return Plane;
  49294. }());
  49295. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  49296. // point is on the plane.
  49297. Plane.EPSILON = 1e-5;
  49298. // # class Polygon
  49299. // Represents a convex polygon. The vertices used to initialize a polygon must
  49300. // be coplanar and form a convex loop.
  49301. //
  49302. // Each convex polygon has a `shared` property, which is shared between all
  49303. // polygons that are clones of each other or were split from the same polygon.
  49304. // This can be used to define per-polygon properties (such as surface color).
  49305. var Polygon = (function () {
  49306. function Polygon(vertices, shared) {
  49307. this.vertices = vertices;
  49308. this.shared = shared;
  49309. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  49310. }
  49311. Polygon.prototype.clone = function () {
  49312. var vertices = this.vertices.map(function (v) { return v.clone(); });
  49313. return new Polygon(vertices, this.shared);
  49314. };
  49315. Polygon.prototype.flip = function () {
  49316. this.vertices.reverse().map(function (v) { v.flip(); });
  49317. this.plane.flip();
  49318. };
  49319. return Polygon;
  49320. }());
  49321. // # class Node
  49322. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  49323. // by picking a polygon to split along. That polygon (and all other coplanar
  49324. // polygons) are added directly to that node and the other polygons are added to
  49325. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  49326. // no distinction between internal and leaf nodes.
  49327. var Node = (function () {
  49328. function Node(polygons) {
  49329. this.plane = null;
  49330. this.front = null;
  49331. this.back = null;
  49332. this.polygons = [];
  49333. if (polygons) {
  49334. this.build(polygons);
  49335. }
  49336. }
  49337. Node.prototype.clone = function () {
  49338. var node = new Node();
  49339. node.plane = this.plane && this.plane.clone();
  49340. node.front = this.front && this.front.clone();
  49341. node.back = this.back && this.back.clone();
  49342. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  49343. return node;
  49344. };
  49345. // Convert solid space to empty space and empty space to solid space.
  49346. Node.prototype.invert = function () {
  49347. for (var i = 0; i < this.polygons.length; i++) {
  49348. this.polygons[i].flip();
  49349. }
  49350. if (this.plane) {
  49351. this.plane.flip();
  49352. }
  49353. if (this.front) {
  49354. this.front.invert();
  49355. }
  49356. if (this.back) {
  49357. this.back.invert();
  49358. }
  49359. var temp = this.front;
  49360. this.front = this.back;
  49361. this.back = temp;
  49362. };
  49363. // Recursively remove all polygons in `polygons` that are inside this BSP
  49364. // tree.
  49365. Node.prototype.clipPolygons = function (polygons) {
  49366. if (!this.plane)
  49367. return polygons.slice();
  49368. var front = [], back = [];
  49369. for (var i = 0; i < polygons.length; i++) {
  49370. this.plane.splitPolygon(polygons[i], front, back, front, back);
  49371. }
  49372. if (this.front) {
  49373. front = this.front.clipPolygons(front);
  49374. }
  49375. if (this.back) {
  49376. back = this.back.clipPolygons(back);
  49377. }
  49378. else {
  49379. back = [];
  49380. }
  49381. return front.concat(back);
  49382. };
  49383. // Remove all polygons in this BSP tree that are inside the other BSP tree
  49384. // `bsp`.
  49385. Node.prototype.clipTo = function (bsp) {
  49386. this.polygons = bsp.clipPolygons(this.polygons);
  49387. if (this.front)
  49388. this.front.clipTo(bsp);
  49389. if (this.back)
  49390. this.back.clipTo(bsp);
  49391. };
  49392. // Return a list of all polygons in this BSP tree.
  49393. Node.prototype.allPolygons = function () {
  49394. var polygons = this.polygons.slice();
  49395. if (this.front)
  49396. polygons = polygons.concat(this.front.allPolygons());
  49397. if (this.back)
  49398. polygons = polygons.concat(this.back.allPolygons());
  49399. return polygons;
  49400. };
  49401. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  49402. // new polygons are filtered down to the bottom of the tree and become new
  49403. // nodes there. Each set of polygons is partitioned using the first polygon
  49404. // (no heuristic is used to pick a good split).
  49405. Node.prototype.build = function (polygons) {
  49406. if (!polygons.length)
  49407. return;
  49408. if (!this.plane)
  49409. this.plane = polygons[0].plane.clone();
  49410. var front = [], back = [];
  49411. for (var i = 0; i < polygons.length; i++) {
  49412. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  49413. }
  49414. if (front.length) {
  49415. if (!this.front)
  49416. this.front = new Node();
  49417. this.front.build(front);
  49418. }
  49419. if (back.length) {
  49420. if (!this.back)
  49421. this.back = new Node();
  49422. this.back.build(back);
  49423. }
  49424. };
  49425. return Node;
  49426. }());
  49427. var CSG = (function () {
  49428. function CSG() {
  49429. this.polygons = new Array();
  49430. }
  49431. // Convert BABYLON.Mesh to BABYLON.CSG
  49432. CSG.FromMesh = function (mesh) {
  49433. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  49434. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  49435. if (mesh instanceof BABYLON.Mesh) {
  49436. mesh.computeWorldMatrix(true);
  49437. matrix = mesh.getWorldMatrix();
  49438. meshPosition = mesh.position.clone();
  49439. meshRotation = mesh.rotation.clone();
  49440. if (mesh.rotationQuaternion) {
  49441. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  49442. }
  49443. meshScaling = mesh.scaling.clone();
  49444. }
  49445. else {
  49446. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  49447. }
  49448. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49449. var subMeshes = mesh.subMeshes;
  49450. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  49451. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  49452. vertices = [];
  49453. for (var j = 0; j < 3; j++) {
  49454. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  49455. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  49456. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  49457. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  49458. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  49459. vertex = new Vertex(position, normal, uv);
  49460. vertices.push(vertex);
  49461. }
  49462. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  49463. // To handle the case of degenerated triangle
  49464. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  49465. if (polygon.plane)
  49466. polygons.push(polygon);
  49467. }
  49468. }
  49469. var csg = CSG.FromPolygons(polygons);
  49470. csg.matrix = matrix;
  49471. csg.position = meshPosition;
  49472. csg.rotation = meshRotation;
  49473. csg.scaling = meshScaling;
  49474. csg.rotationQuaternion = meshRotationQuaternion;
  49475. currentCSGMeshId++;
  49476. return csg;
  49477. };
  49478. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  49479. CSG.FromPolygons = function (polygons) {
  49480. var csg = new CSG();
  49481. csg.polygons = polygons;
  49482. return csg;
  49483. };
  49484. CSG.prototype.clone = function () {
  49485. var csg = new CSG();
  49486. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  49487. csg.copyTransformAttributes(this);
  49488. return csg;
  49489. };
  49490. CSG.prototype.toPolygons = function () {
  49491. return this.polygons;
  49492. };
  49493. CSG.prototype.union = function (csg) {
  49494. var a = new Node(this.clone().polygons);
  49495. var b = new Node(csg.clone().polygons);
  49496. a.clipTo(b);
  49497. b.clipTo(a);
  49498. b.invert();
  49499. b.clipTo(a);
  49500. b.invert();
  49501. a.build(b.allPolygons());
  49502. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  49503. };
  49504. CSG.prototype.unionInPlace = function (csg) {
  49505. var a = new Node(this.polygons);
  49506. var b = new Node(csg.polygons);
  49507. a.clipTo(b);
  49508. b.clipTo(a);
  49509. b.invert();
  49510. b.clipTo(a);
  49511. b.invert();
  49512. a.build(b.allPolygons());
  49513. this.polygons = a.allPolygons();
  49514. };
  49515. CSG.prototype.subtract = function (csg) {
  49516. var a = new Node(this.clone().polygons);
  49517. var b = new Node(csg.clone().polygons);
  49518. a.invert();
  49519. a.clipTo(b);
  49520. b.clipTo(a);
  49521. b.invert();
  49522. b.clipTo(a);
  49523. b.invert();
  49524. a.build(b.allPolygons());
  49525. a.invert();
  49526. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  49527. };
  49528. CSG.prototype.subtractInPlace = function (csg) {
  49529. var a = new Node(this.polygons);
  49530. var b = new Node(csg.polygons);
  49531. a.invert();
  49532. a.clipTo(b);
  49533. b.clipTo(a);
  49534. b.invert();
  49535. b.clipTo(a);
  49536. b.invert();
  49537. a.build(b.allPolygons());
  49538. a.invert();
  49539. this.polygons = a.allPolygons();
  49540. };
  49541. CSG.prototype.intersect = function (csg) {
  49542. var a = new Node(this.clone().polygons);
  49543. var b = new Node(csg.clone().polygons);
  49544. a.invert();
  49545. b.clipTo(a);
  49546. b.invert();
  49547. a.clipTo(b);
  49548. b.clipTo(a);
  49549. a.build(b.allPolygons());
  49550. a.invert();
  49551. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  49552. };
  49553. CSG.prototype.intersectInPlace = function (csg) {
  49554. var a = new Node(this.polygons);
  49555. var b = new Node(csg.polygons);
  49556. a.invert();
  49557. b.clipTo(a);
  49558. b.invert();
  49559. a.clipTo(b);
  49560. b.clipTo(a);
  49561. a.build(b.allPolygons());
  49562. a.invert();
  49563. this.polygons = a.allPolygons();
  49564. };
  49565. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  49566. // not modified.
  49567. CSG.prototype.inverse = function () {
  49568. var csg = this.clone();
  49569. csg.inverseInPlace();
  49570. return csg;
  49571. };
  49572. CSG.prototype.inverseInPlace = function () {
  49573. this.polygons.map(function (p) { p.flip(); });
  49574. };
  49575. // This is used to keep meshes transformations so they can be restored
  49576. // when we build back a Babylon Mesh
  49577. // NB : All CSG operations are performed in world coordinates
  49578. CSG.prototype.copyTransformAttributes = function (csg) {
  49579. this.matrix = csg.matrix;
  49580. this.position = csg.position;
  49581. this.rotation = csg.rotation;
  49582. this.scaling = csg.scaling;
  49583. this.rotationQuaternion = csg.rotationQuaternion;
  49584. return this;
  49585. };
  49586. // Build Raw mesh from CSG
  49587. // Coordinates here are in world space
  49588. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  49589. var matrix = this.matrix.clone();
  49590. matrix.invert();
  49591. 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;
  49592. if (keepSubMeshes) {
  49593. // Sort Polygons, since subMeshes are indices range
  49594. polygons.sort(function (a, b) {
  49595. if (a.shared.meshId === b.shared.meshId) {
  49596. return a.shared.subMeshId - b.shared.subMeshId;
  49597. }
  49598. else {
  49599. return a.shared.meshId - b.shared.meshId;
  49600. }
  49601. });
  49602. }
  49603. for (var i = 0, il = polygons.length; i < il; i++) {
  49604. polygon = polygons[i];
  49605. // Building SubMeshes
  49606. if (!subMesh_dict[polygon.shared.meshId]) {
  49607. subMesh_dict[polygon.shared.meshId] = {};
  49608. }
  49609. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  49610. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  49611. indexStart: +Infinity,
  49612. indexEnd: -Infinity,
  49613. materialIndex: polygon.shared.materialIndex
  49614. };
  49615. }
  49616. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  49617. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  49618. polygonIndices[0] = 0;
  49619. polygonIndices[1] = j - 1;
  49620. polygonIndices[2] = j;
  49621. for (var k = 0; k < 3; k++) {
  49622. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  49623. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  49624. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  49625. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  49626. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  49627. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  49628. // Check if 2 points can be merged
  49629. if (!(typeof vertex_idx !== 'undefined' &&
  49630. normals[vertex_idx * 3] === localNormal.x &&
  49631. normals[vertex_idx * 3 + 1] === localNormal.y &&
  49632. normals[vertex_idx * 3 + 2] === localNormal.z &&
  49633. uvs[vertex_idx * 2] === uv.x &&
  49634. uvs[vertex_idx * 2 + 1] === uv.y)) {
  49635. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  49636. uvs.push(uv.x, uv.y);
  49637. normals.push(normal.x, normal.y, normal.z);
  49638. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  49639. }
  49640. indices.push(vertex_idx);
  49641. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  49642. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  49643. currentIndex++;
  49644. }
  49645. }
  49646. }
  49647. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  49648. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  49649. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  49650. mesh.setIndices(indices);
  49651. if (keepSubMeshes) {
  49652. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  49653. var materialIndexOffset = 0, materialMaxIndex;
  49654. mesh.subMeshes = new Array();
  49655. for (var m in subMesh_dict) {
  49656. materialMaxIndex = -1;
  49657. for (var sm in subMesh_dict[m]) {
  49658. subMesh_obj = subMesh_dict[m][sm];
  49659. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  49660. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  49661. }
  49662. materialIndexOffset += ++materialMaxIndex;
  49663. }
  49664. }
  49665. return mesh;
  49666. };
  49667. // Build Mesh from CSG taking material and transforms into account
  49668. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  49669. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  49670. mesh.material = material;
  49671. mesh.position.copyFrom(this.position);
  49672. mesh.rotation.copyFrom(this.rotation);
  49673. if (this.rotationQuaternion) {
  49674. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  49675. }
  49676. mesh.scaling.copyFrom(this.scaling);
  49677. mesh.computeWorldMatrix(true);
  49678. return mesh;
  49679. };
  49680. return CSG;
  49681. }());
  49682. BABYLON.CSG = CSG;
  49683. })(BABYLON || (BABYLON = {}));
  49684. //# sourceMappingURL=babylon.csg.js.map
  49685. var BABYLON;
  49686. (function (BABYLON) {
  49687. var VRDistortionCorrectionPostProcess = (function (_super) {
  49688. __extends(VRDistortionCorrectionPostProcess, _super);
  49689. //ANY
  49690. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  49691. var _this = _super.call(this, name, "vrDistortionCorrection", [
  49692. 'LensCenter',
  49693. 'Scale',
  49694. 'ScaleIn',
  49695. 'HmdWarpParam'
  49696. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  49697. _this._isRightEye = isRightEye;
  49698. _this._distortionFactors = vrMetrics.distortionK;
  49699. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  49700. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  49701. _this.onSizeChangedObservable.add(function () {
  49702. _this.aspectRatio = _this.width * .5 / _this.height;
  49703. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  49704. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  49705. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  49706. });
  49707. _this.onApplyObservable.add(function (effect) {
  49708. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  49709. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  49710. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  49711. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  49712. });
  49713. return _this;
  49714. }
  49715. return VRDistortionCorrectionPostProcess;
  49716. }(BABYLON.PostProcess));
  49717. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  49718. })(BABYLON || (BABYLON = {}));
  49719. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  49720. // Mainly based on these 2 articles :
  49721. // 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
  49722. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  49723. var BABYLON;
  49724. (function (BABYLON) {
  49725. var JoystickAxis;
  49726. (function (JoystickAxis) {
  49727. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  49728. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  49729. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  49730. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  49731. var VirtualJoystick = (function () {
  49732. function VirtualJoystick(leftJoystick) {
  49733. var _this = this;
  49734. if (leftJoystick) {
  49735. this._leftJoystick = true;
  49736. }
  49737. else {
  49738. this._leftJoystick = false;
  49739. }
  49740. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  49741. VirtualJoystick._globalJoystickIndex++;
  49742. // By default left & right arrow keys are moving the X
  49743. // and up & down keys are moving the Y
  49744. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  49745. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  49746. this.reverseLeftRight = false;
  49747. this.reverseUpDown = false;
  49748. // collections of pointers
  49749. this._touches = new BABYLON.StringDictionary();
  49750. this.deltaPosition = BABYLON.Vector3.Zero();
  49751. this._joystickSensibility = 25;
  49752. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  49753. this._rotationSpeed = 25;
  49754. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  49755. this._rotateOnAxisRelativeToMesh = false;
  49756. this._onResize = function (evt) {
  49757. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  49758. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  49759. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  49760. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  49761. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  49762. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  49763. };
  49764. // injecting a canvas element on top of the canvas 3D game
  49765. if (!VirtualJoystick.vjCanvas) {
  49766. window.addEventListener("resize", this._onResize, false);
  49767. VirtualJoystick.vjCanvas = document.createElement("canvas");
  49768. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  49769. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  49770. VirtualJoystick.vjCanvas.width = window.innerWidth;
  49771. VirtualJoystick.vjCanvas.height = window.innerHeight;
  49772. VirtualJoystick.vjCanvas.style.width = "100%";
  49773. VirtualJoystick.vjCanvas.style.height = "100%";
  49774. VirtualJoystick.vjCanvas.style.position = "absolute";
  49775. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  49776. VirtualJoystick.vjCanvas.style.top = "0px";
  49777. VirtualJoystick.vjCanvas.style.left = "0px";
  49778. VirtualJoystick.vjCanvas.style.zIndex = "5";
  49779. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  49780. // Support for jQuery PEP polyfill
  49781. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  49782. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  49783. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  49784. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  49785. document.body.appendChild(VirtualJoystick.vjCanvas);
  49786. }
  49787. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  49788. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  49789. this.pressed = false;
  49790. // default joystick color
  49791. this._joystickColor = "cyan";
  49792. this._joystickPointerID = -1;
  49793. // current joystick position
  49794. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  49795. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  49796. // origin joystick position
  49797. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  49798. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  49799. this._onPointerDownHandlerRef = function (evt) {
  49800. _this._onPointerDown(evt);
  49801. };
  49802. this._onPointerMoveHandlerRef = function (evt) {
  49803. _this._onPointerMove(evt);
  49804. };
  49805. this._onPointerOutHandlerRef = function (evt) {
  49806. _this._onPointerUp(evt);
  49807. };
  49808. this._onPointerUpHandlerRef = function (evt) {
  49809. _this._onPointerUp(evt);
  49810. };
  49811. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  49812. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  49813. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  49814. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  49815. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  49816. evt.preventDefault(); // Disables system menu
  49817. }, false);
  49818. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  49819. }
  49820. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  49821. this._joystickSensibility = newJoystickSensibility;
  49822. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  49823. };
  49824. VirtualJoystick.prototype._onPointerDown = function (e) {
  49825. var positionOnScreenCondition;
  49826. e.preventDefault();
  49827. if (this._leftJoystick === true) {
  49828. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  49829. }
  49830. else {
  49831. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  49832. }
  49833. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  49834. // First contact will be dedicated to the virtual joystick
  49835. this._joystickPointerID = e.pointerId;
  49836. this._joystickPointerStartPos.x = e.clientX;
  49837. this._joystickPointerStartPos.y = e.clientY;
  49838. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  49839. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  49840. this._deltaJoystickVector.x = 0;
  49841. this._deltaJoystickVector.y = 0;
  49842. this.pressed = true;
  49843. this._touches.add(e.pointerId.toString(), e);
  49844. }
  49845. else {
  49846. // You can only trigger the action buttons with a joystick declared
  49847. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  49848. this._action();
  49849. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  49850. }
  49851. }
  49852. };
  49853. VirtualJoystick.prototype._onPointerMove = function (e) {
  49854. // If the current pointer is the one associated to the joystick (first touch contact)
  49855. if (this._joystickPointerID == e.pointerId) {
  49856. this._joystickPointerPos.x = e.clientX;
  49857. this._joystickPointerPos.y = e.clientY;
  49858. this._deltaJoystickVector = this._joystickPointerPos.clone();
  49859. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  49860. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  49861. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  49862. switch (this._axisTargetedByLeftAndRight) {
  49863. case JoystickAxis.X:
  49864. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  49865. break;
  49866. case JoystickAxis.Y:
  49867. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  49868. break;
  49869. case JoystickAxis.Z:
  49870. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  49871. break;
  49872. }
  49873. var directionUpDown = this.reverseUpDown ? 1 : -1;
  49874. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  49875. switch (this._axisTargetedByUpAndDown) {
  49876. case JoystickAxis.X:
  49877. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  49878. break;
  49879. case JoystickAxis.Y:
  49880. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  49881. break;
  49882. case JoystickAxis.Z:
  49883. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  49884. break;
  49885. }
  49886. }
  49887. else {
  49888. var data = this._touches.get(e.pointerId.toString());
  49889. if (data) {
  49890. data.x = e.clientX;
  49891. data.y = e.clientY;
  49892. }
  49893. }
  49894. };
  49895. VirtualJoystick.prototype._onPointerUp = function (e) {
  49896. if (this._joystickPointerID == e.pointerId) {
  49897. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  49898. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  49899. this._joystickPointerID = -1;
  49900. this.pressed = false;
  49901. }
  49902. else {
  49903. var touch = this._touches.get(e.pointerId.toString());
  49904. if (touch) {
  49905. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  49906. }
  49907. }
  49908. this._deltaJoystickVector.x = 0;
  49909. this._deltaJoystickVector.y = 0;
  49910. this._touches.remove(e.pointerId.toString());
  49911. };
  49912. /**
  49913. * Change the color of the virtual joystick
  49914. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  49915. */
  49916. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  49917. this._joystickColor = newColor;
  49918. };
  49919. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  49920. this._action = action;
  49921. };
  49922. // Define which axis you'd like to control for left & right
  49923. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  49924. switch (axis) {
  49925. case JoystickAxis.X:
  49926. case JoystickAxis.Y:
  49927. case JoystickAxis.Z:
  49928. this._axisTargetedByLeftAndRight = axis;
  49929. break;
  49930. default:
  49931. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  49932. break;
  49933. }
  49934. };
  49935. // Define which axis you'd like to control for up & down
  49936. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  49937. switch (axis) {
  49938. case JoystickAxis.X:
  49939. case JoystickAxis.Y:
  49940. case JoystickAxis.Z:
  49941. this._axisTargetedByUpAndDown = axis;
  49942. break;
  49943. default:
  49944. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  49945. break;
  49946. }
  49947. };
  49948. VirtualJoystick.prototype._clearCanvas = function () {
  49949. if (this._leftJoystick) {
  49950. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  49951. }
  49952. else {
  49953. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  49954. }
  49955. };
  49956. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  49957. var _this = this;
  49958. if (this.pressed) {
  49959. this._touches.forEach(function (key, touch) {
  49960. if (touch.pointerId === _this._joystickPointerID) {
  49961. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  49962. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  49963. VirtualJoystick.vjCanvasContext.beginPath();
  49964. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  49965. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  49966. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  49967. VirtualJoystick.vjCanvasContext.stroke();
  49968. VirtualJoystick.vjCanvasContext.closePath();
  49969. VirtualJoystick.vjCanvasContext.beginPath();
  49970. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  49971. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  49972. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  49973. VirtualJoystick.vjCanvasContext.stroke();
  49974. VirtualJoystick.vjCanvasContext.closePath();
  49975. VirtualJoystick.vjCanvasContext.beginPath();
  49976. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  49977. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  49978. VirtualJoystick.vjCanvasContext.stroke();
  49979. VirtualJoystick.vjCanvasContext.closePath();
  49980. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  49981. }
  49982. else {
  49983. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  49984. VirtualJoystick.vjCanvasContext.beginPath();
  49985. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  49986. VirtualJoystick.vjCanvasContext.beginPath();
  49987. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  49988. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  49989. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  49990. VirtualJoystick.vjCanvasContext.stroke();
  49991. VirtualJoystick.vjCanvasContext.closePath();
  49992. touch.prevX = touch.x;
  49993. touch.prevY = touch.y;
  49994. }
  49995. ;
  49996. });
  49997. }
  49998. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  49999. };
  50000. VirtualJoystick.prototype.releaseCanvas = function () {
  50001. if (VirtualJoystick.vjCanvas) {
  50002. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  50003. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  50004. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  50005. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  50006. window.removeEventListener("resize", this._onResize);
  50007. document.body.removeChild(VirtualJoystick.vjCanvas);
  50008. VirtualJoystick.vjCanvas = null;
  50009. }
  50010. };
  50011. return VirtualJoystick;
  50012. }());
  50013. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  50014. VirtualJoystick._globalJoystickIndex = 0;
  50015. BABYLON.VirtualJoystick = VirtualJoystick;
  50016. })(BABYLON || (BABYLON = {}));
  50017. //# sourceMappingURL=babylon.virtualJoystick.js.map
  50018. var BABYLON;
  50019. (function (BABYLON) {
  50020. // We're mainly based on the logic defined into the FreeCamera code
  50021. var VirtualJoysticksCamera = (function (_super) {
  50022. __extends(VirtualJoysticksCamera, _super);
  50023. function VirtualJoysticksCamera(name, position, scene) {
  50024. var _this = _super.call(this, name, position, scene) || this;
  50025. _this.inputs.addVirtualJoystick();
  50026. return _this;
  50027. }
  50028. VirtualJoysticksCamera.prototype.getClassName = function () {
  50029. return "VirtualJoysticksCamera";
  50030. };
  50031. return VirtualJoysticksCamera;
  50032. }(BABYLON.FreeCamera));
  50033. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  50034. })(BABYLON || (BABYLON = {}));
  50035. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  50036. var BABYLON;
  50037. (function (BABYLON) {
  50038. var FreeCameraVirtualJoystickInput = (function () {
  50039. function FreeCameraVirtualJoystickInput() {
  50040. }
  50041. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  50042. return this._leftjoystick;
  50043. };
  50044. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  50045. return this._rightjoystick;
  50046. };
  50047. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  50048. if (this._leftjoystick) {
  50049. var camera = this.camera;
  50050. var speed = camera._computeLocalCameraSpeed() * 50;
  50051. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  50052. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  50053. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  50054. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  50055. if (!this._leftjoystick.pressed) {
  50056. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  50057. }
  50058. if (!this._rightjoystick.pressed) {
  50059. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  50060. }
  50061. }
  50062. };
  50063. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  50064. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  50065. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  50066. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  50067. this._leftjoystick.setJoystickSensibility(0.15);
  50068. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  50069. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  50070. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  50071. this._rightjoystick.reverseUpDown = true;
  50072. this._rightjoystick.setJoystickSensibility(0.05);
  50073. this._rightjoystick.setJoystickColor("yellow");
  50074. };
  50075. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  50076. this._leftjoystick.releaseCanvas();
  50077. this._rightjoystick.releaseCanvas();
  50078. };
  50079. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  50080. return "FreeCameraVirtualJoystickInput";
  50081. };
  50082. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  50083. return "virtualJoystick";
  50084. };
  50085. return FreeCameraVirtualJoystickInput;
  50086. }());
  50087. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  50088. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  50089. })(BABYLON || (BABYLON = {}));
  50090. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  50091. var BABYLON;
  50092. (function (BABYLON) {
  50093. var AnaglyphPostProcess = (function (_super) {
  50094. __extends(AnaglyphPostProcess, _super);
  50095. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  50096. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  50097. _this._passedProcess = rigCameras[0]._rigPostProcess;
  50098. _this.onApplyObservable.add(function (effect) {
  50099. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  50100. });
  50101. return _this;
  50102. }
  50103. return AnaglyphPostProcess;
  50104. }(BABYLON.PostProcess));
  50105. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  50106. })(BABYLON || (BABYLON = {}));
  50107. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  50108. var BABYLON;
  50109. (function (BABYLON) {
  50110. var OutlineRenderer = (function () {
  50111. function OutlineRenderer(scene) {
  50112. this._scene = scene;
  50113. }
  50114. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  50115. var _this = this;
  50116. if (useOverlay === void 0) { useOverlay = false; }
  50117. var scene = this._scene;
  50118. var engine = this._scene.getEngine();
  50119. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  50120. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  50121. return;
  50122. }
  50123. var mesh = subMesh.getRenderingMesh();
  50124. var material = subMesh.getMaterial();
  50125. engine.enableEffect(this._effect);
  50126. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  50127. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  50128. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  50129. // Bones
  50130. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50131. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50132. }
  50133. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  50134. // Alpha test
  50135. if (material && material.needAlphaTesting()) {
  50136. var alphaTexture = material.getAlphaTestTexture();
  50137. this._effect.setTexture("diffuseSampler", alphaTexture);
  50138. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50139. }
  50140. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  50141. };
  50142. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  50143. var defines = [];
  50144. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  50145. var mesh = subMesh.getMesh();
  50146. var material = subMesh.getMaterial();
  50147. // Alpha test
  50148. if (material && material.needAlphaTesting()) {
  50149. defines.push("#define ALPHATEST");
  50150. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50151. attribs.push(BABYLON.VertexBuffer.UVKind);
  50152. defines.push("#define UV1");
  50153. }
  50154. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50155. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50156. defines.push("#define UV2");
  50157. }
  50158. }
  50159. // Bones
  50160. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50161. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50162. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50163. if (mesh.numBoneInfluencers > 4) {
  50164. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50165. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50166. }
  50167. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50168. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50169. }
  50170. else {
  50171. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50172. }
  50173. // Instances
  50174. if (useInstances) {
  50175. defines.push("#define INSTANCES");
  50176. attribs.push("world0");
  50177. attribs.push("world1");
  50178. attribs.push("world2");
  50179. attribs.push("world3");
  50180. }
  50181. // Get correct effect
  50182. var join = defines.join("\n");
  50183. if (this._cachedDefines !== join) {
  50184. this._cachedDefines = join;
  50185. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  50186. }
  50187. return this._effect.isReady();
  50188. };
  50189. return OutlineRenderer;
  50190. }());
  50191. BABYLON.OutlineRenderer = OutlineRenderer;
  50192. })(BABYLON || (BABYLON = {}));
  50193. //# sourceMappingURL=babylon.outlineRenderer.js.map
  50194. var BABYLON;
  50195. (function (BABYLON) {
  50196. var MeshAssetTask = (function () {
  50197. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  50198. this.name = name;
  50199. this.meshesNames = meshesNames;
  50200. this.rootUrl = rootUrl;
  50201. this.sceneFilename = sceneFilename;
  50202. this.isCompleted = false;
  50203. }
  50204. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50205. var _this = this;
  50206. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  50207. _this.loadedMeshes = meshes;
  50208. _this.loadedParticleSystems = particleSystems;
  50209. _this.loadedSkeletons = skeletons;
  50210. _this.isCompleted = true;
  50211. if (_this.onSuccess) {
  50212. _this.onSuccess(_this);
  50213. }
  50214. onSuccess();
  50215. }, null, function () {
  50216. if (_this.onError) {
  50217. _this.onError(_this);
  50218. }
  50219. onError();
  50220. });
  50221. };
  50222. return MeshAssetTask;
  50223. }());
  50224. BABYLON.MeshAssetTask = MeshAssetTask;
  50225. var TextFileAssetTask = (function () {
  50226. function TextFileAssetTask(name, url) {
  50227. this.name = name;
  50228. this.url = url;
  50229. this.isCompleted = false;
  50230. }
  50231. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50232. var _this = this;
  50233. BABYLON.Tools.LoadFile(this.url, function (data) {
  50234. _this.text = data;
  50235. _this.isCompleted = true;
  50236. if (_this.onSuccess) {
  50237. _this.onSuccess(_this);
  50238. }
  50239. onSuccess();
  50240. }, null, scene.database, false, function () {
  50241. if (_this.onError) {
  50242. _this.onError(_this);
  50243. }
  50244. onError();
  50245. });
  50246. };
  50247. return TextFileAssetTask;
  50248. }());
  50249. BABYLON.TextFileAssetTask = TextFileAssetTask;
  50250. var BinaryFileAssetTask = (function () {
  50251. function BinaryFileAssetTask(name, url) {
  50252. this.name = name;
  50253. this.url = url;
  50254. this.isCompleted = false;
  50255. }
  50256. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50257. var _this = this;
  50258. BABYLON.Tools.LoadFile(this.url, function (data) {
  50259. _this.data = data;
  50260. _this.isCompleted = true;
  50261. if (_this.onSuccess) {
  50262. _this.onSuccess(_this);
  50263. }
  50264. onSuccess();
  50265. }, null, scene.database, true, function () {
  50266. if (_this.onError) {
  50267. _this.onError(_this);
  50268. }
  50269. onError();
  50270. });
  50271. };
  50272. return BinaryFileAssetTask;
  50273. }());
  50274. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  50275. var ImageAssetTask = (function () {
  50276. function ImageAssetTask(name, url) {
  50277. this.name = name;
  50278. this.url = url;
  50279. this.isCompleted = false;
  50280. }
  50281. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50282. var _this = this;
  50283. var img = new Image();
  50284. BABYLON.Tools.SetCorsBehavior(this.url, img);
  50285. img.onload = function () {
  50286. _this.image = img;
  50287. _this.isCompleted = true;
  50288. if (_this.onSuccess) {
  50289. _this.onSuccess(_this);
  50290. }
  50291. onSuccess();
  50292. };
  50293. img.onerror = function () {
  50294. if (_this.onError) {
  50295. _this.onError(_this);
  50296. }
  50297. onError();
  50298. };
  50299. img.src = this.url;
  50300. };
  50301. return ImageAssetTask;
  50302. }());
  50303. BABYLON.ImageAssetTask = ImageAssetTask;
  50304. var TextureAssetTask = (function () {
  50305. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  50306. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50307. this.name = name;
  50308. this.url = url;
  50309. this.noMipmap = noMipmap;
  50310. this.invertY = invertY;
  50311. this.samplingMode = samplingMode;
  50312. this.isCompleted = false;
  50313. }
  50314. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50315. var _this = this;
  50316. var onload = function () {
  50317. _this.isCompleted = true;
  50318. if (_this.onSuccess) {
  50319. _this.onSuccess(_this);
  50320. }
  50321. onSuccess();
  50322. };
  50323. var onerror = function () {
  50324. if (_this.onError) {
  50325. _this.onError(_this);
  50326. }
  50327. onError();
  50328. };
  50329. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  50330. };
  50331. return TextureAssetTask;
  50332. }());
  50333. BABYLON.TextureAssetTask = TextureAssetTask;
  50334. var CubeTextureAssetTask = (function () {
  50335. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  50336. this.name = name;
  50337. this.url = url;
  50338. this.extensions = extensions;
  50339. this.noMipmap = noMipmap;
  50340. this.files = files;
  50341. this.isCompleted = false;
  50342. }
  50343. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50344. var _this = this;
  50345. var onload = function () {
  50346. _this.isCompleted = true;
  50347. if (_this.onSuccess) {
  50348. _this.onSuccess(_this);
  50349. }
  50350. onSuccess();
  50351. };
  50352. var onerror = function () {
  50353. if (_this.onError) {
  50354. _this.onError(_this);
  50355. }
  50356. onError();
  50357. };
  50358. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  50359. };
  50360. return CubeTextureAssetTask;
  50361. }());
  50362. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  50363. var HDRCubeTextureAssetTask = (function () {
  50364. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  50365. if (noMipmap === void 0) { noMipmap = false; }
  50366. if (generateHarmonics === void 0) { generateHarmonics = true; }
  50367. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  50368. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  50369. this.name = name;
  50370. this.url = url;
  50371. this.size = size;
  50372. this.noMipmap = noMipmap;
  50373. this.generateHarmonics = generateHarmonics;
  50374. this.useInGammaSpace = useInGammaSpace;
  50375. this.usePMREMGenerator = usePMREMGenerator;
  50376. this.isCompleted = false;
  50377. }
  50378. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50379. var _this = this;
  50380. var onload = function () {
  50381. _this.isCompleted = true;
  50382. if (_this.onSuccess) {
  50383. _this.onSuccess(_this);
  50384. }
  50385. onSuccess();
  50386. };
  50387. var onerror = function () {
  50388. if (_this.onError) {
  50389. _this.onError(_this);
  50390. }
  50391. onError();
  50392. };
  50393. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  50394. };
  50395. return HDRCubeTextureAssetTask;
  50396. }());
  50397. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  50398. var AssetsManager = (function () {
  50399. function AssetsManager(scene) {
  50400. this.tasks = new Array();
  50401. this.waitingTasksCount = 0;
  50402. this.useDefaultLoadingScreen = true;
  50403. this._scene = scene;
  50404. }
  50405. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  50406. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  50407. this.tasks.push(task);
  50408. return task;
  50409. };
  50410. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  50411. var task = new TextFileAssetTask(taskName, url);
  50412. this.tasks.push(task);
  50413. return task;
  50414. };
  50415. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  50416. var task = new BinaryFileAssetTask(taskName, url);
  50417. this.tasks.push(task);
  50418. return task;
  50419. };
  50420. AssetsManager.prototype.addImageTask = function (taskName, url) {
  50421. var task = new ImageAssetTask(taskName, url);
  50422. this.tasks.push(task);
  50423. return task;
  50424. };
  50425. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  50426. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50427. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  50428. this.tasks.push(task);
  50429. return task;
  50430. };
  50431. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  50432. this.waitingTasksCount--;
  50433. if (this.waitingTasksCount === 0) {
  50434. if (this.onFinish) {
  50435. this.onFinish(this.tasks);
  50436. }
  50437. this._scene.getEngine().hideLoadingUI();
  50438. }
  50439. };
  50440. AssetsManager.prototype._runTask = function (task) {
  50441. var _this = this;
  50442. task.run(this._scene, function () {
  50443. if (_this.onTaskSuccess) {
  50444. _this.onTaskSuccess(task);
  50445. }
  50446. _this._decreaseWaitingTasksCount();
  50447. }, function () {
  50448. if (_this.onTaskError) {
  50449. _this.onTaskError(task);
  50450. }
  50451. _this._decreaseWaitingTasksCount();
  50452. });
  50453. };
  50454. AssetsManager.prototype.reset = function () {
  50455. this.tasks = new Array();
  50456. return this;
  50457. };
  50458. AssetsManager.prototype.load = function () {
  50459. this.waitingTasksCount = this.tasks.length;
  50460. if (this.waitingTasksCount === 0) {
  50461. if (this.onFinish) {
  50462. this.onFinish(this.tasks);
  50463. }
  50464. return this;
  50465. }
  50466. if (this.useDefaultLoadingScreen) {
  50467. this._scene.getEngine().displayLoadingUI();
  50468. }
  50469. for (var index = 0; index < this.tasks.length; index++) {
  50470. var task = this.tasks[index];
  50471. this._runTask(task);
  50472. }
  50473. return this;
  50474. };
  50475. return AssetsManager;
  50476. }());
  50477. BABYLON.AssetsManager = AssetsManager;
  50478. })(BABYLON || (BABYLON = {}));
  50479. //# sourceMappingURL=babylon.assetsManager.js.map
  50480. var BABYLON;
  50481. (function (BABYLON) {
  50482. var VRCameraMetrics = (function () {
  50483. function VRCameraMetrics() {
  50484. this.compensateDistortion = true;
  50485. }
  50486. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  50487. get: function () {
  50488. return this.hResolution / (2 * this.vResolution);
  50489. },
  50490. enumerable: true,
  50491. configurable: true
  50492. });
  50493. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  50494. get: function () {
  50495. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  50496. },
  50497. enumerable: true,
  50498. configurable: true
  50499. });
  50500. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  50501. get: function () {
  50502. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  50503. var h = (4 * meters) / this.hScreenSize;
  50504. return BABYLON.Matrix.Translation(h, 0, 0);
  50505. },
  50506. enumerable: true,
  50507. configurable: true
  50508. });
  50509. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  50510. get: function () {
  50511. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  50512. var h = (4 * meters) / this.hScreenSize;
  50513. return BABYLON.Matrix.Translation(-h, 0, 0);
  50514. },
  50515. enumerable: true,
  50516. configurable: true
  50517. });
  50518. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  50519. get: function () {
  50520. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  50521. },
  50522. enumerable: true,
  50523. configurable: true
  50524. });
  50525. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  50526. get: function () {
  50527. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  50528. },
  50529. enumerable: true,
  50530. configurable: true
  50531. });
  50532. VRCameraMetrics.GetDefault = function () {
  50533. var result = new VRCameraMetrics();
  50534. result.hResolution = 1280;
  50535. result.vResolution = 800;
  50536. result.hScreenSize = 0.149759993;
  50537. result.vScreenSize = 0.0935999975;
  50538. result.vScreenCenter = 0.0467999987;
  50539. result.eyeToScreenDistance = 0.0410000011;
  50540. result.lensSeparationDistance = 0.0635000020;
  50541. result.interpupillaryDistance = 0.0640000030;
  50542. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  50543. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  50544. result.postProcessScaleFactor = 1.714605507808412;
  50545. result.lensCenterOffset = 0.151976421;
  50546. return result;
  50547. };
  50548. return VRCameraMetrics;
  50549. }());
  50550. BABYLON.VRCameraMetrics = VRCameraMetrics;
  50551. })(BABYLON || (BABYLON = {}));
  50552. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  50553. var BABYLON;
  50554. (function (BABYLON) {
  50555. var WebVRFreeCamera = (function (_super) {
  50556. __extends(WebVRFreeCamera, _super);
  50557. function WebVRFreeCamera(name, position, scene, webVROptions) {
  50558. if (webVROptions === void 0) { webVROptions = {}; }
  50559. var _this = _super.call(this, name, position, scene) || this;
  50560. _this.webVROptions = webVROptions;
  50561. _this._vrDevice = null;
  50562. _this.rawPose = null;
  50563. _this._vrEnabled = false;
  50564. _this._attached = false;
  50565. _this._positionOffset = BABYLON.Vector3.Zero();
  50566. _this._descendants = [];
  50567. _this.devicePosition = BABYLON.Vector3.Zero();
  50568. _this.deviceScaleFactor = 1;
  50569. _this.controllers = [];
  50570. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  50571. //legacy support - the compensation boolean was removed.
  50572. if (arguments.length === 5) {
  50573. _this.webVROptions = arguments[4];
  50574. }
  50575. // default webVR options
  50576. if (_this.webVROptions.trackPosition == undefined) {
  50577. _this.webVROptions.trackPosition = true;
  50578. }
  50579. if (_this.webVROptions.controllerMeshes == undefined) {
  50580. _this.webVROptions.controllerMeshes = true;
  50581. }
  50582. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  50583. _this.webVROptions.defaultLightningOnControllers = true;
  50584. }
  50585. _this.rotationQuaternion = new BABYLON.Quaternion();
  50586. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  50587. if (_this.webVROptions && _this.webVROptions.positionScale) {
  50588. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  50589. }
  50590. //enable VR
  50591. _this.getEngine().initWebVR();
  50592. if (!_this.getEngine().vrDisplaysPromise) {
  50593. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  50594. }
  50595. else {
  50596. _this._frameData = new VRFrameData();
  50597. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  50598. if (devices.length > 0) {
  50599. _this._vrEnabled = true;
  50600. if (_this.webVROptions.displayName) {
  50601. var found = devices.some(function (device) {
  50602. if (device.displayName === _this.webVROptions.displayName) {
  50603. _this._vrDevice = device;
  50604. return true;
  50605. }
  50606. else {
  50607. return false;
  50608. }
  50609. });
  50610. if (!found) {
  50611. _this._vrDevice = devices[0];
  50612. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  50613. }
  50614. }
  50615. else {
  50616. //choose the first one
  50617. _this._vrDevice = devices[0];
  50618. }
  50619. //reset the rig parameters.
  50620. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData });
  50621. if (_this._attached) {
  50622. _this.getEngine().enableVR(_this._vrDevice);
  50623. }
  50624. }
  50625. else {
  50626. BABYLON.Tools.Error("No WebVR devices found!");
  50627. }
  50628. });
  50629. }
  50630. // try to attach the controllers, if found.
  50631. _this.initControllers();
  50632. /**
  50633. * The idea behind the following lines:
  50634. * objects that have the camera as parent should actually have the rig cameras as a parent.
  50635. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  50636. * the second will not show it correctly.
  50637. *
  50638. * To solve this - each object that has the camera as parent will be added to a protected array.
  50639. * When the rig camera renders, it will take this array and set all of those to be its children.
  50640. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  50641. * Amazing!
  50642. */
  50643. scene.onBeforeCameraRenderObservable.add(function (camera) {
  50644. if (camera.parent === _this && _this.rigParenting) {
  50645. _this._descendants = _this.getDescendants(true, function (n) {
  50646. // don't take the cameras or the controllers!
  50647. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  50648. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  50649. return !isController && !isRigCamera;
  50650. });
  50651. _this._descendants.forEach(function (node) {
  50652. node.parent = camera;
  50653. });
  50654. }
  50655. });
  50656. scene.onAfterCameraRenderObservable.add(function (camera) {
  50657. if (camera.parent === _this && _this.rigParenting) {
  50658. _this._descendants.forEach(function (node) {
  50659. node.parent = _this;
  50660. });
  50661. }
  50662. });
  50663. return _this;
  50664. }
  50665. WebVRFreeCamera.prototype._checkInputs = function () {
  50666. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  50667. var currentPose = this._frameData.pose;
  50668. this.updateFromDevice(currentPose);
  50669. }
  50670. _super.prototype._checkInputs.call(this);
  50671. };
  50672. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  50673. if (poseData && poseData.orientation) {
  50674. this.rawPose = poseData;
  50675. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  50676. if (this.getScene().useRightHandedSystem) {
  50677. this.deviceRotationQuaternion.z *= -1;
  50678. this.deviceRotationQuaternion.w *= -1;
  50679. }
  50680. if (this.webVROptions.trackPosition && this.rawPose.position) {
  50681. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  50682. if (this.getScene().useRightHandedSystem) {
  50683. this.devicePosition.z *= -1;
  50684. }
  50685. }
  50686. }
  50687. };
  50688. /**
  50689. * WebVR's attach control will start broadcasting frames to the device.
  50690. * Note that in certain browsers (chrome for example) this function must be called
  50691. * within a user-interaction callback. Example:
  50692. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  50693. *
  50694. * @param {HTMLElement} element
  50695. * @param {boolean} [noPreventDefault]
  50696. *
  50697. * @memberOf WebVRFreeCamera
  50698. */
  50699. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  50700. _super.prototype.attachControl.call(this, element, noPreventDefault);
  50701. this._attached = true;
  50702. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  50703. if (this._vrEnabled) {
  50704. this.getEngine().enableVR(this._vrDevice);
  50705. }
  50706. };
  50707. WebVRFreeCamera.prototype.detachControl = function (element) {
  50708. _super.prototype.detachControl.call(this, element);
  50709. this._vrEnabled = false;
  50710. this._attached = false;
  50711. this.getEngine().disableVR();
  50712. };
  50713. WebVRFreeCamera.prototype.getClassName = function () {
  50714. return "WebVRFreeCamera";
  50715. };
  50716. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  50717. //uses the vrDisplay's "resetPose()".
  50718. //pitch and roll won't be affected.
  50719. this._vrDevice.resetPose();
  50720. };
  50721. WebVRFreeCamera.prototype._updateRigCameras = function () {
  50722. var camLeft = this._rigCameras[0];
  50723. var camRight = this._rigCameras[1];
  50724. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  50725. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  50726. camLeft.position.copyFrom(this.devicePosition);
  50727. camRight.position.copyFrom(this.devicePosition);
  50728. };
  50729. /**
  50730. * This function is called by the two RIG cameras.
  50731. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  50732. */
  50733. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  50734. var _this = this;
  50735. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  50736. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  50737. if (!this.getScene().useRightHandedSystem) {
  50738. [2, 6, 8, 9, 14].forEach(function (num) {
  50739. _this._webvrViewMatrix.m[num] *= -1;
  50740. });
  50741. }
  50742. var parentCamera = this._cameraRigParams["parentCamera"];
  50743. // should the view matrix be updated with scale and position offset?
  50744. if (parentCamera.deviceScaleFactor !== 1) {
  50745. this._webvrViewMatrix.invert();
  50746. // scale the position, if set
  50747. if (parentCamera.deviceScaleFactor) {
  50748. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  50749. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  50750. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  50751. }
  50752. this._webvrViewMatrix.invert();
  50753. }
  50754. // update the camera rotation matrix
  50755. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  50756. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  50757. // Computing target and final matrix
  50758. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  50759. return this._webvrViewMatrix;
  50760. };
  50761. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  50762. var _this = this;
  50763. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  50764. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  50765. //babylon compatible matrix
  50766. if (!this.getScene().useRightHandedSystem) {
  50767. [8, 9, 10, 11].forEach(function (num) {
  50768. _this._projectionMatrix.m[num] *= -1;
  50769. });
  50770. }
  50771. return this._projectionMatrix;
  50772. };
  50773. WebVRFreeCamera.prototype.initControllers = function () {
  50774. var _this = this;
  50775. this.controllers = [];
  50776. new BABYLON.Gamepads(function (gp) {
  50777. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  50778. var webVrController = gp;
  50779. if (_this.webVROptions.controllerMeshes) {
  50780. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  50781. if (_this.webVROptions.defaultLightningOnControllers) {
  50782. if (!_this._lightOnControllers) {
  50783. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  50784. }
  50785. loadedMesh.getChildren().forEach(function (mesh) {
  50786. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  50787. });
  50788. }
  50789. });
  50790. }
  50791. webVrController.attachToPoseControlledCamera(_this);
  50792. // since this is async - sanity check. Is the controller already stored?
  50793. if (_this.controllers.indexOf(webVrController) === -1) {
  50794. //add to the controllers array
  50795. _this.controllers.push(webVrController);
  50796. //did we find enough controllers? Great! let the developer know.
  50797. if (_this.onControllersAttached && _this.controllers.length === 2) {
  50798. _this.onControllersAttached(_this.controllers);
  50799. }
  50800. }
  50801. }
  50802. });
  50803. };
  50804. return WebVRFreeCamera;
  50805. }(BABYLON.FreeCamera));
  50806. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  50807. })(BABYLON || (BABYLON = {}));
  50808. //# sourceMappingURL=babylon.webVRCamera.js.map
  50809. var BABYLON;
  50810. (function (BABYLON) {
  50811. // Standard optimizations
  50812. var SceneOptimization = (function () {
  50813. function SceneOptimization(priority) {
  50814. if (priority === void 0) { priority = 0; }
  50815. this.priority = priority;
  50816. this.apply = function (scene) {
  50817. return true; // Return true if everything that can be done was applied
  50818. };
  50819. }
  50820. return SceneOptimization;
  50821. }());
  50822. BABYLON.SceneOptimization = SceneOptimization;
  50823. var TextureOptimization = (function (_super) {
  50824. __extends(TextureOptimization, _super);
  50825. function TextureOptimization(priority, maximumSize) {
  50826. if (priority === void 0) { priority = 0; }
  50827. if (maximumSize === void 0) { maximumSize = 1024; }
  50828. var _this = _super.call(this, priority) || this;
  50829. _this.priority = priority;
  50830. _this.maximumSize = maximumSize;
  50831. _this.apply = function (scene) {
  50832. var allDone = true;
  50833. for (var index = 0; index < scene.textures.length; index++) {
  50834. var texture = scene.textures[index];
  50835. if (!texture.canRescale) {
  50836. continue;
  50837. }
  50838. var currentSize = texture.getSize();
  50839. var maxDimension = Math.max(currentSize.width, currentSize.height);
  50840. if (maxDimension > _this.maximumSize) {
  50841. texture.scale(0.5);
  50842. allDone = false;
  50843. }
  50844. }
  50845. return allDone;
  50846. };
  50847. return _this;
  50848. }
  50849. return TextureOptimization;
  50850. }(SceneOptimization));
  50851. BABYLON.TextureOptimization = TextureOptimization;
  50852. var HardwareScalingOptimization = (function (_super) {
  50853. __extends(HardwareScalingOptimization, _super);
  50854. function HardwareScalingOptimization(priority, maximumScale) {
  50855. if (priority === void 0) { priority = 0; }
  50856. if (maximumScale === void 0) { maximumScale = 2; }
  50857. var _this = _super.call(this, priority) || this;
  50858. _this.priority = priority;
  50859. _this.maximumScale = maximumScale;
  50860. _this._currentScale = 1;
  50861. _this.apply = function (scene) {
  50862. _this._currentScale++;
  50863. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  50864. return _this._currentScale >= _this.maximumScale;
  50865. };
  50866. return _this;
  50867. }
  50868. return HardwareScalingOptimization;
  50869. }(SceneOptimization));
  50870. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  50871. var ShadowsOptimization = (function (_super) {
  50872. __extends(ShadowsOptimization, _super);
  50873. function ShadowsOptimization() {
  50874. var _this = _super !== null && _super.apply(this, arguments) || this;
  50875. _this.apply = function (scene) {
  50876. scene.shadowsEnabled = false;
  50877. return true;
  50878. };
  50879. return _this;
  50880. }
  50881. return ShadowsOptimization;
  50882. }(SceneOptimization));
  50883. BABYLON.ShadowsOptimization = ShadowsOptimization;
  50884. var PostProcessesOptimization = (function (_super) {
  50885. __extends(PostProcessesOptimization, _super);
  50886. function PostProcessesOptimization() {
  50887. var _this = _super !== null && _super.apply(this, arguments) || this;
  50888. _this.apply = function (scene) {
  50889. scene.postProcessesEnabled = false;
  50890. return true;
  50891. };
  50892. return _this;
  50893. }
  50894. return PostProcessesOptimization;
  50895. }(SceneOptimization));
  50896. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  50897. var LensFlaresOptimization = (function (_super) {
  50898. __extends(LensFlaresOptimization, _super);
  50899. function LensFlaresOptimization() {
  50900. var _this = _super !== null && _super.apply(this, arguments) || this;
  50901. _this.apply = function (scene) {
  50902. scene.lensFlaresEnabled = false;
  50903. return true;
  50904. };
  50905. return _this;
  50906. }
  50907. return LensFlaresOptimization;
  50908. }(SceneOptimization));
  50909. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  50910. var ParticlesOptimization = (function (_super) {
  50911. __extends(ParticlesOptimization, _super);
  50912. function ParticlesOptimization() {
  50913. var _this = _super !== null && _super.apply(this, arguments) || this;
  50914. _this.apply = function (scene) {
  50915. scene.particlesEnabled = false;
  50916. return true;
  50917. };
  50918. return _this;
  50919. }
  50920. return ParticlesOptimization;
  50921. }(SceneOptimization));
  50922. BABYLON.ParticlesOptimization = ParticlesOptimization;
  50923. var RenderTargetsOptimization = (function (_super) {
  50924. __extends(RenderTargetsOptimization, _super);
  50925. function RenderTargetsOptimization() {
  50926. var _this = _super !== null && _super.apply(this, arguments) || this;
  50927. _this.apply = function (scene) {
  50928. scene.renderTargetsEnabled = false;
  50929. return true;
  50930. };
  50931. return _this;
  50932. }
  50933. return RenderTargetsOptimization;
  50934. }(SceneOptimization));
  50935. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  50936. var MergeMeshesOptimization = (function (_super) {
  50937. __extends(MergeMeshesOptimization, _super);
  50938. function MergeMeshesOptimization() {
  50939. var _this = _super !== null && _super.apply(this, arguments) || this;
  50940. _this._canBeMerged = function (abstractMesh) {
  50941. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  50942. return false;
  50943. }
  50944. var mesh = abstractMesh;
  50945. if (!mesh.isVisible || !mesh.isEnabled()) {
  50946. return false;
  50947. }
  50948. if (mesh.instances.length > 0) {
  50949. return false;
  50950. }
  50951. if (mesh.skeleton || mesh.hasLODLevels) {
  50952. return false;
  50953. }
  50954. if (mesh.parent) {
  50955. return false;
  50956. }
  50957. return true;
  50958. };
  50959. _this.apply = function (scene, updateSelectionTree) {
  50960. var globalPool = scene.meshes.slice(0);
  50961. var globalLength = globalPool.length;
  50962. for (var index = 0; index < globalLength; index++) {
  50963. var currentPool = new Array();
  50964. var current = globalPool[index];
  50965. // Checks
  50966. if (!_this._canBeMerged(current)) {
  50967. continue;
  50968. }
  50969. currentPool.push(current);
  50970. // Find compatible meshes
  50971. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  50972. var otherMesh = globalPool[subIndex];
  50973. if (!_this._canBeMerged(otherMesh)) {
  50974. continue;
  50975. }
  50976. if (otherMesh.material !== current.material) {
  50977. continue;
  50978. }
  50979. if (otherMesh.checkCollisions !== current.checkCollisions) {
  50980. continue;
  50981. }
  50982. currentPool.push(otherMesh);
  50983. globalLength--;
  50984. globalPool.splice(subIndex, 1);
  50985. subIndex--;
  50986. }
  50987. if (currentPool.length < 2) {
  50988. continue;
  50989. }
  50990. // Merge meshes
  50991. BABYLON.Mesh.MergeMeshes(currentPool);
  50992. }
  50993. if (updateSelectionTree != undefined) {
  50994. if (updateSelectionTree) {
  50995. scene.createOrUpdateSelectionOctree();
  50996. }
  50997. }
  50998. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  50999. scene.createOrUpdateSelectionOctree();
  51000. }
  51001. return true;
  51002. };
  51003. return _this;
  51004. }
  51005. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  51006. get: function () {
  51007. return MergeMeshesOptimization._UpdateSelectionTree;
  51008. },
  51009. set: function (value) {
  51010. MergeMeshesOptimization._UpdateSelectionTree = value;
  51011. },
  51012. enumerable: true,
  51013. configurable: true
  51014. });
  51015. return MergeMeshesOptimization;
  51016. }(SceneOptimization));
  51017. MergeMeshesOptimization._UpdateSelectionTree = false;
  51018. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  51019. // Options
  51020. var SceneOptimizerOptions = (function () {
  51021. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  51022. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  51023. if (trackerDuration === void 0) { trackerDuration = 2000; }
  51024. this.targetFrameRate = targetFrameRate;
  51025. this.trackerDuration = trackerDuration;
  51026. this.optimizations = new Array();
  51027. }
  51028. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  51029. var result = new SceneOptimizerOptions(targetFrameRate);
  51030. var priority = 0;
  51031. result.optimizations.push(new MergeMeshesOptimization(priority));
  51032. result.optimizations.push(new ShadowsOptimization(priority));
  51033. result.optimizations.push(new LensFlaresOptimization(priority));
  51034. // Next priority
  51035. priority++;
  51036. result.optimizations.push(new PostProcessesOptimization(priority));
  51037. result.optimizations.push(new ParticlesOptimization(priority));
  51038. // Next priority
  51039. priority++;
  51040. result.optimizations.push(new TextureOptimization(priority, 1024));
  51041. return result;
  51042. };
  51043. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  51044. var result = new SceneOptimizerOptions(targetFrameRate);
  51045. var priority = 0;
  51046. result.optimizations.push(new MergeMeshesOptimization(priority));
  51047. result.optimizations.push(new ShadowsOptimization(priority));
  51048. result.optimizations.push(new LensFlaresOptimization(priority));
  51049. // Next priority
  51050. priority++;
  51051. result.optimizations.push(new PostProcessesOptimization(priority));
  51052. result.optimizations.push(new ParticlesOptimization(priority));
  51053. // Next priority
  51054. priority++;
  51055. result.optimizations.push(new TextureOptimization(priority, 512));
  51056. // Next priority
  51057. priority++;
  51058. result.optimizations.push(new RenderTargetsOptimization(priority));
  51059. // Next priority
  51060. priority++;
  51061. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  51062. return result;
  51063. };
  51064. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  51065. var result = new SceneOptimizerOptions(targetFrameRate);
  51066. var priority = 0;
  51067. result.optimizations.push(new MergeMeshesOptimization(priority));
  51068. result.optimizations.push(new ShadowsOptimization(priority));
  51069. result.optimizations.push(new LensFlaresOptimization(priority));
  51070. // Next priority
  51071. priority++;
  51072. result.optimizations.push(new PostProcessesOptimization(priority));
  51073. result.optimizations.push(new ParticlesOptimization(priority));
  51074. // Next priority
  51075. priority++;
  51076. result.optimizations.push(new TextureOptimization(priority, 256));
  51077. // Next priority
  51078. priority++;
  51079. result.optimizations.push(new RenderTargetsOptimization(priority));
  51080. // Next priority
  51081. priority++;
  51082. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  51083. return result;
  51084. };
  51085. return SceneOptimizerOptions;
  51086. }());
  51087. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  51088. // Scene optimizer tool
  51089. var SceneOptimizer = (function () {
  51090. function SceneOptimizer() {
  51091. }
  51092. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  51093. // TODO: add an epsilon
  51094. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  51095. if (onSuccess) {
  51096. onSuccess();
  51097. }
  51098. return;
  51099. }
  51100. // Apply current level of optimizations
  51101. var allDone = true;
  51102. var noOptimizationApplied = true;
  51103. for (var index = 0; index < options.optimizations.length; index++) {
  51104. var optimization = options.optimizations[index];
  51105. if (optimization.priority === currentPriorityLevel) {
  51106. noOptimizationApplied = false;
  51107. allDone = allDone && optimization.apply(scene);
  51108. }
  51109. }
  51110. // If no optimization was applied, this is a failure :(
  51111. if (noOptimizationApplied) {
  51112. if (onFailure) {
  51113. onFailure();
  51114. }
  51115. return;
  51116. }
  51117. // If all optimizations were done, move to next level
  51118. if (allDone) {
  51119. currentPriorityLevel++;
  51120. }
  51121. // Let's the system running for a specific amount of time before checking FPS
  51122. scene.executeWhenReady(function () {
  51123. setTimeout(function () {
  51124. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  51125. }, options.trackerDuration);
  51126. });
  51127. };
  51128. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  51129. if (!options) {
  51130. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  51131. }
  51132. // Let's the system running for a specific amount of time before checking FPS
  51133. scene.executeWhenReady(function () {
  51134. setTimeout(function () {
  51135. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  51136. }, options.trackerDuration);
  51137. });
  51138. };
  51139. return SceneOptimizer;
  51140. }());
  51141. BABYLON.SceneOptimizer = SceneOptimizer;
  51142. })(BABYLON || (BABYLON = {}));
  51143. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  51144. var BABYLON;
  51145. (function (BABYLON) {
  51146. var Internals;
  51147. (function (Internals) {
  51148. var MeshLODLevel = (function () {
  51149. function MeshLODLevel(distance, mesh) {
  51150. this.distance = distance;
  51151. this.mesh = mesh;
  51152. }
  51153. return MeshLODLevel;
  51154. }());
  51155. Internals.MeshLODLevel = MeshLODLevel;
  51156. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51157. })(BABYLON || (BABYLON = {}));
  51158. //# sourceMappingURL=babylon.meshLODLevel.js.map
  51159. var BABYLON;
  51160. (function (BABYLON) {
  51161. var RawTexture = (function (_super) {
  51162. __extends(RawTexture, _super);
  51163. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  51164. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51165. if (invertY === void 0) { invertY = false; }
  51166. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51167. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51168. _this.format = format;
  51169. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  51170. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51171. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51172. return _this;
  51173. }
  51174. RawTexture.prototype.update = function (data) {
  51175. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  51176. };
  51177. // Statics
  51178. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51179. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51180. if (invertY === void 0) { invertY = false; }
  51181. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51182. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  51183. };
  51184. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51185. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51186. if (invertY === void 0) { invertY = false; }
  51187. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51188. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51189. };
  51190. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51191. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51192. if (invertY === void 0) { invertY = false; }
  51193. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51194. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51195. };
  51196. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51197. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51198. if (invertY === void 0) { invertY = false; }
  51199. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51200. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  51201. };
  51202. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51203. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51204. if (invertY === void 0) { invertY = false; }
  51205. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51206. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  51207. };
  51208. return RawTexture;
  51209. }(BABYLON.Texture));
  51210. BABYLON.RawTexture = RawTexture;
  51211. })(BABYLON || (BABYLON = {}));
  51212. //# sourceMappingURL=babylon.rawTexture.js.map
  51213. /// <reference path="..\Math\babylon.math.ts" />
  51214. var BABYLON;
  51215. (function (BABYLON) {
  51216. var IndexedVector2 = (function (_super) {
  51217. __extends(IndexedVector2, _super);
  51218. function IndexedVector2(original, index) {
  51219. var _this = _super.call(this, original.x, original.y) || this;
  51220. _this.index = index;
  51221. return _this;
  51222. }
  51223. return IndexedVector2;
  51224. }(BABYLON.Vector2));
  51225. var PolygonPoints = (function () {
  51226. function PolygonPoints() {
  51227. this.elements = new Array();
  51228. }
  51229. PolygonPoints.prototype.add = function (originalPoints) {
  51230. var _this = this;
  51231. var result = new Array();
  51232. originalPoints.forEach(function (point) {
  51233. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  51234. var newPoint = new IndexedVector2(point, _this.elements.length);
  51235. result.push(newPoint);
  51236. _this.elements.push(newPoint);
  51237. }
  51238. });
  51239. return result;
  51240. };
  51241. PolygonPoints.prototype.computeBounds = function () {
  51242. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  51243. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  51244. this.elements.forEach(function (point) {
  51245. // x
  51246. if (point.x < lmin.x) {
  51247. lmin.x = point.x;
  51248. }
  51249. else if (point.x > lmax.x) {
  51250. lmax.x = point.x;
  51251. }
  51252. // y
  51253. if (point.y < lmin.y) {
  51254. lmin.y = point.y;
  51255. }
  51256. else if (point.y > lmax.y) {
  51257. lmax.y = point.y;
  51258. }
  51259. });
  51260. return {
  51261. min: lmin,
  51262. max: lmax,
  51263. width: lmax.x - lmin.x,
  51264. height: lmax.y - lmin.y
  51265. };
  51266. };
  51267. return PolygonPoints;
  51268. }());
  51269. var Polygon = (function () {
  51270. function Polygon() {
  51271. }
  51272. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  51273. return [
  51274. new BABYLON.Vector2(xmin, ymin),
  51275. new BABYLON.Vector2(xmax, ymin),
  51276. new BABYLON.Vector2(xmax, ymax),
  51277. new BABYLON.Vector2(xmin, ymax)
  51278. ];
  51279. };
  51280. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  51281. if (cx === void 0) { cx = 0; }
  51282. if (cy === void 0) { cy = 0; }
  51283. if (numberOfSides === void 0) { numberOfSides = 32; }
  51284. var result = new Array();
  51285. var angle = 0;
  51286. var increment = (Math.PI * 2) / numberOfSides;
  51287. for (var i = 0; i < numberOfSides; i++) {
  51288. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  51289. angle -= increment;
  51290. }
  51291. return result;
  51292. };
  51293. Polygon.Parse = function (input) {
  51294. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  51295. var i, result = [];
  51296. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  51297. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  51298. }
  51299. return result;
  51300. };
  51301. Polygon.StartingAt = function (x, y) {
  51302. return BABYLON.Path2.StartingAt(x, y);
  51303. };
  51304. return Polygon;
  51305. }());
  51306. BABYLON.Polygon = Polygon;
  51307. var PolygonMeshBuilder = (function () {
  51308. function PolygonMeshBuilder(name, contours, scene) {
  51309. this._points = new PolygonPoints();
  51310. this._outlinepoints = new PolygonPoints();
  51311. this._holes = [];
  51312. this._epoints = new Array();
  51313. this._eholes = new Array();
  51314. this._name = name;
  51315. this._scene = scene;
  51316. var points;
  51317. if (contours instanceof BABYLON.Path2) {
  51318. points = contours.getPoints();
  51319. }
  51320. else {
  51321. points = contours;
  51322. }
  51323. this._addToepoint(points);
  51324. this._points.add(points);
  51325. this._outlinepoints.add(points);
  51326. }
  51327. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  51328. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  51329. var p = points_1[_i];
  51330. this._epoints.push(p.x, p.y);
  51331. }
  51332. };
  51333. PolygonMeshBuilder.prototype.addHole = function (hole) {
  51334. this._points.add(hole);
  51335. var holepoints = new PolygonPoints();
  51336. holepoints.add(hole);
  51337. this._holes.push(holepoints);
  51338. this._eholes.push(this._epoints.length / 2);
  51339. this._addToepoint(hole);
  51340. return this;
  51341. };
  51342. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  51343. var _this = this;
  51344. if (updatable === void 0) { updatable = false; }
  51345. var result = new BABYLON.Mesh(this._name, this._scene);
  51346. var normals = [];
  51347. var positions = [];
  51348. var uvs = [];
  51349. var bounds = this._points.computeBounds();
  51350. this._points.elements.forEach(function (p) {
  51351. normals.push(0, 1.0, 0);
  51352. positions.push(p.x, 0, p.y);
  51353. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  51354. });
  51355. var indices = [];
  51356. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  51357. for (var i = 0; i < res.length; i++) {
  51358. indices.push(res[i]);
  51359. }
  51360. if (depth > 0) {
  51361. var positionscount = (positions.length / 3); //get the current pointcount
  51362. this._points.elements.forEach(function (p) {
  51363. normals.push(0, -1.0, 0);
  51364. positions.push(p.x, -depth, p.y);
  51365. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  51366. });
  51367. var totalCount = indices.length;
  51368. for (var i = 0; i < totalCount; i += 3) {
  51369. var i0 = indices[i + 0];
  51370. var i1 = indices[i + 1];
  51371. var i2 = indices[i + 2];
  51372. indices.push(i2 + positionscount);
  51373. indices.push(i1 + positionscount);
  51374. indices.push(i0 + positionscount);
  51375. }
  51376. //Add the sides
  51377. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  51378. this._holes.forEach(function (hole) {
  51379. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  51380. });
  51381. }
  51382. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  51383. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  51384. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  51385. result.setIndices(indices);
  51386. return result;
  51387. };
  51388. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  51389. var StartIndex = positions.length / 3;
  51390. var ulength = 0;
  51391. for (var i = 0; i < points.elements.length; i++) {
  51392. var p = points.elements[i];
  51393. var p1;
  51394. if ((i + 1) > points.elements.length - 1) {
  51395. p1 = points.elements[0];
  51396. }
  51397. else {
  51398. p1 = points.elements[i + 1];
  51399. }
  51400. positions.push(p.x, 0, p.y);
  51401. positions.push(p.x, -depth, p.y);
  51402. positions.push(p1.x, 0, p1.y);
  51403. positions.push(p1.x, -depth, p1.y);
  51404. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  51405. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  51406. var v3 = v2.subtract(v1);
  51407. var v4 = new BABYLON.Vector3(0, 1, 0);
  51408. var vn = BABYLON.Vector3.Cross(v3, v4);
  51409. vn = vn.normalize();
  51410. uvs.push(ulength / bounds.width, 0);
  51411. uvs.push(ulength / bounds.width, 1);
  51412. ulength += v3.length();
  51413. uvs.push((ulength / bounds.width), 0);
  51414. uvs.push((ulength / bounds.width), 1);
  51415. if (!flip) {
  51416. normals.push(-vn.x, -vn.y, -vn.z);
  51417. normals.push(-vn.x, -vn.y, -vn.z);
  51418. normals.push(-vn.x, -vn.y, -vn.z);
  51419. normals.push(-vn.x, -vn.y, -vn.z);
  51420. indices.push(StartIndex);
  51421. indices.push(StartIndex + 1);
  51422. indices.push(StartIndex + 2);
  51423. indices.push(StartIndex + 1);
  51424. indices.push(StartIndex + 3);
  51425. indices.push(StartIndex + 2);
  51426. }
  51427. else {
  51428. normals.push(vn.x, vn.y, vn.z);
  51429. normals.push(vn.x, vn.y, vn.z);
  51430. normals.push(vn.x, vn.y, vn.z);
  51431. normals.push(vn.x, vn.y, vn.z);
  51432. indices.push(StartIndex);
  51433. indices.push(StartIndex + 2);
  51434. indices.push(StartIndex + 1);
  51435. indices.push(StartIndex + 1);
  51436. indices.push(StartIndex + 2);
  51437. indices.push(StartIndex + 3);
  51438. }
  51439. StartIndex += 4;
  51440. }
  51441. ;
  51442. };
  51443. return PolygonMeshBuilder;
  51444. }());
  51445. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  51446. })(BABYLON || (BABYLON = {}));
  51447. //# sourceMappingURL=babylon.polygonMesh.js.map
  51448. var BABYLON;
  51449. (function (BABYLON) {
  51450. var Octree = (function () {
  51451. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  51452. if (maxDepth === void 0) { maxDepth = 2; }
  51453. this.maxDepth = maxDepth;
  51454. this.dynamicContent = new Array();
  51455. this._maxBlockCapacity = maxBlockCapacity || 64;
  51456. this._selectionContent = new BABYLON.SmartArray(1024);
  51457. this._creationFunc = creationFunc;
  51458. }
  51459. // Methods
  51460. Octree.prototype.update = function (worldMin, worldMax, entries) {
  51461. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  51462. };
  51463. Octree.prototype.addMesh = function (entry) {
  51464. for (var index = 0; index < this.blocks.length; index++) {
  51465. var block = this.blocks[index];
  51466. block.addEntry(entry);
  51467. }
  51468. };
  51469. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  51470. this._selectionContent.reset();
  51471. for (var index = 0; index < this.blocks.length; index++) {
  51472. var block = this.blocks[index];
  51473. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  51474. }
  51475. if (allowDuplicate) {
  51476. this._selectionContent.concat(this.dynamicContent);
  51477. }
  51478. else {
  51479. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51480. }
  51481. return this._selectionContent;
  51482. };
  51483. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  51484. this._selectionContent.reset();
  51485. for (var index = 0; index < this.blocks.length; index++) {
  51486. var block = this.blocks[index];
  51487. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  51488. }
  51489. if (allowDuplicate) {
  51490. this._selectionContent.concat(this.dynamicContent);
  51491. }
  51492. else {
  51493. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51494. }
  51495. return this._selectionContent;
  51496. };
  51497. Octree.prototype.intersectsRay = function (ray) {
  51498. this._selectionContent.reset();
  51499. for (var index = 0; index < this.blocks.length; index++) {
  51500. var block = this.blocks[index];
  51501. block.intersectsRay(ray, this._selectionContent);
  51502. }
  51503. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51504. return this._selectionContent;
  51505. };
  51506. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  51507. target.blocks = new Array();
  51508. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  51509. // Segmenting space
  51510. for (var x = 0; x < 2; x++) {
  51511. for (var y = 0; y < 2; y++) {
  51512. for (var z = 0; z < 2; z++) {
  51513. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  51514. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  51515. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  51516. block.addEntries(entries);
  51517. target.blocks.push(block);
  51518. }
  51519. }
  51520. }
  51521. };
  51522. return Octree;
  51523. }());
  51524. Octree.CreationFuncForMeshes = function (entry, block) {
  51525. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  51526. block.entries.push(entry);
  51527. }
  51528. };
  51529. Octree.CreationFuncForSubMeshes = function (entry, block) {
  51530. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  51531. block.entries.push(entry);
  51532. }
  51533. };
  51534. BABYLON.Octree = Octree;
  51535. })(BABYLON || (BABYLON = {}));
  51536. //# sourceMappingURL=babylon.octree.js.map
  51537. var BABYLON;
  51538. (function (BABYLON) {
  51539. var OctreeBlock = (function () {
  51540. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  51541. this.entries = new Array();
  51542. this._boundingVectors = new Array();
  51543. this._capacity = capacity;
  51544. this._depth = depth;
  51545. this._maxDepth = maxDepth;
  51546. this._creationFunc = creationFunc;
  51547. this._minPoint = minPoint;
  51548. this._maxPoint = maxPoint;
  51549. this._boundingVectors.push(minPoint.clone());
  51550. this._boundingVectors.push(maxPoint.clone());
  51551. this._boundingVectors.push(minPoint.clone());
  51552. this._boundingVectors[2].x = maxPoint.x;
  51553. this._boundingVectors.push(minPoint.clone());
  51554. this._boundingVectors[3].y = maxPoint.y;
  51555. this._boundingVectors.push(minPoint.clone());
  51556. this._boundingVectors[4].z = maxPoint.z;
  51557. this._boundingVectors.push(maxPoint.clone());
  51558. this._boundingVectors[5].z = minPoint.z;
  51559. this._boundingVectors.push(maxPoint.clone());
  51560. this._boundingVectors[6].x = minPoint.x;
  51561. this._boundingVectors.push(maxPoint.clone());
  51562. this._boundingVectors[7].y = minPoint.y;
  51563. }
  51564. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  51565. // Property
  51566. get: function () {
  51567. return this._capacity;
  51568. },
  51569. enumerable: true,
  51570. configurable: true
  51571. });
  51572. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  51573. get: function () {
  51574. return this._minPoint;
  51575. },
  51576. enumerable: true,
  51577. configurable: true
  51578. });
  51579. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  51580. get: function () {
  51581. return this._maxPoint;
  51582. },
  51583. enumerable: true,
  51584. configurable: true
  51585. });
  51586. // Methods
  51587. OctreeBlock.prototype.addEntry = function (entry) {
  51588. if (this.blocks) {
  51589. for (var index = 0; index < this.blocks.length; index++) {
  51590. var block = this.blocks[index];
  51591. block.addEntry(entry);
  51592. }
  51593. return;
  51594. }
  51595. this._creationFunc(entry, this);
  51596. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  51597. this.createInnerBlocks();
  51598. }
  51599. };
  51600. OctreeBlock.prototype.addEntries = function (entries) {
  51601. for (var index = 0; index < entries.length; index++) {
  51602. var mesh = entries[index];
  51603. this.addEntry(mesh);
  51604. }
  51605. };
  51606. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  51607. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  51608. if (this.blocks) {
  51609. for (var index = 0; index < this.blocks.length; index++) {
  51610. var block = this.blocks[index];
  51611. block.select(frustumPlanes, selection, allowDuplicate);
  51612. }
  51613. return;
  51614. }
  51615. if (allowDuplicate) {
  51616. selection.concat(this.entries);
  51617. }
  51618. else {
  51619. selection.concatWithNoDuplicate(this.entries);
  51620. }
  51621. }
  51622. };
  51623. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  51624. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  51625. if (this.blocks) {
  51626. for (var index = 0; index < this.blocks.length; index++) {
  51627. var block = this.blocks[index];
  51628. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  51629. }
  51630. return;
  51631. }
  51632. if (allowDuplicate) {
  51633. selection.concat(this.entries);
  51634. }
  51635. else {
  51636. selection.concatWithNoDuplicate(this.entries);
  51637. }
  51638. }
  51639. };
  51640. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  51641. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  51642. if (this.blocks) {
  51643. for (var index = 0; index < this.blocks.length; index++) {
  51644. var block = this.blocks[index];
  51645. block.intersectsRay(ray, selection);
  51646. }
  51647. return;
  51648. }
  51649. selection.concatWithNoDuplicate(this.entries);
  51650. }
  51651. };
  51652. OctreeBlock.prototype.createInnerBlocks = function () {
  51653. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  51654. };
  51655. return OctreeBlock;
  51656. }());
  51657. BABYLON.OctreeBlock = OctreeBlock;
  51658. })(BABYLON || (BABYLON = {}));
  51659. //# sourceMappingURL=babylon.octreeBlock.js.map
  51660. var BABYLON;
  51661. (function (BABYLON) {
  51662. var BlurPostProcess = (function (_super) {
  51663. __extends(BlurPostProcess, _super);
  51664. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  51665. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51666. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  51667. _this.direction = direction;
  51668. _this.blurWidth = blurWidth;
  51669. _this.onApplyObservable.add(function (effect) {
  51670. effect.setFloat2("screenSize", _this.width, _this.height);
  51671. effect.setVector2("direction", _this.direction);
  51672. effect.setFloat("blurWidth", _this.blurWidth);
  51673. });
  51674. return _this;
  51675. }
  51676. return BlurPostProcess;
  51677. }(BABYLON.PostProcess));
  51678. BABYLON.BlurPostProcess = BlurPostProcess;
  51679. })(BABYLON || (BABYLON = {}));
  51680. //# sourceMappingURL=babylon.blurPostProcess.js.map
  51681. var BABYLON;
  51682. (function (BABYLON) {
  51683. var RefractionPostProcess = (function (_super) {
  51684. __extends(RefractionPostProcess, _super);
  51685. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  51686. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  51687. _this.color = color;
  51688. _this.depth = depth;
  51689. _this.colorLevel = colorLevel;
  51690. _this.onActivateObservable.add(function (cam) {
  51691. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  51692. });
  51693. _this.onApplyObservable.add(function (effect) {
  51694. effect.setColor3("baseColor", _this.color);
  51695. effect.setFloat("depth", _this.depth);
  51696. effect.setFloat("colorLevel", _this.colorLevel);
  51697. effect.setTexture("refractionSampler", _this._refRexture);
  51698. });
  51699. return _this;
  51700. }
  51701. // Methods
  51702. RefractionPostProcess.prototype.dispose = function (camera) {
  51703. if (this._refRexture) {
  51704. this._refRexture.dispose();
  51705. }
  51706. _super.prototype.dispose.call(this, camera);
  51707. };
  51708. return RefractionPostProcess;
  51709. }(BABYLON.PostProcess));
  51710. BABYLON.RefractionPostProcess = RefractionPostProcess;
  51711. })(BABYLON || (BABYLON = {}));
  51712. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  51713. var BABYLON;
  51714. (function (BABYLON) {
  51715. var BlackAndWhitePostProcess = (function (_super) {
  51716. __extends(BlackAndWhitePostProcess, _super);
  51717. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  51718. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  51719. }
  51720. return BlackAndWhitePostProcess;
  51721. }(BABYLON.PostProcess));
  51722. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  51723. })(BABYLON || (BABYLON = {}));
  51724. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  51725. var BABYLON;
  51726. (function (BABYLON) {
  51727. var ConvolutionPostProcess = (function (_super) {
  51728. __extends(ConvolutionPostProcess, _super);
  51729. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  51730. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  51731. _this.kernel = kernel;
  51732. _this.onApply = function (effect) {
  51733. effect.setFloat2("screenSize", _this.width, _this.height);
  51734. effect.setArray("kernel", _this.kernel);
  51735. };
  51736. return _this;
  51737. }
  51738. return ConvolutionPostProcess;
  51739. }(BABYLON.PostProcess));
  51740. // Statics
  51741. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  51742. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  51743. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  51744. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  51745. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  51746. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  51747. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  51748. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  51749. })(BABYLON || (BABYLON = {}));
  51750. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  51751. var BABYLON;
  51752. (function (BABYLON) {
  51753. var FilterPostProcess = (function (_super) {
  51754. __extends(FilterPostProcess, _super);
  51755. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  51756. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  51757. _this.kernelMatrix = kernelMatrix;
  51758. _this.onApply = function (effect) {
  51759. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  51760. };
  51761. return _this;
  51762. }
  51763. return FilterPostProcess;
  51764. }(BABYLON.PostProcess));
  51765. BABYLON.FilterPostProcess = FilterPostProcess;
  51766. })(BABYLON || (BABYLON = {}));
  51767. //# sourceMappingURL=babylon.filterPostProcess.js.map
  51768. var BABYLON;
  51769. (function (BABYLON) {
  51770. var FxaaPostProcess = (function (_super) {
  51771. __extends(FxaaPostProcess, _super);
  51772. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  51773. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable) || this;
  51774. _this.onSizeChangedObservable.add(function () {
  51775. _this.texelWidth = 1.0 / _this.width;
  51776. _this.texelHeight = 1.0 / _this.height;
  51777. });
  51778. _this.onApplyObservable.add(function (effect) {
  51779. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  51780. });
  51781. return _this;
  51782. }
  51783. return FxaaPostProcess;
  51784. }(BABYLON.PostProcess));
  51785. BABYLON.FxaaPostProcess = FxaaPostProcess;
  51786. })(BABYLON || (BABYLON = {}));
  51787. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  51788. var BABYLON;
  51789. (function (BABYLON) {
  51790. var StereoscopicInterlacePostProcess = (function (_super) {
  51791. __extends(StereoscopicInterlacePostProcess, _super);
  51792. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  51793. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  51794. _this._passedProcess = rigCameras[0]._rigPostProcess;
  51795. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  51796. _this.onSizeChangedObservable.add(function () {
  51797. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  51798. });
  51799. _this.onApplyObservable.add(function (effect) {
  51800. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  51801. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  51802. });
  51803. return _this;
  51804. }
  51805. return StereoscopicInterlacePostProcess;
  51806. }(BABYLON.PostProcess));
  51807. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  51808. })(BABYLON || (BABYLON = {}));
  51809. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  51810. var BABYLON;
  51811. (function (BABYLON) {
  51812. var LensFlare = (function () {
  51813. function LensFlare(size, position, color, imgUrl, system) {
  51814. this.size = size;
  51815. this.position = position;
  51816. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  51817. this.dispose = function () {
  51818. if (this.texture) {
  51819. this.texture.dispose();
  51820. }
  51821. // Remove from scene
  51822. var index = this._system.lensFlares.indexOf(this);
  51823. this._system.lensFlares.splice(index, 1);
  51824. };
  51825. this.color = color || new BABYLON.Color3(1, 1, 1);
  51826. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  51827. this._system = system;
  51828. system.lensFlares.push(this);
  51829. }
  51830. return LensFlare;
  51831. }());
  51832. BABYLON.LensFlare = LensFlare;
  51833. })(BABYLON || (BABYLON = {}));
  51834. //# sourceMappingURL=babylon.lensFlare.js.map
  51835. var BABYLON;
  51836. (function (BABYLON) {
  51837. var LensFlareSystem = (function () {
  51838. function LensFlareSystem(name, emitter, scene) {
  51839. this.name = name;
  51840. this.lensFlares = new Array();
  51841. this.borderLimit = 300;
  51842. this.viewportBorder = 0;
  51843. this.layerMask = 0x0FFFFFFF;
  51844. this._vertexBuffers = {};
  51845. this._isEnabled = true;
  51846. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51847. this._emitter = emitter;
  51848. this.id = name;
  51849. scene.lensFlareSystems.push(this);
  51850. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  51851. var engine = scene.getEngine();
  51852. // VBO
  51853. var vertices = [];
  51854. vertices.push(1, 1);
  51855. vertices.push(-1, 1);
  51856. vertices.push(-1, -1);
  51857. vertices.push(1, -1);
  51858. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  51859. // Indices
  51860. var indices = [];
  51861. indices.push(0);
  51862. indices.push(1);
  51863. indices.push(2);
  51864. indices.push(0);
  51865. indices.push(2);
  51866. indices.push(3);
  51867. this._indexBuffer = engine.createIndexBuffer(indices);
  51868. // Effects
  51869. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  51870. }
  51871. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  51872. get: function () {
  51873. return this._isEnabled;
  51874. },
  51875. set: function (value) {
  51876. this._isEnabled = value;
  51877. },
  51878. enumerable: true,
  51879. configurable: true
  51880. });
  51881. LensFlareSystem.prototype.getScene = function () {
  51882. return this._scene;
  51883. };
  51884. LensFlareSystem.prototype.getEmitter = function () {
  51885. return this._emitter;
  51886. };
  51887. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  51888. this._emitter = newEmitter;
  51889. };
  51890. LensFlareSystem.prototype.getEmitterPosition = function () {
  51891. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  51892. };
  51893. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  51894. var position = this.getEmitterPosition();
  51895. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  51896. this._positionX = position.x;
  51897. this._positionY = position.y;
  51898. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  51899. if (this.viewportBorder > 0) {
  51900. globalViewport.x -= this.viewportBorder;
  51901. globalViewport.y -= this.viewportBorder;
  51902. globalViewport.width += this.viewportBorder * 2;
  51903. globalViewport.height += this.viewportBorder * 2;
  51904. position.x += this.viewportBorder;
  51905. position.y += this.viewportBorder;
  51906. this._positionX += this.viewportBorder;
  51907. this._positionY += this.viewportBorder;
  51908. }
  51909. if (position.z > 0) {
  51910. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  51911. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  51912. return true;
  51913. }
  51914. return true;
  51915. }
  51916. return false;
  51917. };
  51918. LensFlareSystem.prototype._isVisible = function () {
  51919. if (!this._isEnabled) {
  51920. return false;
  51921. }
  51922. var emitterPosition = this.getEmitterPosition();
  51923. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  51924. var distance = direction.length();
  51925. direction.normalize();
  51926. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  51927. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  51928. return !pickInfo.hit || pickInfo.distance > distance;
  51929. };
  51930. LensFlareSystem.prototype.render = function () {
  51931. if (!this._effect.isReady())
  51932. return false;
  51933. var engine = this._scene.getEngine();
  51934. var viewport = this._scene.activeCamera.viewport;
  51935. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  51936. // Position
  51937. if (!this.computeEffectivePosition(globalViewport)) {
  51938. return false;
  51939. }
  51940. // Visibility
  51941. if (!this._isVisible()) {
  51942. return false;
  51943. }
  51944. // Intensity
  51945. var awayX;
  51946. var awayY;
  51947. if (this._positionX < this.borderLimit + globalViewport.x) {
  51948. awayX = this.borderLimit + globalViewport.x - this._positionX;
  51949. }
  51950. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  51951. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  51952. }
  51953. else {
  51954. awayX = 0;
  51955. }
  51956. if (this._positionY < this.borderLimit + globalViewport.y) {
  51957. awayY = this.borderLimit + globalViewport.y - this._positionY;
  51958. }
  51959. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  51960. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  51961. }
  51962. else {
  51963. awayY = 0;
  51964. }
  51965. var away = (awayX > awayY) ? awayX : awayY;
  51966. away -= this.viewportBorder;
  51967. if (away > this.borderLimit) {
  51968. away = this.borderLimit;
  51969. }
  51970. var intensity = 1.0 - (away / this.borderLimit);
  51971. if (intensity < 0) {
  51972. return false;
  51973. }
  51974. if (intensity > 1.0) {
  51975. intensity = 1.0;
  51976. }
  51977. if (this.viewportBorder > 0) {
  51978. globalViewport.x += this.viewportBorder;
  51979. globalViewport.y += this.viewportBorder;
  51980. globalViewport.width -= this.viewportBorder * 2;
  51981. globalViewport.height -= this.viewportBorder * 2;
  51982. this._positionX -= this.viewportBorder;
  51983. this._positionY -= this.viewportBorder;
  51984. }
  51985. // Position
  51986. var centerX = globalViewport.x + globalViewport.width / 2;
  51987. var centerY = globalViewport.y + globalViewport.height / 2;
  51988. var distX = centerX - this._positionX;
  51989. var distY = centerY - this._positionY;
  51990. // Effects
  51991. engine.enableEffect(this._effect);
  51992. engine.setState(false);
  51993. engine.setDepthBuffer(false);
  51994. // VBOs
  51995. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  51996. // Flares
  51997. for (var index = 0; index < this.lensFlares.length; index++) {
  51998. var flare = this.lensFlares[index];
  51999. engine.setAlphaMode(flare.alphaMode);
  52000. var x = centerX - (distX * flare.position);
  52001. var y = centerY - (distY * flare.position);
  52002. var cw = flare.size;
  52003. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  52004. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  52005. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  52006. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  52007. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  52008. // Texture
  52009. this._effect.setTexture("textureSampler", flare.texture);
  52010. // Color
  52011. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  52012. // Draw order
  52013. engine.draw(true, 0, 6);
  52014. }
  52015. engine.setDepthBuffer(true);
  52016. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52017. return true;
  52018. };
  52019. LensFlareSystem.prototype.dispose = function () {
  52020. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  52021. if (vertexBuffer) {
  52022. vertexBuffer.dispose();
  52023. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  52024. }
  52025. if (this._indexBuffer) {
  52026. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52027. this._indexBuffer = null;
  52028. }
  52029. while (this.lensFlares.length) {
  52030. this.lensFlares[0].dispose();
  52031. }
  52032. // Remove from scene
  52033. var index = this._scene.lensFlareSystems.indexOf(this);
  52034. this._scene.lensFlareSystems.splice(index, 1);
  52035. };
  52036. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  52037. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  52038. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  52039. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  52040. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  52041. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  52042. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  52043. var parsedFlare = parsedLensFlareSystem.flares[index];
  52044. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  52045. }
  52046. return lensFlareSystem;
  52047. };
  52048. LensFlareSystem.prototype.serialize = function () {
  52049. var serializationObject = {};
  52050. serializationObject.id = this.id;
  52051. serializationObject.name = this.name;
  52052. serializationObject.emitterId = this.getEmitter().id;
  52053. serializationObject.borderLimit = this.borderLimit;
  52054. serializationObject.flares = [];
  52055. for (var index = 0; index < this.lensFlares.length; index++) {
  52056. var flare = this.lensFlares[index];
  52057. serializationObject.flares.push({
  52058. size: flare.size,
  52059. position: flare.position,
  52060. color: flare.color.asArray(),
  52061. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  52062. });
  52063. }
  52064. return serializationObject;
  52065. };
  52066. return LensFlareSystem;
  52067. }());
  52068. BABYLON.LensFlareSystem = LensFlareSystem;
  52069. })(BABYLON || (BABYLON = {}));
  52070. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  52071. /// <reference path="babylon.freeCamera.ts" />
  52072. var BABYLON;
  52073. (function (BABYLON) {
  52074. // We're mainly based on the logic defined into the FreeCamera code
  52075. var DeviceOrientationCamera = (function (_super) {
  52076. __extends(DeviceOrientationCamera, _super);
  52077. function DeviceOrientationCamera(name, position, scene) {
  52078. var _this = _super.call(this, name, position, scene) || this;
  52079. _this._quaternionCache = new BABYLON.Quaternion();
  52080. _this.inputs.addDeviceOrientation();
  52081. return _this;
  52082. }
  52083. DeviceOrientationCamera.prototype.getClassName = function () {
  52084. return "DeviceOrientationCamera";
  52085. };
  52086. DeviceOrientationCamera.prototype._checkInputs = function () {
  52087. _super.prototype._checkInputs.call(this);
  52088. this._quaternionCache.copyFrom(this.rotationQuaternion);
  52089. if (this._initialQuaternion) {
  52090. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  52091. }
  52092. };
  52093. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  52094. var _this = this;
  52095. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  52096. //can only work if this camera has a rotation quaternion already.
  52097. if (!this.rotationQuaternion)
  52098. return;
  52099. if (!this._initialQuaternion) {
  52100. this._initialQuaternion = new BABYLON.Quaternion();
  52101. }
  52102. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  52103. ['x', 'y', 'z'].forEach(function (axisName) {
  52104. if (!axis[axisName]) {
  52105. _this._initialQuaternion[axisName] = 0;
  52106. }
  52107. else {
  52108. _this._initialQuaternion[axisName] *= -1;
  52109. }
  52110. });
  52111. this._initialQuaternion.normalize();
  52112. //force rotation update
  52113. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  52114. };
  52115. return DeviceOrientationCamera;
  52116. }(BABYLON.FreeCamera));
  52117. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  52118. })(BABYLON || (BABYLON = {}));
  52119. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  52120. var BABYLON;
  52121. (function (BABYLON) {
  52122. var VRDeviceOrientationFreeCamera = (function (_super) {
  52123. __extends(VRDeviceOrientationFreeCamera, _super);
  52124. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  52125. if (compensateDistortion === void 0) { compensateDistortion = true; }
  52126. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  52127. var _this = _super.call(this, name, position, scene) || this;
  52128. vrCameraMetrics.compensateDistortion = compensateDistortion;
  52129. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  52130. return _this;
  52131. }
  52132. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  52133. return "VRDeviceOrientationFreeCamera";
  52134. };
  52135. return VRDeviceOrientationFreeCamera;
  52136. }(BABYLON.DeviceOrientationCamera));
  52137. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  52138. var VRDeviceOrientationGamepadCamera = (function (_super) {
  52139. __extends(VRDeviceOrientationGamepadCamera, _super);
  52140. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  52141. if (compensateDistortion === void 0) { compensateDistortion = true; }
  52142. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  52143. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  52144. _this.inputs.addGamepad();
  52145. return _this;
  52146. }
  52147. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  52148. return "VRDeviceOrientationGamepadCamera";
  52149. };
  52150. return VRDeviceOrientationGamepadCamera;
  52151. }(VRDeviceOrientationFreeCamera));
  52152. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  52153. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  52154. __extends(VRDeviceOrientationArcRotateCamera, _super);
  52155. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  52156. if (compensateDistortion === void 0) { compensateDistortion = true; }
  52157. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  52158. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  52159. vrCameraMetrics.compensateDistortion = compensateDistortion;
  52160. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  52161. _this.inputs.addVRDeviceOrientation();
  52162. return _this;
  52163. }
  52164. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  52165. return "VRDeviceOrientationArcRotateCamera";
  52166. };
  52167. return VRDeviceOrientationArcRotateCamera;
  52168. }(BABYLON.ArcRotateCamera));
  52169. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  52170. })(BABYLON || (BABYLON = {}));
  52171. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  52172. /// <reference path="babylon.touchCamera.ts" />
  52173. var BABYLON;
  52174. (function (BABYLON) {
  52175. // We're mainly based on the logic defined into the FreeCamera code
  52176. var UniversalCamera = (function (_super) {
  52177. __extends(UniversalCamera, _super);
  52178. //-- end properties for backward compatibility for inputs
  52179. function UniversalCamera(name, position, scene) {
  52180. var _this = _super.call(this, name, position, scene) || this;
  52181. _this.inputs.addGamepad();
  52182. return _this;
  52183. }
  52184. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  52185. //-- Begin properties for backward compatibility for inputs
  52186. get: function () {
  52187. var gamepad = this.inputs.attached["gamepad"];
  52188. if (gamepad)
  52189. return gamepad.gamepadAngularSensibility;
  52190. },
  52191. set: function (value) {
  52192. var gamepad = this.inputs.attached["gamepad"];
  52193. if (gamepad)
  52194. gamepad.gamepadAngularSensibility = value;
  52195. },
  52196. enumerable: true,
  52197. configurable: true
  52198. });
  52199. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  52200. get: function () {
  52201. var gamepad = this.inputs.attached["gamepad"];
  52202. if (gamepad)
  52203. return gamepad.gamepadMoveSensibility;
  52204. },
  52205. set: function (value) {
  52206. var gamepad = this.inputs.attached["gamepad"];
  52207. if (gamepad)
  52208. gamepad.gamepadMoveSensibility = value;
  52209. },
  52210. enumerable: true,
  52211. configurable: true
  52212. });
  52213. UniversalCamera.prototype.getClassName = function () {
  52214. return "UniversalCamera";
  52215. };
  52216. return UniversalCamera;
  52217. }(BABYLON.TouchCamera));
  52218. BABYLON.UniversalCamera = UniversalCamera;
  52219. })(BABYLON || (BABYLON = {}));
  52220. //# sourceMappingURL=babylon.universalCamera.js.map
  52221. var BABYLON;
  52222. (function (BABYLON) {
  52223. var Gamepads = (function () {
  52224. function Gamepads(ongamedpadconnected) {
  52225. var _this = this;
  52226. this.babylonGamepads = [];
  52227. this.oneGamepadConnected = false;
  52228. this.isMonitoring = false;
  52229. this.gamepadEventSupported = 'GamepadEvent' in window;
  52230. this.gamepadSupport = (navigator.getGamepads ||
  52231. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  52232. this._callbackGamepadConnected = ongamedpadconnected;
  52233. if (this.gamepadSupport) {
  52234. //first add already-connected gamepads
  52235. this._updateGamepadObjects();
  52236. if (this.babylonGamepads.length) {
  52237. this._startMonitoringGamepads();
  52238. }
  52239. // Checking if the gamepad connected event is supported (like in Firefox)
  52240. if (this.gamepadEventSupported) {
  52241. this._onGamepadConnectedEvent = function (evt) {
  52242. _this._onGamepadConnected(evt.gamepad);
  52243. };
  52244. this._onGamepadDisonnectedEvent = function (evt) {
  52245. _this._onGamepadDisconnected(evt);
  52246. };
  52247. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  52248. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  52249. }
  52250. else {
  52251. this._startMonitoringGamepads();
  52252. }
  52253. }
  52254. }
  52255. Gamepads.prototype.dispose = function () {
  52256. if (Gamepads.gamepadDOMInfo) {
  52257. document.body.removeChild(Gamepads.gamepadDOMInfo);
  52258. }
  52259. if (this._onGamepadConnectedEvent) {
  52260. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  52261. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  52262. this._onGamepadConnectedEvent = null;
  52263. this._onGamepadDisonnectedEvent = null;
  52264. }
  52265. };
  52266. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  52267. var newGamepad = this._addNewGamepad(gamepad);
  52268. if (this._callbackGamepadConnected)
  52269. this._callbackGamepadConnected(newGamepad);
  52270. this._startMonitoringGamepads();
  52271. };
  52272. Gamepads.prototype._addNewGamepad = function (gamepad) {
  52273. if (!this.oneGamepadConnected) {
  52274. this.oneGamepadConnected = true;
  52275. if (Gamepads.gamepadDOMInfo) {
  52276. document.body.removeChild(Gamepads.gamepadDOMInfo);
  52277. Gamepads.gamepadDOMInfo = null;
  52278. }
  52279. }
  52280. var newGamepad;
  52281. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  52282. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  52283. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  52284. }
  52285. else if (gamepad.pose) {
  52286. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  52287. }
  52288. else {
  52289. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  52290. }
  52291. this.babylonGamepads.push(newGamepad);
  52292. return newGamepad;
  52293. };
  52294. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  52295. // Remove the gamepad from the list of gamepads to monitor.
  52296. for (var i in this.babylonGamepads) {
  52297. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  52298. this.babylonGamepads.splice(+i, 1);
  52299. break;
  52300. }
  52301. }
  52302. // If no gamepads are left, stop the polling loop.
  52303. if (this.babylonGamepads.length == 0) {
  52304. this._stopMonitoringGamepads();
  52305. }
  52306. };
  52307. Gamepads.prototype._startMonitoringGamepads = function () {
  52308. if (!this.isMonitoring) {
  52309. this.isMonitoring = true;
  52310. this._checkGamepadsStatus();
  52311. }
  52312. };
  52313. Gamepads.prototype._stopMonitoringGamepads = function () {
  52314. this.isMonitoring = false;
  52315. };
  52316. Gamepads.prototype._checkGamepadsStatus = function () {
  52317. var _this = this;
  52318. // updating gamepad objects
  52319. this._updateGamepadObjects();
  52320. for (var i in this.babylonGamepads) {
  52321. this.babylonGamepads[i].update();
  52322. }
  52323. if (this.isMonitoring) {
  52324. if (window.requestAnimationFrame) {
  52325. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52326. }
  52327. else if (window.mozRequestAnimationFrame) {
  52328. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52329. }
  52330. else if (window.webkitRequestAnimationFrame) {
  52331. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52332. }
  52333. }
  52334. };
  52335. // This function is called only on Chrome, which does not yet support
  52336. // connection/disconnection events, but requires you to monitor
  52337. // an array for changes.
  52338. Gamepads.prototype._updateGamepadObjects = function () {
  52339. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  52340. for (var i = 0; i < gamepads.length; i++) {
  52341. if (gamepads[i]) {
  52342. if (!(gamepads[i].index in this.babylonGamepads)) {
  52343. var newGamepad = this._addNewGamepad(gamepads[i]);
  52344. if (this._callbackGamepadConnected) {
  52345. this._callbackGamepadConnected(newGamepad);
  52346. }
  52347. }
  52348. else {
  52349. this.babylonGamepads[i].browserGamepad = gamepads[i];
  52350. }
  52351. }
  52352. }
  52353. };
  52354. return Gamepads;
  52355. }());
  52356. BABYLON.Gamepads = Gamepads;
  52357. var StickValues = (function () {
  52358. function StickValues(x, y) {
  52359. this.x = x;
  52360. this.y = y;
  52361. }
  52362. return StickValues;
  52363. }());
  52364. BABYLON.StickValues = StickValues;
  52365. var Gamepad = (function () {
  52366. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  52367. if (leftStickX === void 0) { leftStickX = 0; }
  52368. if (leftStickY === void 0) { leftStickY = 1; }
  52369. if (rightStickX === void 0) { rightStickX = 2; }
  52370. if (rightStickY === void 0) { rightStickY = 3; }
  52371. this.id = id;
  52372. this.index = index;
  52373. this.browserGamepad = browserGamepad;
  52374. this.type = Gamepad.GAMEPAD;
  52375. this._leftStickAxisX = leftStickX;
  52376. this._leftStickAxisY = leftStickY;
  52377. this._rightStickAxisX = rightStickX;
  52378. this._rightStickAxisY = rightStickY;
  52379. if (this.browserGamepad.axes.length >= 2) {
  52380. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  52381. }
  52382. if (this.browserGamepad.axes.length >= 4) {
  52383. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  52384. }
  52385. }
  52386. Gamepad.prototype.onleftstickchanged = function (callback) {
  52387. this._onleftstickchanged = callback;
  52388. };
  52389. Gamepad.prototype.onrightstickchanged = function (callback) {
  52390. this._onrightstickchanged = callback;
  52391. };
  52392. Object.defineProperty(Gamepad.prototype, "leftStick", {
  52393. get: function () {
  52394. return this._leftStick;
  52395. },
  52396. set: function (newValues) {
  52397. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  52398. this._onleftstickchanged(newValues);
  52399. }
  52400. this._leftStick = newValues;
  52401. },
  52402. enumerable: true,
  52403. configurable: true
  52404. });
  52405. Object.defineProperty(Gamepad.prototype, "rightStick", {
  52406. get: function () {
  52407. return this._rightStick;
  52408. },
  52409. set: function (newValues) {
  52410. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  52411. this._onrightstickchanged(newValues);
  52412. }
  52413. this._rightStick = newValues;
  52414. },
  52415. enumerable: true,
  52416. configurable: true
  52417. });
  52418. Gamepad.prototype.update = function () {
  52419. if (this._leftStick) {
  52420. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  52421. }
  52422. if (this._rightStick) {
  52423. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  52424. }
  52425. };
  52426. return Gamepad;
  52427. }());
  52428. Gamepad.GAMEPAD = 0;
  52429. Gamepad.GENERIC = 1;
  52430. Gamepad.XBOX = 2;
  52431. Gamepad.POSE_ENABLED = 3;
  52432. BABYLON.Gamepad = Gamepad;
  52433. var GenericPad = (function (_super) {
  52434. __extends(GenericPad, _super);
  52435. function GenericPad(id, index, gamepad) {
  52436. var _this = _super.call(this, id, index, gamepad) || this;
  52437. _this.id = id;
  52438. _this.index = index;
  52439. _this.gamepad = gamepad;
  52440. _this.type = Gamepad.GENERIC;
  52441. _this._buttons = new Array(gamepad.buttons.length);
  52442. return _this;
  52443. }
  52444. GenericPad.prototype.onbuttondown = function (callback) {
  52445. this._onbuttondown = callback;
  52446. };
  52447. GenericPad.prototype.onbuttonup = function (callback) {
  52448. this._onbuttonup = callback;
  52449. };
  52450. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  52451. if (newValue !== currentValue) {
  52452. if (this._onbuttondown && newValue === 1) {
  52453. this._onbuttondown(buttonIndex);
  52454. }
  52455. if (this._onbuttonup && newValue === 0) {
  52456. this._onbuttonup(buttonIndex);
  52457. }
  52458. }
  52459. return newValue;
  52460. };
  52461. GenericPad.prototype.update = function () {
  52462. _super.prototype.update.call(this);
  52463. for (var index = 0; index < this._buttons.length; index++) {
  52464. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  52465. }
  52466. };
  52467. return GenericPad;
  52468. }(Gamepad));
  52469. BABYLON.GenericPad = GenericPad;
  52470. var Xbox360Button;
  52471. (function (Xbox360Button) {
  52472. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  52473. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  52474. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  52475. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  52476. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  52477. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  52478. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  52479. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  52480. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  52481. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  52482. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  52483. var Xbox360Dpad;
  52484. (function (Xbox360Dpad) {
  52485. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  52486. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  52487. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  52488. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  52489. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  52490. var Xbox360Pad = (function (_super) {
  52491. __extends(Xbox360Pad, _super);
  52492. function Xbox360Pad(id, index, gamepad, xboxOne) {
  52493. if (xboxOne === void 0) { xboxOne = false; }
  52494. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  52495. _this._leftTrigger = 0;
  52496. _this._rightTrigger = 0;
  52497. _this._buttonA = 0;
  52498. _this._buttonB = 0;
  52499. _this._buttonX = 0;
  52500. _this._buttonY = 0;
  52501. _this._buttonBack = 0;
  52502. _this._buttonStart = 0;
  52503. _this._buttonLB = 0;
  52504. _this._buttonRB = 0;
  52505. _this._buttonLeftStick = 0;
  52506. _this._buttonRightStick = 0;
  52507. _this._dPadUp = 0;
  52508. _this._dPadDown = 0;
  52509. _this._dPadLeft = 0;
  52510. _this._dPadRight = 0;
  52511. _this._isXboxOnePad = false;
  52512. _this.type = Gamepad.XBOX;
  52513. _this._isXboxOnePad = xboxOne;
  52514. return _this;
  52515. }
  52516. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  52517. this._onlefttriggerchanged = callback;
  52518. };
  52519. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  52520. this._onrighttriggerchanged = callback;
  52521. };
  52522. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  52523. get: function () {
  52524. return this._leftTrigger;
  52525. },
  52526. set: function (newValue) {
  52527. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  52528. this._onlefttriggerchanged(newValue);
  52529. }
  52530. this._leftTrigger = newValue;
  52531. },
  52532. enumerable: true,
  52533. configurable: true
  52534. });
  52535. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  52536. get: function () {
  52537. return this._rightTrigger;
  52538. },
  52539. set: function (newValue) {
  52540. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  52541. this._onrighttriggerchanged(newValue);
  52542. }
  52543. this._rightTrigger = newValue;
  52544. },
  52545. enumerable: true,
  52546. configurable: true
  52547. });
  52548. Xbox360Pad.prototype.onbuttondown = function (callback) {
  52549. this._onbuttondown = callback;
  52550. };
  52551. Xbox360Pad.prototype.onbuttonup = function (callback) {
  52552. this._onbuttonup = callback;
  52553. };
  52554. Xbox360Pad.prototype.ondpaddown = function (callback) {
  52555. this._ondpaddown = callback;
  52556. };
  52557. Xbox360Pad.prototype.ondpadup = function (callback) {
  52558. this._ondpadup = callback;
  52559. };
  52560. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  52561. if (newValue !== currentValue) {
  52562. if (this._onbuttondown && newValue === 1) {
  52563. this._onbuttondown(buttonType);
  52564. }
  52565. if (this._onbuttonup && newValue === 0) {
  52566. this._onbuttonup(buttonType);
  52567. }
  52568. }
  52569. return newValue;
  52570. };
  52571. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  52572. if (newValue !== currentValue) {
  52573. if (this._ondpaddown && newValue === 1) {
  52574. this._ondpaddown(buttonType);
  52575. }
  52576. if (this._ondpadup && newValue === 0) {
  52577. this._ondpadup(buttonType);
  52578. }
  52579. }
  52580. return newValue;
  52581. };
  52582. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  52583. get: function () {
  52584. return this._buttonA;
  52585. },
  52586. set: function (value) {
  52587. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  52588. },
  52589. enumerable: true,
  52590. configurable: true
  52591. });
  52592. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  52593. get: function () {
  52594. return this._buttonB;
  52595. },
  52596. set: function (value) {
  52597. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  52598. },
  52599. enumerable: true,
  52600. configurable: true
  52601. });
  52602. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  52603. get: function () {
  52604. return this._buttonX;
  52605. },
  52606. set: function (value) {
  52607. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  52608. },
  52609. enumerable: true,
  52610. configurable: true
  52611. });
  52612. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  52613. get: function () {
  52614. return this._buttonY;
  52615. },
  52616. set: function (value) {
  52617. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  52618. },
  52619. enumerable: true,
  52620. configurable: true
  52621. });
  52622. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  52623. get: function () {
  52624. return this._buttonStart;
  52625. },
  52626. set: function (value) {
  52627. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  52628. },
  52629. enumerable: true,
  52630. configurable: true
  52631. });
  52632. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  52633. get: function () {
  52634. return this._buttonBack;
  52635. },
  52636. set: function (value) {
  52637. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  52638. },
  52639. enumerable: true,
  52640. configurable: true
  52641. });
  52642. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  52643. get: function () {
  52644. return this._buttonLB;
  52645. },
  52646. set: function (value) {
  52647. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  52648. },
  52649. enumerable: true,
  52650. configurable: true
  52651. });
  52652. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  52653. get: function () {
  52654. return this._buttonRB;
  52655. },
  52656. set: function (value) {
  52657. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  52658. },
  52659. enumerable: true,
  52660. configurable: true
  52661. });
  52662. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  52663. get: function () {
  52664. return this._buttonLeftStick;
  52665. },
  52666. set: function (value) {
  52667. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  52668. },
  52669. enumerable: true,
  52670. configurable: true
  52671. });
  52672. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  52673. get: function () {
  52674. return this._buttonRightStick;
  52675. },
  52676. set: function (value) {
  52677. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  52678. },
  52679. enumerable: true,
  52680. configurable: true
  52681. });
  52682. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  52683. get: function () {
  52684. return this._dPadUp;
  52685. },
  52686. set: function (value) {
  52687. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  52688. },
  52689. enumerable: true,
  52690. configurable: true
  52691. });
  52692. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  52693. get: function () {
  52694. return this._dPadDown;
  52695. },
  52696. set: function (value) {
  52697. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  52698. },
  52699. enumerable: true,
  52700. configurable: true
  52701. });
  52702. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  52703. get: function () {
  52704. return this._dPadLeft;
  52705. },
  52706. set: function (value) {
  52707. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  52708. },
  52709. enumerable: true,
  52710. configurable: true
  52711. });
  52712. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  52713. get: function () {
  52714. return this._dPadRight;
  52715. },
  52716. set: function (value) {
  52717. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  52718. },
  52719. enumerable: true,
  52720. configurable: true
  52721. });
  52722. Xbox360Pad.prototype.update = function () {
  52723. _super.prototype.update.call(this);
  52724. if (this._isXboxOnePad) {
  52725. this.buttonA = this.browserGamepad.buttons[0].value;
  52726. this.buttonB = this.browserGamepad.buttons[1].value;
  52727. this.buttonX = this.browserGamepad.buttons[2].value;
  52728. this.buttonY = this.browserGamepad.buttons[3].value;
  52729. this.buttonLB = this.browserGamepad.buttons[4].value;
  52730. this.buttonRB = this.browserGamepad.buttons[5].value;
  52731. this.leftTrigger = this.browserGamepad.axes[2];
  52732. this.rightTrigger = this.browserGamepad.axes[5];
  52733. this.buttonBack = this.browserGamepad.buttons[9].value;
  52734. this.buttonStart = this.browserGamepad.buttons[8].value;
  52735. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  52736. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  52737. this.dPadUp = this.browserGamepad.buttons[11].value;
  52738. this.dPadDown = this.browserGamepad.buttons[12].value;
  52739. this.dPadLeft = this.browserGamepad.buttons[13].value;
  52740. this.dPadRight = this.browserGamepad.buttons[14].value;
  52741. }
  52742. else {
  52743. this.buttonA = this.browserGamepad.buttons[0].value;
  52744. this.buttonB = this.browserGamepad.buttons[1].value;
  52745. this.buttonX = this.browserGamepad.buttons[2].value;
  52746. this.buttonY = this.browserGamepad.buttons[3].value;
  52747. this.buttonLB = this.browserGamepad.buttons[4].value;
  52748. this.buttonRB = this.browserGamepad.buttons[5].value;
  52749. this.leftTrigger = this.browserGamepad.buttons[6].value;
  52750. this.rightTrigger = this.browserGamepad.buttons[7].value;
  52751. this.buttonBack = this.browserGamepad.buttons[8].value;
  52752. this.buttonStart = this.browserGamepad.buttons[9].value;
  52753. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  52754. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  52755. this.dPadUp = this.browserGamepad.buttons[12].value;
  52756. this.dPadDown = this.browserGamepad.buttons[13].value;
  52757. this.dPadLeft = this.browserGamepad.buttons[14].value;
  52758. this.dPadRight = this.browserGamepad.buttons[15].value;
  52759. }
  52760. };
  52761. return Xbox360Pad;
  52762. }(Gamepad));
  52763. BABYLON.Xbox360Pad = Xbox360Pad;
  52764. })(BABYLON || (BABYLON = {}));
  52765. //# sourceMappingURL=babylon.gamepads.js.map
  52766. var BABYLON;
  52767. (function (BABYLON) {
  52768. var PoseEnabledControllerType;
  52769. (function (PoseEnabledControllerType) {
  52770. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  52771. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  52772. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  52773. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  52774. var PoseEnabledControllerHelper = (function () {
  52775. function PoseEnabledControllerHelper() {
  52776. }
  52777. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  52778. // for now, only Oculus and Vive are supported
  52779. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  52780. return new OculusTouchController(vrGamepad);
  52781. }
  52782. else {
  52783. return new ViveController(vrGamepad);
  52784. }
  52785. };
  52786. return PoseEnabledControllerHelper;
  52787. }());
  52788. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  52789. var PoseEnabledController = (function (_super) {
  52790. __extends(PoseEnabledController, _super);
  52791. function PoseEnabledController(vrGamepad) {
  52792. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  52793. _this.vrGamepad = vrGamepad;
  52794. _this.deviceScaleFactor = 1;
  52795. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  52796. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  52797. _this.controllerType = PoseEnabledControllerType.GENERIC;
  52798. _this.position = BABYLON.Vector3.Zero();
  52799. _this.rotationQuaternion = new BABYLON.Quaternion();
  52800. _this.devicePosition = BABYLON.Vector3.Zero();
  52801. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  52802. _this._calculatedPosition = BABYLON.Vector3.Zero();
  52803. _this._calculatedRotation = new BABYLON.Quaternion();
  52804. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  52805. return _this;
  52806. }
  52807. PoseEnabledController.prototype.update = function () {
  52808. _super.prototype.update.call(this);
  52809. // update this device's offset position from the attached camera, if provided
  52810. //if (this._poseControlledCamera && this._poseControlledCamera.deviceScaleFactor) {
  52811. //this.position.copyFrom(this._poseControlledCamera.position);
  52812. //this.rotationQuaternion.copyFrom(this._poseControlledCamera.rotationQuaternion);
  52813. //this.deviceScaleFactor = this._poseControlledCamera.deviceScaleFactor;
  52814. //}
  52815. var pose = this.vrGamepad.pose;
  52816. this.updateFromDevice(pose);
  52817. if (this._mesh) {
  52818. this._mesh.position.copyFrom(this._calculatedPosition);
  52819. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  52820. }
  52821. };
  52822. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  52823. if (poseData) {
  52824. this.rawPose = poseData;
  52825. if (poseData.position) {
  52826. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  52827. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  52828. this.devicePosition.z *= -1;
  52829. }
  52830. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  52831. this._calculatedPosition.addInPlace(this.position);
  52832. // scale the position using the scale factor, add the device's position
  52833. /*if (this._poseControlledCamera) {
  52834. // this allows total positioning freedom - the device, the camera and the mesh can be individually controlled.
  52835. this._calculatedPosition.addInPlace(this._poseControlledCamera.position);
  52836. }*/
  52837. }
  52838. if (poseData.orientation) {
  52839. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  52840. if (this._mesh) {
  52841. if (this._mesh.getScene().useRightHandedSystem) {
  52842. this.deviceRotationQuaternion.z *= -1;
  52843. this.deviceRotationQuaternion.w *= -1;
  52844. }
  52845. else {
  52846. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  52847. }
  52848. }
  52849. // if the camera is set, rotate to the camera's rotation
  52850. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  52851. /*if (this._poseControlledCamera) {
  52852. Matrix.ScalingToRef(1, 1, 1, Tmp.Matrix[1]);
  52853. this._calculatedRotation.toRotationMatrix(Tmp.Matrix[0]);
  52854. Matrix.TranslationToRef(this._calculatedPosition.x, this._calculatedPosition.y, this._calculatedPosition.z, Tmp.Matrix[2]);
  52855. //Matrix.Identity().multiplyToRef(Tmp.Matrix[1], Tmp.Matrix[4]);
  52856. Tmp.Matrix[1].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[5]);
  52857. this._poseControlledCamera.getWorldMatrix().getTranslationToRef(Tmp.Vector3[0])
  52858. Matrix.ComposeToRef(new Vector3(this.deviceScaleFactor, this.deviceScaleFactor, this.deviceScaleFactor), this._poseControlledCamera.rotationQuaternion, Tmp.Vector3[0], Tmp.Matrix[4]);
  52859. Tmp.Matrix[5].multiplyToRef(Tmp.Matrix[2], Tmp.Matrix[1]);
  52860. Tmp.Matrix[1].multiplyToRef(Tmp.Matrix[4], Tmp.Matrix[2]);
  52861. Tmp.Matrix[2].decompose(Tmp.Vector3[0], this._calculatedRotation, this._calculatedPosition);
  52862. }*/
  52863. }
  52864. }
  52865. };
  52866. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  52867. if (this._mesh) {
  52868. this._mesh.parent = undefined;
  52869. }
  52870. this._mesh = mesh;
  52871. if (this._poseControlledCamera) {
  52872. this._mesh.parent = this._poseControlledCamera;
  52873. }
  52874. if (!this._mesh.rotationQuaternion) {
  52875. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  52876. }
  52877. };
  52878. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  52879. this._poseControlledCamera = camera;
  52880. if (this._mesh) {
  52881. this._mesh.parent = this._poseControlledCamera;
  52882. }
  52883. };
  52884. PoseEnabledController.prototype.detachMesh = function () {
  52885. this._mesh = undefined;
  52886. };
  52887. return PoseEnabledController;
  52888. }(BABYLON.Gamepad));
  52889. BABYLON.PoseEnabledController = PoseEnabledController;
  52890. var WebVRController = (function (_super) {
  52891. __extends(WebVRController, _super);
  52892. function WebVRController(vrGamepad) {
  52893. var _this = _super.call(this, vrGamepad) || this;
  52894. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  52895. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  52896. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  52897. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  52898. _this.onPadStateChangedObservable = new BABYLON.Observable();
  52899. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  52900. _this.pad = { x: 0, y: 0 };
  52901. // avoid GC, store state in a tmp object
  52902. _this._changes = {
  52903. pressChanged: false,
  52904. touchChanged: false,
  52905. valueChanged: false,
  52906. changed: false
  52907. };
  52908. _this._buttons = new Array(vrGamepad.buttons.length);
  52909. _this.hand = vrGamepad.hand;
  52910. return _this;
  52911. }
  52912. WebVRController.prototype.onButtonStateChange = function (callback) {
  52913. this._onButtonStateChange = callback;
  52914. };
  52915. WebVRController.prototype.update = function () {
  52916. _super.prototype.update.call(this);
  52917. for (var index = 0; index < this._buttons.length; index++) {
  52918. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  52919. }
  52920. ;
  52921. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  52922. this.pad.x = this.leftStick.x;
  52923. this.pad.y = this.leftStick.y;
  52924. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  52925. }
  52926. };
  52927. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  52928. if (!currentState) {
  52929. this._buttons[buttonIndex] = {
  52930. pressed: newState.pressed,
  52931. touched: newState.touched,
  52932. value: newState.value
  52933. };
  52934. return;
  52935. }
  52936. this._checkChanges(newState, currentState);
  52937. if (this._changes.changed) {
  52938. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  52939. this.handleButtonChange(buttonIndex, newState, this._changes);
  52940. }
  52941. this._buttons[buttonIndex].pressed = newState.pressed;
  52942. this._buttons[buttonIndex].touched = newState.touched;
  52943. // oculus triggers are never 0, thou not touched.
  52944. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  52945. };
  52946. WebVRController.prototype._checkChanges = function (newState, currentState) {
  52947. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  52948. this._changes.touchChanged = newState.touched !== currentState.touched;
  52949. this._changes.valueChanged = newState.value !== currentState.value;
  52950. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  52951. return this._changes;
  52952. };
  52953. return WebVRController;
  52954. }(PoseEnabledController));
  52955. BABYLON.WebVRController = WebVRController;
  52956. var OculusTouchController = (function (_super) {
  52957. __extends(OculusTouchController, _super);
  52958. function OculusTouchController(vrGamepad) {
  52959. var _this = _super.call(this, vrGamepad) || this;
  52960. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  52961. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  52962. _this.controllerType = PoseEnabledControllerType.OCULUS;
  52963. return _this;
  52964. }
  52965. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52966. var _this = this;
  52967. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  52968. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  52969. /*
  52970. Parent Mesh name: oculus_touch_left
  52971. - body
  52972. - trigger
  52973. - thumbstick
  52974. - grip
  52975. - button_y
  52976. - button_x
  52977. - button_enter
  52978. */
  52979. _this._defaultModel = newMeshes[1];
  52980. if (meshLoaded) {
  52981. meshLoaded(_this._defaultModel);
  52982. }
  52983. _this.attachToMesh(_this._defaultModel);
  52984. });
  52985. };
  52986. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  52987. // helper getters for left and right hand.
  52988. get: function () {
  52989. if (this.hand === 'right') {
  52990. return this.onMainButtonStateChangedObservable;
  52991. }
  52992. else {
  52993. throw new Error('No A button on left hand');
  52994. }
  52995. },
  52996. enumerable: true,
  52997. configurable: true
  52998. });
  52999. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  53000. get: function () {
  53001. if (this.hand === 'right') {
  53002. return this.onSecondaryButtonStateChangedObservable;
  53003. }
  53004. else {
  53005. throw new Error('No B button on left hand');
  53006. }
  53007. },
  53008. enumerable: true,
  53009. configurable: true
  53010. });
  53011. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  53012. get: function () {
  53013. if (this.hand === 'left') {
  53014. return this.onMainButtonStateChangedObservable;
  53015. }
  53016. else {
  53017. throw new Error('No X button on right hand');
  53018. }
  53019. },
  53020. enumerable: true,
  53021. configurable: true
  53022. });
  53023. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  53024. get: function () {
  53025. if (this.hand === 'left') {
  53026. return this.onSecondaryButtonStateChangedObservable;
  53027. }
  53028. else {
  53029. throw new Error('No Y button on right hand');
  53030. }
  53031. },
  53032. enumerable: true,
  53033. configurable: true
  53034. });
  53035. /*
  53036. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  53037. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  53038. 2) secondary trigger (same)
  53039. 3) A (right) X (left), touch, pressed = value
  53040. 4) B / Y
  53041. 5) thumb rest
  53042. */
  53043. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  53044. var notifyObject = state; //{ state: state, changes: changes };
  53045. switch (buttonIdx) {
  53046. case 0:
  53047. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  53048. return;
  53049. case 1:
  53050. if (this._defaultModel) {
  53051. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  53052. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  53053. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  53054. }
  53055. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  53056. return;
  53057. case 2:
  53058. if (this._defaultModel) {
  53059. (this._defaultModel.getChildren()[4]).position.x = notifyObject.value * 0.0035;
  53060. }
  53061. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  53062. return;
  53063. case 3:
  53064. if (this._defaultModel) {
  53065. if (notifyObject.pressed) {
  53066. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  53067. }
  53068. else {
  53069. (this._defaultModel.getChildren()[1]).position.y = 0;
  53070. }
  53071. }
  53072. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  53073. return;
  53074. case 4:
  53075. if (this._defaultModel) {
  53076. if (notifyObject.pressed) {
  53077. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  53078. }
  53079. else {
  53080. (this._defaultModel.getChildren()[2]).position.y = 0;
  53081. }
  53082. }
  53083. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  53084. return;
  53085. case 5:
  53086. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  53087. return;
  53088. }
  53089. };
  53090. return OculusTouchController;
  53091. }(WebVRController));
  53092. BABYLON.OculusTouchController = OculusTouchController;
  53093. var ViveController = (function (_super) {
  53094. __extends(ViveController, _super);
  53095. function ViveController(vrGamepad) {
  53096. var _this = _super.call(this, vrGamepad) || this;
  53097. _this.controllerType = PoseEnabledControllerType.VIVE;
  53098. return _this;
  53099. }
  53100. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  53101. var _this = this;
  53102. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  53103. /*
  53104. Parent Mesh name: ViveWand
  53105. - body
  53106. - r_gripper
  53107. - l_gripper
  53108. - menu_button
  53109. - system_button
  53110. - trackpad
  53111. - trigger
  53112. - LED
  53113. */
  53114. _this._defaultModel = newMeshes[1];
  53115. if (meshLoaded) {
  53116. meshLoaded(_this._defaultModel);
  53117. }
  53118. _this.attachToMesh(_this._defaultModel);
  53119. });
  53120. };
  53121. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  53122. get: function () {
  53123. return this.onMainButtonStateChangedObservable;
  53124. },
  53125. enumerable: true,
  53126. configurable: true
  53127. });
  53128. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  53129. get: function () {
  53130. return this.onMainButtonStateChangedObservable;
  53131. },
  53132. enumerable: true,
  53133. configurable: true
  53134. });
  53135. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  53136. get: function () {
  53137. return this.onSecondaryButtonStateChangedObservable;
  53138. },
  53139. enumerable: true,
  53140. configurable: true
  53141. });
  53142. /**
  53143. * Vive mapping:
  53144. * 0: touchpad
  53145. * 1: trigger
  53146. * 2: left AND right buttons
  53147. * 3: menu button
  53148. */
  53149. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  53150. var notifyObject = state; //{ state: state, changes: changes };
  53151. switch (buttonIdx) {
  53152. case 0:
  53153. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  53154. return;
  53155. case 1:
  53156. if (this._defaultModel) {
  53157. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  53158. }
  53159. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  53160. return;
  53161. case 2:
  53162. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  53163. return;
  53164. case 3:
  53165. if (this._defaultModel) {
  53166. if (notifyObject.pressed) {
  53167. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  53168. }
  53169. else {
  53170. (this._defaultModel.getChildren()[2]).position.y = 0;
  53171. }
  53172. }
  53173. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  53174. return;
  53175. }
  53176. };
  53177. return ViveController;
  53178. }(WebVRController));
  53179. BABYLON.ViveController = ViveController;
  53180. })(BABYLON || (BABYLON = {}));
  53181. //# sourceMappingURL=babylon.extendedGamepad.js.map
  53182. /// <reference path="babylon.universalCamera.ts" />
  53183. var BABYLON;
  53184. (function (BABYLON) {
  53185. // We're mainly based on the logic defined into the FreeCamera code
  53186. var GamepadCamera = (function (_super) {
  53187. __extends(GamepadCamera, _super);
  53188. //-- end properties for backward compatibility for inputs
  53189. function GamepadCamera(name, position, scene) {
  53190. return _super.call(this, name, position, scene) || this;
  53191. }
  53192. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  53193. //-- Begin properties for backward compatibility for inputs
  53194. get: function () {
  53195. var gamepad = this.inputs.attached["gamepad"];
  53196. if (gamepad)
  53197. return gamepad.gamepadAngularSensibility;
  53198. },
  53199. set: function (value) {
  53200. var gamepad = this.inputs.attached["gamepad"];
  53201. if (gamepad)
  53202. gamepad.gamepadAngularSensibility = value;
  53203. },
  53204. enumerable: true,
  53205. configurable: true
  53206. });
  53207. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  53208. get: function () {
  53209. var gamepad = this.inputs.attached["gamepad"];
  53210. if (gamepad)
  53211. return gamepad.gamepadMoveSensibility;
  53212. },
  53213. set: function (value) {
  53214. var gamepad = this.inputs.attached["gamepad"];
  53215. if (gamepad)
  53216. gamepad.gamepadMoveSensibility = value;
  53217. },
  53218. enumerable: true,
  53219. configurable: true
  53220. });
  53221. GamepadCamera.prototype.getClassName = function () {
  53222. return "GamepadCamera";
  53223. };
  53224. return GamepadCamera;
  53225. }(BABYLON.UniversalCamera));
  53226. BABYLON.GamepadCamera = GamepadCamera;
  53227. })(BABYLON || (BABYLON = {}));
  53228. //# sourceMappingURL=babylon.gamepadCamera.js.map
  53229. var BABYLON;
  53230. (function (BABYLON) {
  53231. var Analyser = (function () {
  53232. function Analyser(scene) {
  53233. this.SMOOTHING = 0.75;
  53234. this.FFT_SIZE = 512;
  53235. this.BARGRAPHAMPLITUDE = 256;
  53236. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  53237. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  53238. this._scene = scene;
  53239. this._audioEngine = BABYLON.Engine.audioEngine;
  53240. if (this._audioEngine.canUseWebAudio) {
  53241. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  53242. this._webAudioAnalyser.minDecibels = -140;
  53243. this._webAudioAnalyser.maxDecibels = 0;
  53244. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53245. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53246. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  53247. }
  53248. }
  53249. Analyser.prototype.getFrequencyBinCount = function () {
  53250. if (this._audioEngine.canUseWebAudio) {
  53251. return this._webAudioAnalyser.frequencyBinCount;
  53252. }
  53253. else {
  53254. return 0;
  53255. }
  53256. };
  53257. Analyser.prototype.getByteFrequencyData = function () {
  53258. if (this._audioEngine.canUseWebAudio) {
  53259. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53260. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53261. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  53262. }
  53263. return this._byteFreqs;
  53264. };
  53265. Analyser.prototype.getByteTimeDomainData = function () {
  53266. if (this._audioEngine.canUseWebAudio) {
  53267. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53268. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53269. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  53270. }
  53271. return this._byteTime;
  53272. };
  53273. Analyser.prototype.getFloatFrequencyData = function () {
  53274. if (this._audioEngine.canUseWebAudio) {
  53275. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53276. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53277. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  53278. }
  53279. return this._floatFreqs;
  53280. };
  53281. Analyser.prototype.drawDebugCanvas = function () {
  53282. var _this = this;
  53283. if (this._audioEngine.canUseWebAudio) {
  53284. if (!this._debugCanvas) {
  53285. this._debugCanvas = document.createElement("canvas");
  53286. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  53287. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  53288. this._debugCanvas.style.position = "absolute";
  53289. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  53290. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  53291. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  53292. document.body.appendChild(this._debugCanvas);
  53293. this._registerFunc = function () {
  53294. _this.drawDebugCanvas();
  53295. };
  53296. this._scene.registerBeforeRender(this._registerFunc);
  53297. }
  53298. if (this._registerFunc) {
  53299. var workingArray = this.getByteFrequencyData();
  53300. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  53301. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  53302. // Draw the frequency domain chart.
  53303. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  53304. var value = workingArray[i];
  53305. var percent = value / this.BARGRAPHAMPLITUDE;
  53306. var height = this.DEBUGCANVASSIZE.height * percent;
  53307. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  53308. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  53309. var hue = i / this.getFrequencyBinCount() * 360;
  53310. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  53311. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  53312. }
  53313. }
  53314. }
  53315. };
  53316. Analyser.prototype.stopDebugCanvas = function () {
  53317. if (this._debugCanvas) {
  53318. this._scene.unregisterBeforeRender(this._registerFunc);
  53319. this._registerFunc = null;
  53320. document.body.removeChild(this._debugCanvas);
  53321. this._debugCanvas = null;
  53322. this._debugCanvasContext = null;
  53323. }
  53324. };
  53325. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  53326. if (this._audioEngine.canUseWebAudio) {
  53327. inputAudioNode.connect(this._webAudioAnalyser);
  53328. this._webAudioAnalyser.connect(outputAudioNode);
  53329. }
  53330. };
  53331. Analyser.prototype.dispose = function () {
  53332. if (this._audioEngine.canUseWebAudio) {
  53333. this._webAudioAnalyser.disconnect();
  53334. }
  53335. };
  53336. return Analyser;
  53337. }());
  53338. BABYLON.Analyser = Analyser;
  53339. })(BABYLON || (BABYLON = {}));
  53340. //# sourceMappingURL=babylon.analyser.js.map
  53341. var BABYLON;
  53342. (function (BABYLON) {
  53343. var DepthRenderer = (function () {
  53344. function DepthRenderer(scene, type) {
  53345. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  53346. var _this = this;
  53347. this._viewMatrix = BABYLON.Matrix.Zero();
  53348. this._projectionMatrix = BABYLON.Matrix.Zero();
  53349. this._transformMatrix = BABYLON.Matrix.Zero();
  53350. this._worldViewProjection = BABYLON.Matrix.Zero();
  53351. this._scene = scene;
  53352. var engine = scene.getEngine();
  53353. // Render target
  53354. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  53355. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53356. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53357. this._depthMap.refreshRate = 1;
  53358. this._depthMap.renderParticles = false;
  53359. this._depthMap.renderList = null;
  53360. // set default depth value to 1.0 (far away)
  53361. this._depthMap.onClearObservable.add(function (engine) {
  53362. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53363. });
  53364. // Custom render function
  53365. var renderSubMesh = function (subMesh) {
  53366. var mesh = subMesh.getRenderingMesh();
  53367. var scene = _this._scene;
  53368. var engine = scene.getEngine();
  53369. // Culling
  53370. engine.setState(subMesh.getMaterial().backFaceCulling);
  53371. // Managing instances
  53372. var batch = mesh._getInstancesRenderList(subMesh._id);
  53373. if (batch.mustReturn) {
  53374. return;
  53375. }
  53376. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  53377. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53378. engine.enableEffect(_this._effect);
  53379. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  53380. var material = subMesh.getMaterial();
  53381. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53382. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  53383. // Alpha test
  53384. if (material && material.needAlphaTesting()) {
  53385. var alphaTexture = material.getAlphaTestTexture();
  53386. _this._effect.setTexture("diffuseSampler", alphaTexture);
  53387. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53388. }
  53389. // Bones
  53390. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53391. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53392. }
  53393. // Draw
  53394. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53395. }
  53396. };
  53397. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  53398. var index;
  53399. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53400. renderSubMesh(opaqueSubMeshes.data[index]);
  53401. }
  53402. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53403. renderSubMesh(alphaTestSubMeshes.data[index]);
  53404. }
  53405. };
  53406. }
  53407. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  53408. var material = subMesh.getMaterial();
  53409. if (material.disableDepthWrite) {
  53410. return false;
  53411. }
  53412. var defines = [];
  53413. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53414. var mesh = subMesh.getMesh();
  53415. var scene = mesh.getScene();
  53416. // Alpha test
  53417. if (material && material.needAlphaTesting()) {
  53418. defines.push("#define ALPHATEST");
  53419. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53420. attribs.push(BABYLON.VertexBuffer.UVKind);
  53421. defines.push("#define UV1");
  53422. }
  53423. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53424. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53425. defines.push("#define UV2");
  53426. }
  53427. }
  53428. // Bones
  53429. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53430. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53431. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53432. if (mesh.numBoneInfluencers > 4) {
  53433. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53434. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53435. }
  53436. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53437. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53438. }
  53439. else {
  53440. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53441. }
  53442. // Instances
  53443. if (useInstances) {
  53444. defines.push("#define INSTANCES");
  53445. attribs.push("world0");
  53446. attribs.push("world1");
  53447. attribs.push("world2");
  53448. attribs.push("world3");
  53449. }
  53450. // Get correct effect
  53451. var join = defines.join("\n");
  53452. if (this._cachedDefines !== join) {
  53453. this._cachedDefines = join;
  53454. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  53455. }
  53456. return this._effect.isReady();
  53457. };
  53458. DepthRenderer.prototype.getDepthMap = function () {
  53459. return this._depthMap;
  53460. };
  53461. // Methods
  53462. DepthRenderer.prototype.dispose = function () {
  53463. this._depthMap.dispose();
  53464. };
  53465. return DepthRenderer;
  53466. }());
  53467. BABYLON.DepthRenderer = DepthRenderer;
  53468. })(BABYLON || (BABYLON = {}));
  53469. //# sourceMappingURL=babylon.depthRenderer.js.map
  53470. var BABYLON;
  53471. (function (BABYLON) {
  53472. var SSAORenderingPipeline = (function (_super) {
  53473. __extends(SSAORenderingPipeline, _super);
  53474. /**
  53475. * @constructor
  53476. * @param {string} name - The rendering pipeline name
  53477. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53478. * @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 }
  53479. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53480. */
  53481. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  53482. var _this = _super.call(this, scene.getEngine(), name) || this;
  53483. // Members
  53484. /**
  53485. * The PassPostProcess id in the pipeline that contains the original scene color
  53486. * @type {string}
  53487. */
  53488. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  53489. /**
  53490. * The SSAO PostProcess id in the pipeline
  53491. * @type {string}
  53492. */
  53493. _this.SSAORenderEffect = "SSAORenderEffect";
  53494. /**
  53495. * The horizontal blur PostProcess id in the pipeline
  53496. * @type {string}
  53497. */
  53498. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  53499. /**
  53500. * The vertical blur PostProcess id in the pipeline
  53501. * @type {string}
  53502. */
  53503. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  53504. /**
  53505. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  53506. * @type {string}
  53507. */
  53508. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  53509. /**
  53510. * The output strength of the SSAO post-process. Default value is 1.0.
  53511. * @type {number}
  53512. */
  53513. _this.totalStrength = 1.0;
  53514. /**
  53515. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  53516. * @type {number}
  53517. */
  53518. _this.radius = 0.0001;
  53519. /**
  53520. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  53521. * Must not be equal to fallOff and superior to fallOff.
  53522. * Default value is 0.975
  53523. * @type {number}
  53524. */
  53525. _this.area = 0.0075;
  53526. /**
  53527. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  53528. * Must not be equal to area and inferior to area.
  53529. * Default value is 0.0
  53530. * @type {number}
  53531. */
  53532. _this.fallOff = 0.000001;
  53533. /**
  53534. * The base color of the SSAO post-process
  53535. * The final result is "base + ssao" between [0, 1]
  53536. * @type {number}
  53537. */
  53538. _this.base = 0.5;
  53539. _this._firstUpdate = true;
  53540. _this._scene = scene;
  53541. // Set up assets
  53542. _this._createRandomTexture();
  53543. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53544. var ssaoRatio = ratio.ssaoRatio || ratio;
  53545. var combineRatio = ratio.combineRatio || ratio;
  53546. _this._ratio = {
  53547. ssaoRatio: ssaoRatio,
  53548. combineRatio: combineRatio
  53549. };
  53550. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53551. _this._createSSAOPostProcess(ssaoRatio);
  53552. _this._createBlurPostProcess(ssaoRatio);
  53553. _this._createSSAOCombinePostProcess(combineRatio);
  53554. // Set up pipeline
  53555. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53556. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53557. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53558. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53559. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53560. // Finish
  53561. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53562. if (cameras)
  53563. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53564. return _this;
  53565. }
  53566. // Public Methods
  53567. /**
  53568. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53569. */
  53570. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53571. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53572. for (var i = 0; i < this._scene.cameras.length; i++) {
  53573. var camera = this._scene.cameras[i];
  53574. this._originalColorPostProcess.dispose(camera);
  53575. this._ssaoPostProcess.dispose(camera);
  53576. this._blurHPostProcess.dispose(camera);
  53577. this._blurVPostProcess.dispose(camera);
  53578. this._ssaoCombinePostProcess.dispose(camera);
  53579. }
  53580. this._randomTexture.dispose();
  53581. if (disableDepthRender)
  53582. this._scene.disableDepthRenderer();
  53583. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53584. _super.prototype.dispose.call(this);
  53585. };
  53586. // Private Methods
  53587. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  53588. var _this = this;
  53589. /*
  53590. var samplerOffsets = [
  53591. -8.0, -6.0, -4.0, -2.0,
  53592. 0.0,
  53593. 2.0, 4.0, 6.0, 8.0
  53594. ];
  53595. */
  53596. var samples = 16;
  53597. var samplerOffsets = [];
  53598. for (var i = -8; i < 8; i++) {
  53599. samplerOffsets.push(i * 2);
  53600. }
  53601. 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");
  53602. this._blurHPostProcess.onApply = function (effect) {
  53603. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53604. effect.setTexture("depthSampler", _this._depthTexture);
  53605. if (_this._firstUpdate) {
  53606. effect.setArray("samplerOffsets", samplerOffsets);
  53607. }
  53608. };
  53609. 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");
  53610. this._blurVPostProcess.onApply = function (effect) {
  53611. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53612. effect.setTexture("depthSampler", _this._depthTexture);
  53613. if (_this._firstUpdate) {
  53614. effect.setArray("samplerOffsets", samplerOffsets);
  53615. _this._firstUpdate = false;
  53616. }
  53617. };
  53618. };
  53619. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53620. var _this = this;
  53621. var numSamples = 16;
  53622. var sampleSphere = [
  53623. 0.5381, 0.1856, -0.4319,
  53624. 0.1379, 0.2486, 0.4430,
  53625. 0.3371, 0.5679, -0.0057,
  53626. -0.6999, -0.0451, -0.0019,
  53627. 0.0689, -0.1598, -0.8547,
  53628. 0.0560, 0.0069, -0.1843,
  53629. -0.0146, 0.1402, 0.0762,
  53630. 0.0100, -0.1924, -0.0344,
  53631. -0.3577, -0.5301, -0.4358,
  53632. -0.3169, 0.1063, 0.0158,
  53633. 0.0103, -0.5869, 0.0046,
  53634. -0.0897, -0.4940, 0.3287,
  53635. 0.7119, -0.0154, -0.0918,
  53636. -0.0533, 0.0596, -0.5411,
  53637. 0.0352, -0.0631, 0.5460,
  53638. -0.4776, 0.2847, -0.0271
  53639. ];
  53640. var samplesFactor = 1.0 / numSamples;
  53641. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  53642. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  53643. "area", "fallOff", "base", "range", "viewport"
  53644. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  53645. var viewport = new BABYLON.Vector2(0, 0);
  53646. this._ssaoPostProcess.onApply = function (effect) {
  53647. if (_this._firstUpdate) {
  53648. effect.setArray3("sampleSphere", sampleSphere);
  53649. effect.setFloat("samplesFactor", samplesFactor);
  53650. effect.setFloat("randTextureTiles", 4.0);
  53651. }
  53652. effect.setFloat("totalStrength", _this.totalStrength);
  53653. effect.setFloat("radius", _this.radius);
  53654. effect.setFloat("area", _this.area);
  53655. effect.setFloat("fallOff", _this.fallOff);
  53656. effect.setFloat("base", _this.base);
  53657. effect.setTexture("textureSampler", _this._depthTexture);
  53658. effect.setTexture("randomSampler", _this._randomTexture);
  53659. };
  53660. };
  53661. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  53662. var _this = this;
  53663. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53664. this._ssaoCombinePostProcess.onApply = function (effect) {
  53665. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  53666. };
  53667. };
  53668. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  53669. var size = 512;
  53670. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53671. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53672. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53673. var context = this._randomTexture.getContext();
  53674. var rand = function (min, max) {
  53675. return Math.random() * (max - min) + min;
  53676. };
  53677. var randVector = BABYLON.Vector3.Zero();
  53678. for (var x = 0; x < size; x++) {
  53679. for (var y = 0; y < size; y++) {
  53680. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  53681. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  53682. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  53683. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  53684. context.fillRect(x, y, 1, 1);
  53685. }
  53686. }
  53687. this._randomTexture.update(false);
  53688. };
  53689. return SSAORenderingPipeline;
  53690. }(BABYLON.PostProcessRenderPipeline));
  53691. __decorate([
  53692. BABYLON.serialize()
  53693. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  53694. __decorate([
  53695. BABYLON.serialize()
  53696. ], SSAORenderingPipeline.prototype, "radius", void 0);
  53697. __decorate([
  53698. BABYLON.serialize()
  53699. ], SSAORenderingPipeline.prototype, "area", void 0);
  53700. __decorate([
  53701. BABYLON.serialize()
  53702. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  53703. __decorate([
  53704. BABYLON.serialize()
  53705. ], SSAORenderingPipeline.prototype, "base", void 0);
  53706. __decorate([
  53707. BABYLON.serialize()
  53708. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  53709. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  53710. })(BABYLON || (BABYLON = {}));
  53711. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  53712. var BABYLON;
  53713. (function (BABYLON) {
  53714. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  53715. var VolumetricLightScatteringPostProcess = (function (_super) {
  53716. __extends(VolumetricLightScatteringPostProcess, _super);
  53717. /**
  53718. * @constructor
  53719. * @param {string} name - The post-process name
  53720. * @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)
  53721. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  53722. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  53723. * @param {number} samples - The post-process quality, default 100
  53724. * @param {number} samplingMode - The post-process filtering mode
  53725. * @param {BABYLON.Engine} engine - The babylon engine
  53726. * @param {boolean} reusable - If the post-process is reusable
  53727. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  53728. */
  53729. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  53730. if (samples === void 0) { samples = 100; }
  53731. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53732. 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;
  53733. _this._screenCoordinates = BABYLON.Vector2.Zero();
  53734. /**
  53735. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  53736. * @type {Vector3}
  53737. */
  53738. _this.customMeshPosition = BABYLON.Vector3.Zero();
  53739. /**
  53740. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  53741. * @type {boolean}
  53742. */
  53743. _this.useCustomMeshPosition = false;
  53744. /**
  53745. * If the post-process should inverse the light scattering direction
  53746. * @type {boolean}
  53747. */
  53748. _this.invert = true;
  53749. /**
  53750. * Array containing the excluded meshes not rendered in the internal pass
  53751. */
  53752. _this.excludedMeshes = new Array();
  53753. /**
  53754. * Controls the overall intensity of the post-process
  53755. * @type {number}
  53756. */
  53757. _this.exposure = 0.3;
  53758. /**
  53759. * Dissipates each sample's contribution in range [0, 1]
  53760. * @type {number}
  53761. */
  53762. _this.decay = 0.96815;
  53763. /**
  53764. * Controls the overall intensity of each sample
  53765. * @type {number}
  53766. */
  53767. _this.weight = 0.58767;
  53768. /**
  53769. * Controls the density of each sample
  53770. * @type {number}
  53771. */
  53772. _this.density = 0.926;
  53773. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  53774. var engine = scene.getEngine();
  53775. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  53776. // Configure mesh
  53777. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  53778. // Configure
  53779. _this._createPass(scene, ratio.passRatio || ratio);
  53780. _this.onActivate = function (camera) {
  53781. if (!_this.isSupported) {
  53782. _this.dispose(camera);
  53783. }
  53784. _this.onActivate = null;
  53785. };
  53786. _this.onApplyObservable.add(function (effect) {
  53787. _this._updateMeshScreenCoordinates(scene);
  53788. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  53789. effect.setFloat("exposure", _this.exposure);
  53790. effect.setFloat("decay", _this.decay);
  53791. effect.setFloat("weight", _this.weight);
  53792. effect.setFloat("density", _this.density);
  53793. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  53794. });
  53795. return _this;
  53796. }
  53797. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  53798. get: function () {
  53799. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53800. return false;
  53801. },
  53802. set: function (useDiffuseColor) {
  53803. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53804. },
  53805. enumerable: true,
  53806. configurable: true
  53807. });
  53808. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  53809. var mesh = subMesh.getMesh();
  53810. // Render this.mesh as default
  53811. if (mesh === this.mesh) {
  53812. return mesh.material.isReady(mesh);
  53813. }
  53814. var defines = [];
  53815. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53816. var material = subMesh.getMaterial();
  53817. var needUV = false;
  53818. // Alpha test
  53819. if (material) {
  53820. if (material.needAlphaTesting()) {
  53821. defines.push("#define ALPHATEST");
  53822. }
  53823. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53824. attribs.push(BABYLON.VertexBuffer.UVKind);
  53825. defines.push("#define UV1");
  53826. }
  53827. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53828. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53829. defines.push("#define UV2");
  53830. }
  53831. }
  53832. // Bones
  53833. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53834. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53835. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53836. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53837. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53838. }
  53839. else {
  53840. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53841. }
  53842. // Instances
  53843. if (useInstances) {
  53844. defines.push("#define INSTANCES");
  53845. attribs.push("world0");
  53846. attribs.push("world1");
  53847. attribs.push("world2");
  53848. attribs.push("world3");
  53849. }
  53850. // Get correct effect
  53851. var join = defines.join("\n");
  53852. if (this._cachedDefines !== join) {
  53853. this._cachedDefines = join;
  53854. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  53855. }
  53856. return this._volumetricLightScatteringPass.isReady();
  53857. };
  53858. /**
  53859. * Sets the new light position for light scattering effect
  53860. * @param {BABYLON.Vector3} The new custom light position
  53861. */
  53862. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  53863. this.customMeshPosition = position;
  53864. };
  53865. /**
  53866. * Returns the light position for light scattering effect
  53867. * @return {BABYLON.Vector3} The custom light position
  53868. */
  53869. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  53870. return this.customMeshPosition;
  53871. };
  53872. /**
  53873. * Disposes the internal assets and detaches the post-process from the camera
  53874. */
  53875. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  53876. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  53877. if (rttIndex !== -1) {
  53878. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  53879. }
  53880. this._volumetricLightScatteringRTT.dispose();
  53881. _super.prototype.dispose.call(this, camera);
  53882. };
  53883. /**
  53884. * Returns the render target texture used by the post-process
  53885. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  53886. */
  53887. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  53888. return this._volumetricLightScatteringRTT;
  53889. };
  53890. // Private methods
  53891. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  53892. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  53893. return true;
  53894. }
  53895. return false;
  53896. };
  53897. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  53898. var _this = this;
  53899. var engine = scene.getEngine();
  53900. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53901. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53902. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53903. this._volumetricLightScatteringRTT.renderList = null;
  53904. this._volumetricLightScatteringRTT.renderParticles = false;
  53905. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  53906. // Custom render function for submeshes
  53907. var renderSubMesh = function (subMesh) {
  53908. var mesh = subMesh.getRenderingMesh();
  53909. if (_this._meshExcluded(mesh)) {
  53910. return;
  53911. }
  53912. var scene = mesh.getScene();
  53913. var engine = scene.getEngine();
  53914. // Culling
  53915. engine.setState(subMesh.getMaterial().backFaceCulling);
  53916. // Managing instances
  53917. var batch = mesh._getInstancesRenderList(subMesh._id);
  53918. if (batch.mustReturn) {
  53919. return;
  53920. }
  53921. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  53922. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53923. var effect = _this._volumetricLightScatteringPass;
  53924. if (mesh === _this.mesh) {
  53925. if (subMesh.effect) {
  53926. effect = subMesh.effect;
  53927. }
  53928. else {
  53929. effect = subMesh.getMaterial().getEffect();
  53930. }
  53931. }
  53932. engine.enableEffect(effect);
  53933. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  53934. if (mesh === _this.mesh) {
  53935. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  53936. }
  53937. else {
  53938. var material = subMesh.getMaterial();
  53939. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  53940. // Alpha test
  53941. if (material && material.needAlphaTesting()) {
  53942. var alphaTexture = material.getAlphaTestTexture();
  53943. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  53944. if (alphaTexture) {
  53945. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53946. }
  53947. }
  53948. // Bones
  53949. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53950. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53951. }
  53952. }
  53953. // Draw
  53954. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  53955. }
  53956. };
  53957. // Render target texture callbacks
  53958. var savedSceneClearColor;
  53959. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  53960. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  53961. savedSceneClearColor = scene.clearColor;
  53962. scene.clearColor = sceneClearColor;
  53963. });
  53964. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  53965. scene.clearColor = savedSceneClearColor;
  53966. });
  53967. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  53968. var engine = scene.getEngine();
  53969. var index;
  53970. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53971. renderSubMesh(opaqueSubMeshes.data[index]);
  53972. }
  53973. engine.setAlphaTesting(true);
  53974. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53975. renderSubMesh(alphaTestSubMeshes.data[index]);
  53976. }
  53977. engine.setAlphaTesting(false);
  53978. if (transparentSubMeshes.length) {
  53979. // Sort sub meshes
  53980. for (index = 0; index < transparentSubMeshes.length; index++) {
  53981. var submesh = transparentSubMeshes.data[index];
  53982. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  53983. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  53984. }
  53985. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  53986. sortedArray.sort(function (a, b) {
  53987. // Alpha index first
  53988. if (a._alphaIndex > b._alphaIndex) {
  53989. return 1;
  53990. }
  53991. if (a._alphaIndex < b._alphaIndex) {
  53992. return -1;
  53993. }
  53994. // Then distance to camera
  53995. if (a._distanceToCamera < b._distanceToCamera) {
  53996. return 1;
  53997. }
  53998. if (a._distanceToCamera > b._distanceToCamera) {
  53999. return -1;
  54000. }
  54001. return 0;
  54002. });
  54003. // Render sub meshes
  54004. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54005. for (index = 0; index < sortedArray.length; index++) {
  54006. renderSubMesh(sortedArray[index]);
  54007. }
  54008. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54009. }
  54010. };
  54011. };
  54012. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  54013. var transform = scene.getTransformMatrix();
  54014. var meshPosition;
  54015. if (this.useCustomMeshPosition) {
  54016. meshPosition = this.customMeshPosition;
  54017. }
  54018. else if (this.attachedNode) {
  54019. meshPosition = this.attachedNode.position;
  54020. }
  54021. else {
  54022. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  54023. }
  54024. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  54025. this._screenCoordinates.x = pos.x / this._viewPort.width;
  54026. this._screenCoordinates.y = pos.y / this._viewPort.height;
  54027. if (this.invert)
  54028. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  54029. };
  54030. // Static methods
  54031. /**
  54032. * Creates a default mesh for the Volumeric Light Scattering post-process
  54033. * @param {string} The mesh name
  54034. * @param {BABYLON.Scene} The scene where to create the mesh
  54035. * @return {BABYLON.Mesh} the default mesh
  54036. */
  54037. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  54038. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  54039. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  54040. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  54041. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  54042. mesh.material = material;
  54043. return mesh;
  54044. };
  54045. return VolumetricLightScatteringPostProcess;
  54046. }(BABYLON.PostProcess));
  54047. __decorate([
  54048. BABYLON.serializeAsVector3()
  54049. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  54050. __decorate([
  54051. BABYLON.serialize()
  54052. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  54053. __decorate([
  54054. BABYLON.serialize()
  54055. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  54056. __decorate([
  54057. BABYLON.serializeAsMeshReference()
  54058. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  54059. __decorate([
  54060. BABYLON.serialize()
  54061. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  54062. __decorate([
  54063. BABYLON.serialize()
  54064. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  54065. __decorate([
  54066. BABYLON.serialize()
  54067. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  54068. __decorate([
  54069. BABYLON.serialize()
  54070. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  54071. __decorate([
  54072. BABYLON.serialize()
  54073. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  54074. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  54075. })(BABYLON || (BABYLON = {}));
  54076. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  54077. // BABYLON.JS Chromatic Aberration GLSL Shader
  54078. // Author: Olivier Guyot
  54079. // Separates very slightly R, G and B colors on the edges of the screen
  54080. // Inspired by Francois Tarlier & Martins Upitis
  54081. var BABYLON;
  54082. (function (BABYLON) {
  54083. var LensRenderingPipeline = (function (_super) {
  54084. __extends(LensRenderingPipeline, _super);
  54085. /**
  54086. * @constructor
  54087. *
  54088. * Effect parameters are as follow:
  54089. * {
  54090. * chromatic_aberration: number; // from 0 to x (1 for realism)
  54091. * edge_blur: number; // from 0 to x (1 for realism)
  54092. * distortion: number; // from 0 to x (1 for realism)
  54093. * grain_amount: number; // from 0 to 1
  54094. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  54095. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  54096. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  54097. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  54098. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  54099. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  54100. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  54101. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  54102. * }
  54103. * Note: if an effect parameter is unset, effect is disabled
  54104. *
  54105. * @param {string} name - The rendering pipeline name
  54106. * @param {object} parameters - An object containing all parameters (see above)
  54107. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54108. * @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)
  54109. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54110. */
  54111. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  54112. if (ratio === void 0) { ratio = 1.0; }
  54113. var _this = _super.call(this, scene.getEngine(), name) || this;
  54114. // Lens effects can be of the following:
  54115. // - chromatic aberration (slight shift of RGB colors)
  54116. // - blur on the edge of the lens
  54117. // - lens distortion
  54118. // - depth-of-field blur & highlights enhancing
  54119. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  54120. // - grain effect (noise or custom texture)
  54121. // Two additional texture samplers are needed:
  54122. // - depth map (for depth-of-field)
  54123. // - grain texture
  54124. /**
  54125. * The chromatic aberration PostProcess id in the pipeline
  54126. * @type {string}
  54127. */
  54128. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  54129. /**
  54130. * The highlights enhancing PostProcess id in the pipeline
  54131. * @type {string}
  54132. */
  54133. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  54134. /**
  54135. * The depth-of-field PostProcess id in the pipeline
  54136. * @type {string}
  54137. */
  54138. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  54139. _this._scene = scene;
  54140. // Fetch texture samplers
  54141. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  54142. if (parameters.grain_texture) {
  54143. _this._grainTexture = parameters.grain_texture;
  54144. }
  54145. else {
  54146. _this._createGrainTexture();
  54147. }
  54148. // save parameters
  54149. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  54150. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  54151. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  54152. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  54153. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  54154. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  54155. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  54156. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  54157. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  54158. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  54159. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  54160. // Create effects
  54161. _this._createChromaticAberrationPostProcess(ratio);
  54162. _this._createHighlightsPostProcess(ratio);
  54163. _this._createDepthOfFieldPostProcess(ratio / 4);
  54164. // Set up pipeline
  54165. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  54166. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  54167. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  54168. if (_this._highlightsGain === -1) {
  54169. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  54170. }
  54171. // Finish
  54172. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54173. if (cameras) {
  54174. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54175. }
  54176. return _this;
  54177. }
  54178. // public methods (self explanatory)
  54179. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  54180. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  54181. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  54182. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  54183. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  54184. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  54185. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  54186. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  54187. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  54188. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  54189. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  54190. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  54191. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  54192. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  54193. };
  54194. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  54195. this._highlightsPostProcess.updateEffect();
  54196. };
  54197. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  54198. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  54199. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  54200. this._highlightsGain = amount;
  54201. };
  54202. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  54203. if (this._highlightsGain === -1) {
  54204. this._highlightsGain = 1.0;
  54205. }
  54206. this._highlightsThreshold = amount;
  54207. };
  54208. LensRenderingPipeline.prototype.disableHighlights = function () {
  54209. this._highlightsGain = -1;
  54210. };
  54211. /**
  54212. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  54213. */
  54214. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  54215. if (disableDepthRender === void 0) { disableDepthRender = false; }
  54216. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54217. this._chromaticAberrationPostProcess = undefined;
  54218. this._highlightsPostProcess = undefined;
  54219. this._depthOfFieldPostProcess = undefined;
  54220. this._grainTexture.dispose();
  54221. if (disableDepthRender)
  54222. this._scene.disableDepthRenderer();
  54223. };
  54224. // colors shifting and distortion
  54225. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  54226. var _this = this;
  54227. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  54228. [], // samplers
  54229. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54230. this._chromaticAberrationPostProcess.onApply = function (effect) {
  54231. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  54232. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54233. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54234. };
  54235. };
  54236. // highlights enhancing
  54237. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  54238. var _this = this;
  54239. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  54240. [], // samplers
  54241. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  54242. this._highlightsPostProcess.onApply = function (effect) {
  54243. effect.setFloat('gain', _this._highlightsGain);
  54244. effect.setFloat('threshold', _this._highlightsThreshold);
  54245. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  54246. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54247. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54248. };
  54249. };
  54250. // colors shifting and distortion
  54251. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  54252. var _this = this;
  54253. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  54254. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  54255. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  54256. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54257. this._depthOfFieldPostProcess.onApply = function (effect) {
  54258. effect.setTexture("depthSampler", _this._depthTexture);
  54259. effect.setTexture("grainSampler", _this._grainTexture);
  54260. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  54261. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  54262. effect.setFloat('grain_amount', _this._grainAmount);
  54263. effect.setBool('blur_noise', _this._blurNoise);
  54264. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54265. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54266. effect.setFloat('distortion', _this._distortion);
  54267. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  54268. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  54269. effect.setFloat('aperture', _this._dofAperture);
  54270. effect.setFloat('darken', _this._dofDarken);
  54271. effect.setFloat('edge_blur', _this._edgeBlur);
  54272. effect.setBool('highlights', (_this._highlightsGain !== -1));
  54273. effect.setFloat('near', _this._scene.activeCamera.minZ);
  54274. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  54275. };
  54276. };
  54277. // creates a black and white random noise texture, 512x512
  54278. LensRenderingPipeline.prototype._createGrainTexture = function () {
  54279. var size = 512;
  54280. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54281. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54282. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54283. var context = this._grainTexture.getContext();
  54284. var rand = function (min, max) {
  54285. return Math.random() * (max - min) + min;
  54286. };
  54287. var value;
  54288. for (var x = 0; x < size; x++) {
  54289. for (var y = 0; y < size; y++) {
  54290. value = Math.floor(rand(0.42, 0.58) * 255);
  54291. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  54292. context.fillRect(x, y, 1, 1);
  54293. }
  54294. }
  54295. this._grainTexture.update(false);
  54296. };
  54297. return LensRenderingPipeline;
  54298. }(BABYLON.PostProcessRenderPipeline));
  54299. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  54300. })(BABYLON || (BABYLON = {}));
  54301. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  54302. //
  54303. // This post-process allows the modification of rendered colors by using
  54304. // a 'look-up table' (LUT). This effect is also called Color Grading.
  54305. //
  54306. // The object needs to be provided an url to a texture containing the color
  54307. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  54308. // Use an image editing software to tweak the LUT to match your needs.
  54309. //
  54310. // For an example of a color LUT, see here:
  54311. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  54312. // For explanations on color grading, see here:
  54313. // http://udn.epicgames.com/Three/ColorGrading.html
  54314. //
  54315. var BABYLON;
  54316. (function (BABYLON) {
  54317. var ColorCorrectionPostProcess = (function (_super) {
  54318. __extends(ColorCorrectionPostProcess, _super);
  54319. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  54320. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  54321. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54322. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  54323. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54324. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54325. _this.onApply = function (effect) {
  54326. effect.setTexture("colorTable", _this._colorTableTexture);
  54327. };
  54328. return _this;
  54329. }
  54330. return ColorCorrectionPostProcess;
  54331. }(BABYLON.PostProcess));
  54332. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  54333. })(BABYLON || (BABYLON = {}));
  54334. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  54335. /// <reference path="babylon.freeCamera.ts" />
  54336. /// <reference path="babylon.arcRotateCamera.ts" />
  54337. /// <reference path="babylon.gamepadCamera.ts" />
  54338. /// <reference path="babylon.universalCamera.ts" />
  54339. var BABYLON;
  54340. (function (BABYLON) {
  54341. var AnaglyphFreeCamera = (function (_super) {
  54342. __extends(AnaglyphFreeCamera, _super);
  54343. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  54344. var _this = _super.call(this, name, position, scene) || this;
  54345. _this.interaxialDistance = interaxialDistance;
  54346. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54347. return _this;
  54348. }
  54349. AnaglyphFreeCamera.prototype.getClassName = function () {
  54350. return "AnaglyphFreeCamera";
  54351. };
  54352. return AnaglyphFreeCamera;
  54353. }(BABYLON.FreeCamera));
  54354. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  54355. var AnaglyphArcRotateCamera = (function (_super) {
  54356. __extends(AnaglyphArcRotateCamera, _super);
  54357. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  54358. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  54359. _this.interaxialDistance = interaxialDistance;
  54360. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54361. return _this;
  54362. }
  54363. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  54364. return "AnaglyphArcRotateCamera";
  54365. };
  54366. return AnaglyphArcRotateCamera;
  54367. }(BABYLON.ArcRotateCamera));
  54368. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  54369. var AnaglyphGamepadCamera = (function (_super) {
  54370. __extends(AnaglyphGamepadCamera, _super);
  54371. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  54372. var _this = _super.call(this, name, position, scene) || this;
  54373. _this.interaxialDistance = interaxialDistance;
  54374. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54375. return _this;
  54376. }
  54377. AnaglyphGamepadCamera.prototype.getClassName = function () {
  54378. return "AnaglyphGamepadCamera";
  54379. };
  54380. return AnaglyphGamepadCamera;
  54381. }(BABYLON.GamepadCamera));
  54382. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  54383. var AnaglyphUniversalCamera = (function (_super) {
  54384. __extends(AnaglyphUniversalCamera, _super);
  54385. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  54386. var _this = _super.call(this, name, position, scene) || this;
  54387. _this.interaxialDistance = interaxialDistance;
  54388. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54389. return _this;
  54390. }
  54391. AnaglyphUniversalCamera.prototype.getClassName = function () {
  54392. return "AnaglyphUniversalCamera";
  54393. };
  54394. return AnaglyphUniversalCamera;
  54395. }(BABYLON.UniversalCamera));
  54396. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  54397. var StereoscopicFreeCamera = (function (_super) {
  54398. __extends(StereoscopicFreeCamera, _super);
  54399. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54400. var _this = _super.call(this, name, position, scene) || this;
  54401. _this.interaxialDistance = interaxialDistance;
  54402. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54403. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54404. return _this;
  54405. }
  54406. StereoscopicFreeCamera.prototype.getClassName = function () {
  54407. return "StereoscopicFreeCamera";
  54408. };
  54409. return StereoscopicFreeCamera;
  54410. }(BABYLON.FreeCamera));
  54411. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  54412. var StereoscopicArcRotateCamera = (function (_super) {
  54413. __extends(StereoscopicArcRotateCamera, _super);
  54414. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  54415. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  54416. _this.interaxialDistance = interaxialDistance;
  54417. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54418. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54419. return _this;
  54420. }
  54421. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  54422. return "StereoscopicArcRotateCamera";
  54423. };
  54424. return StereoscopicArcRotateCamera;
  54425. }(BABYLON.ArcRotateCamera));
  54426. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  54427. var StereoscopicGamepadCamera = (function (_super) {
  54428. __extends(StereoscopicGamepadCamera, _super);
  54429. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54430. var _this = _super.call(this, name, position, scene) || this;
  54431. _this.interaxialDistance = interaxialDistance;
  54432. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54433. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54434. return _this;
  54435. }
  54436. StereoscopicGamepadCamera.prototype.getClassName = function () {
  54437. return "StereoscopicGamepadCamera";
  54438. };
  54439. return StereoscopicGamepadCamera;
  54440. }(BABYLON.GamepadCamera));
  54441. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  54442. var StereoscopicUniversalCamera = (function (_super) {
  54443. __extends(StereoscopicUniversalCamera, _super);
  54444. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54445. var _this = _super.call(this, name, position, scene) || this;
  54446. _this.interaxialDistance = interaxialDistance;
  54447. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54448. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54449. return _this;
  54450. }
  54451. StereoscopicUniversalCamera.prototype.getClassName = function () {
  54452. return "StereoscopicUniversalCamera";
  54453. };
  54454. return StereoscopicUniversalCamera;
  54455. }(BABYLON.UniversalCamera));
  54456. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  54457. })(BABYLON || (BABYLON = {}));
  54458. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  54459. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  54460. var BABYLON;
  54461. (function (BABYLON) {
  54462. var HDRRenderingPipeline = (function (_super) {
  54463. __extends(HDRRenderingPipeline, _super);
  54464. /**
  54465. * @constructor
  54466. * @param {string} name - The rendering pipeline name
  54467. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54468. * @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)
  54469. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54470. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54471. */
  54472. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54473. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54474. var _this = _super.call(this, scene.getEngine(), name) || this;
  54475. /**
  54476. * Public members
  54477. */
  54478. // Gaussian Blur
  54479. /**
  54480. * Gaussian blur coefficient
  54481. * @type {number}
  54482. */
  54483. _this.gaussCoeff = 0.3;
  54484. /**
  54485. * Gaussian blur mean
  54486. * @type {number}
  54487. */
  54488. _this.gaussMean = 1.0;
  54489. /**
  54490. * Gaussian blur standard deviation
  54491. * @type {number}
  54492. */
  54493. _this.gaussStandDev = 0.8;
  54494. /**
  54495. * Gaussian blur multiplier. Multiplies the blur effect
  54496. * @type {number}
  54497. */
  54498. _this.gaussMultiplier = 4.0;
  54499. // HDR
  54500. /**
  54501. * Exposure, controls the overall intensity of the pipeline
  54502. * @type {number}
  54503. */
  54504. _this.exposure = 1.0;
  54505. /**
  54506. * Minimum luminance that the post-process can output. Luminance is >= 0
  54507. * @type {number}
  54508. */
  54509. _this.minimumLuminance = 1.0;
  54510. /**
  54511. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  54512. * @type {number}
  54513. */
  54514. _this.maximumLuminance = 1e20;
  54515. /**
  54516. * Increase rate for luminance: eye adaptation speed to dark
  54517. * @type {number}
  54518. */
  54519. _this.luminanceIncreaserate = 0.5;
  54520. /**
  54521. * Decrease rate for luminance: eye adaptation speed to bright
  54522. * @type {number}
  54523. */
  54524. _this.luminanceDecreaseRate = 0.5;
  54525. // Bright pass
  54526. /**
  54527. * Minimum luminance needed to compute HDR
  54528. * @type {number}
  54529. */
  54530. _this.brightThreshold = 0.8;
  54531. _this._needUpdate = true;
  54532. _this._scene = scene;
  54533. // Bright pass
  54534. _this._createBrightPassPostProcess(scene, ratio);
  54535. // Down sample X4
  54536. _this._createDownSampleX4PostProcess(scene, ratio);
  54537. // Create gaussian blur post-processes
  54538. _this._createGaussianBlurPostProcess(scene, ratio);
  54539. // Texture adder
  54540. _this._createTextureAdderPostProcess(scene, ratio);
  54541. // Luminance generator
  54542. _this._createLuminanceGeneratorPostProcess(scene);
  54543. // HDR
  54544. _this._createHDRPostProcess(scene, ratio);
  54545. // Pass postprocess
  54546. if (originalPostProcess === null) {
  54547. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  54548. }
  54549. else {
  54550. _this._originalPostProcess = originalPostProcess;
  54551. }
  54552. // Configure pipeline
  54553. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  54554. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  54555. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  54556. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  54557. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  54558. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  54559. var addDownSamplerPostProcess = function (id) {
  54560. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  54561. };
  54562. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  54563. addDownSamplerPostProcess(i);
  54564. }
  54565. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  54566. // Finish
  54567. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54568. if (cameras !== null) {
  54569. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54570. }
  54571. _this.update();
  54572. return _this;
  54573. }
  54574. /**
  54575. * Tells the pipeline to update its post-processes
  54576. */
  54577. HDRRenderingPipeline.prototype.update = function () {
  54578. this._needUpdate = true;
  54579. };
  54580. /**
  54581. * Returns the current calculated luminance
  54582. */
  54583. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  54584. return this._hdrCurrentLuminance;
  54585. };
  54586. /**
  54587. * Returns the currently drawn luminance
  54588. */
  54589. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  54590. return this._hdrOutputLuminance;
  54591. };
  54592. /**
  54593. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  54594. */
  54595. HDRRenderingPipeline.prototype.dispose = function () {
  54596. for (var i = 0; i < this._scene.cameras.length; i++) {
  54597. var camera = this._scene.cameras[i];
  54598. this._originalPostProcess.dispose(camera);
  54599. this._brightPassPostProcess.dispose(camera);
  54600. this._downSampleX4PostProcess.dispose(camera);
  54601. this._guassianBlurHPostProcess.dispose(camera);
  54602. this._guassianBlurVPostProcess.dispose(camera);
  54603. this._textureAdderPostProcess.dispose(camera);
  54604. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  54605. this._downSamplePostProcesses[j].dispose(camera);
  54606. }
  54607. this._hdrPostProcess.dispose(camera);
  54608. }
  54609. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54610. _super.prototype.dispose.call(this);
  54611. };
  54612. /**
  54613. * Creates the HDR post-process and computes the luminance adaptation
  54614. */
  54615. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  54616. var _this = this;
  54617. var hdrLastLuminance = 0.0;
  54618. this._hdrOutputLuminance = -1.0;
  54619. this._hdrCurrentLuminance = 1.0;
  54620. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  54621. this._hdrPostProcess.onApply = function (effect) {
  54622. if (_this._hdrOutputLuminance < 0.0) {
  54623. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  54624. }
  54625. else {
  54626. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  54627. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  54628. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  54629. }
  54630. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  54631. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  54632. }
  54633. else {
  54634. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  54635. }
  54636. }
  54637. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  54638. hdrLastLuminance += scene.getEngine().getDeltaTime();
  54639. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  54640. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  54641. effect.setFloat("exposure", _this.exposure);
  54642. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  54643. _this._needUpdate = false;
  54644. };
  54645. };
  54646. /**
  54647. * Texture Adder post-process
  54648. */
  54649. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54650. var _this = this;
  54651. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  54652. this._textureAdderPostProcess.onApply = function (effect) {
  54653. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  54654. };
  54655. };
  54656. /**
  54657. * Down sample X4 post-process
  54658. */
  54659. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54660. var _this = this;
  54661. var downSampleX4Offsets = new Array(32);
  54662. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  54663. this._downSampleX4PostProcess.onApply = function (effect) {
  54664. if (_this._needUpdate) {
  54665. var id = 0;
  54666. for (var i = -2; i < 2; i++) {
  54667. for (var j = -2; j < 2; j++) {
  54668. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  54669. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  54670. id += 2;
  54671. }
  54672. }
  54673. }
  54674. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54675. };
  54676. };
  54677. /**
  54678. * Bright pass post-process
  54679. */
  54680. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54681. var _this = this;
  54682. var brightOffsets = new Array(8);
  54683. var brightPassCallback = function (effect) {
  54684. if (_this._needUpdate) {
  54685. var sU = (1.0 / _this._brightPassPostProcess.width);
  54686. var sV = (1.0 / _this._brightPassPostProcess.height);
  54687. brightOffsets[0] = -0.5 * sU;
  54688. brightOffsets[1] = 0.5 * sV;
  54689. brightOffsets[2] = 0.5 * sU;
  54690. brightOffsets[3] = 0.5 * sV;
  54691. brightOffsets[4] = -0.5 * sU;
  54692. brightOffsets[5] = -0.5 * sV;
  54693. brightOffsets[6] = 0.5 * sU;
  54694. brightOffsets[7] = -0.5 * sV;
  54695. }
  54696. effect.setArray2("dsOffsets", brightOffsets);
  54697. effect.setFloat("brightThreshold", _this.brightThreshold);
  54698. };
  54699. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  54700. this._brightPassPostProcess.onApply = brightPassCallback;
  54701. };
  54702. /**
  54703. * Luminance generator. Creates the luminance post-process and down sample post-processes
  54704. */
  54705. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  54706. var _this = this;
  54707. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  54708. var luminanceOffsets = new Array(8);
  54709. var downSampleOffsets = new Array(18);
  54710. var halfDestPixelSize;
  54711. this._downSamplePostProcesses = new Array(lumSteps);
  54712. // Utils for luminance
  54713. var luminanceUpdateSourceOffsets = function (width, height) {
  54714. var sU = (1.0 / width);
  54715. var sV = (1.0 / height);
  54716. luminanceOffsets[0] = -0.5 * sU;
  54717. luminanceOffsets[1] = 0.5 * sV;
  54718. luminanceOffsets[2] = 0.5 * sU;
  54719. luminanceOffsets[3] = 0.5 * sV;
  54720. luminanceOffsets[4] = -0.5 * sU;
  54721. luminanceOffsets[5] = -0.5 * sV;
  54722. luminanceOffsets[6] = 0.5 * sU;
  54723. luminanceOffsets[7] = -0.5 * sV;
  54724. };
  54725. var luminanceUpdateDestOffsets = function (width, height) {
  54726. var id = 0;
  54727. for (var x = -1; x < 2; x++) {
  54728. for (var y = -1; y < 2; y++) {
  54729. downSampleOffsets[id] = (x) / width;
  54730. downSampleOffsets[id + 1] = (y) / height;
  54731. id += 2;
  54732. }
  54733. }
  54734. };
  54735. // Luminance callback
  54736. var luminanceCallback = function (effect) {
  54737. if (_this._needUpdate) {
  54738. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  54739. }
  54740. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  54741. effect.setArray2("lumOffsets", luminanceOffsets);
  54742. };
  54743. // Down sample callbacks
  54744. var downSampleCallback = function (indice) {
  54745. var i = indice;
  54746. return function (effect) {
  54747. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  54748. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  54749. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  54750. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  54751. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  54752. effect.setArray2("dsOffsets", downSampleOffsets);
  54753. };
  54754. };
  54755. var downSampleAfterRenderCallback = function (effect) {
  54756. // Unpack result
  54757. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  54758. 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);
  54759. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  54760. };
  54761. // Create luminance post-process
  54762. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  54763. 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);
  54764. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  54765. // Create down sample post-processes
  54766. for (var i = lumSteps - 2; i >= 0; i--) {
  54767. var length = Math.pow(3, i);
  54768. ratio = { width: length, height: length };
  54769. var defines = "#define DOWN_SAMPLE\n";
  54770. if (i === 0) {
  54771. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  54772. }
  54773. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  54774. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  54775. if (i === 0) {
  54776. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  54777. }
  54778. }
  54779. };
  54780. /**
  54781. * Gaussian blur post-processes. Horizontal and Vertical
  54782. */
  54783. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  54784. var _this = this;
  54785. var blurOffsetsW = new Array(9);
  54786. var blurOffsetsH = new Array(9);
  54787. var blurWeights = new Array(9);
  54788. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  54789. // Utils for gaussian blur
  54790. var calculateBlurOffsets = function (height) {
  54791. var lastOutputDimensions = {
  54792. width: scene.getEngine().getRenderWidth(),
  54793. height: scene.getEngine().getRenderHeight()
  54794. };
  54795. for (var i = 0; i < 9; i++) {
  54796. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  54797. if (height) {
  54798. blurOffsetsH[i] = value;
  54799. }
  54800. else {
  54801. blurOffsetsW[i] = value;
  54802. }
  54803. }
  54804. };
  54805. var calculateWeights = function () {
  54806. var x = 0.0;
  54807. for (var i = 0; i < 9; i++) {
  54808. x = (i - 4.0) / 4.0;
  54809. 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));
  54810. }
  54811. };
  54812. // Callback
  54813. var gaussianBlurCallback = function (height) {
  54814. return function (effect) {
  54815. if (_this._needUpdate) {
  54816. calculateWeights();
  54817. calculateBlurOffsets(height);
  54818. }
  54819. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  54820. effect.setArray("blurWeights", blurWeights);
  54821. effect.setFloat("multiplier", _this.gaussMultiplier);
  54822. };
  54823. };
  54824. // Create horizontal gaussian blur post-processes
  54825. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  54826. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  54827. // Create vertical gaussian blur post-process
  54828. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  54829. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  54830. };
  54831. return HDRRenderingPipeline;
  54832. }(BABYLON.PostProcessRenderPipeline));
  54833. // Luminance generator
  54834. HDRRenderingPipeline.LUM_STEPS = 6;
  54835. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  54836. })(BABYLON || (BABYLON = {}));
  54837. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  54838. var BABYLON;
  54839. (function (BABYLON) {
  54840. var FaceAdjacencies = (function () {
  54841. function FaceAdjacencies() {
  54842. this.edges = new Array();
  54843. this.edgesConnectedCount = 0;
  54844. }
  54845. return FaceAdjacencies;
  54846. }());
  54847. var EdgesRenderer = (function () {
  54848. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  54849. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  54850. if (epsilon === void 0) { epsilon = 0.95; }
  54851. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  54852. this.edgesWidthScalerForOrthographic = 1000.0;
  54853. this.edgesWidthScalerForPerspective = 50.0;
  54854. this._linesPositions = new Array();
  54855. this._linesNormals = new Array();
  54856. this._linesIndices = new Array();
  54857. this._buffers = {};
  54858. this._checkVerticesInsteadOfIndices = false;
  54859. this._source = source;
  54860. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  54861. this._epsilon = epsilon;
  54862. this._prepareRessources();
  54863. this._generateEdgesLines();
  54864. }
  54865. EdgesRenderer.prototype._prepareRessources = function () {
  54866. if (this._lineShader) {
  54867. return;
  54868. }
  54869. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  54870. attributes: ["position", "normal"],
  54871. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  54872. });
  54873. this._lineShader.disableDepthWrite = true;
  54874. this._lineShader.backFaceCulling = false;
  54875. };
  54876. EdgesRenderer.prototype.dispose = function () {
  54877. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  54878. if (buffer) {
  54879. buffer.dispose();
  54880. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  54881. }
  54882. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  54883. if (buffer) {
  54884. buffer.dispose();
  54885. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  54886. }
  54887. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  54888. this._lineShader.dispose();
  54889. };
  54890. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  54891. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  54892. return 0;
  54893. }
  54894. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  54895. return 1;
  54896. }
  54897. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  54898. return 2;
  54899. }
  54900. return -1;
  54901. };
  54902. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  54903. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  54904. return 0;
  54905. }
  54906. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  54907. return 1;
  54908. }
  54909. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  54910. return 2;
  54911. }
  54912. return -1;
  54913. };
  54914. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  54915. var needToCreateLine;
  54916. if (edge === undefined) {
  54917. needToCreateLine = true;
  54918. }
  54919. else {
  54920. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  54921. needToCreateLine = dotProduct < this._epsilon;
  54922. }
  54923. if (needToCreateLine) {
  54924. var offset = this._linesPositions.length / 3;
  54925. var normal = p0.subtract(p1);
  54926. normal.normalize();
  54927. // Positions
  54928. this._linesPositions.push(p0.x);
  54929. this._linesPositions.push(p0.y);
  54930. this._linesPositions.push(p0.z);
  54931. this._linesPositions.push(p0.x);
  54932. this._linesPositions.push(p0.y);
  54933. this._linesPositions.push(p0.z);
  54934. this._linesPositions.push(p1.x);
  54935. this._linesPositions.push(p1.y);
  54936. this._linesPositions.push(p1.z);
  54937. this._linesPositions.push(p1.x);
  54938. this._linesPositions.push(p1.y);
  54939. this._linesPositions.push(p1.z);
  54940. // Normals
  54941. this._linesNormals.push(p1.x);
  54942. this._linesNormals.push(p1.y);
  54943. this._linesNormals.push(p1.z);
  54944. this._linesNormals.push(-1);
  54945. this._linesNormals.push(p1.x);
  54946. this._linesNormals.push(p1.y);
  54947. this._linesNormals.push(p1.z);
  54948. this._linesNormals.push(1);
  54949. this._linesNormals.push(p0.x);
  54950. this._linesNormals.push(p0.y);
  54951. this._linesNormals.push(p0.z);
  54952. this._linesNormals.push(-1);
  54953. this._linesNormals.push(p0.x);
  54954. this._linesNormals.push(p0.y);
  54955. this._linesNormals.push(p0.z);
  54956. this._linesNormals.push(1);
  54957. // Indices
  54958. this._linesIndices.push(offset);
  54959. this._linesIndices.push(offset + 1);
  54960. this._linesIndices.push(offset + 2);
  54961. this._linesIndices.push(offset);
  54962. this._linesIndices.push(offset + 2);
  54963. this._linesIndices.push(offset + 3);
  54964. }
  54965. };
  54966. EdgesRenderer.prototype._generateEdgesLines = function () {
  54967. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54968. var indices = this._source.getIndices();
  54969. // First let's find adjacencies
  54970. var adjacencies = new Array();
  54971. var faceNormals = new Array();
  54972. var index;
  54973. var faceAdjacencies;
  54974. // Prepare faces
  54975. for (index = 0; index < indices.length; index += 3) {
  54976. faceAdjacencies = new FaceAdjacencies();
  54977. var p0Index = indices[index];
  54978. var p1Index = indices[index + 1];
  54979. var p2Index = indices[index + 2];
  54980. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  54981. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  54982. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  54983. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  54984. faceNormal.normalize();
  54985. faceNormals.push(faceNormal);
  54986. adjacencies.push(faceAdjacencies);
  54987. }
  54988. // Scan
  54989. for (index = 0; index < adjacencies.length; index++) {
  54990. faceAdjacencies = adjacencies[index];
  54991. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  54992. var otherFaceAdjacencies = adjacencies[otherIndex];
  54993. if (faceAdjacencies.edgesConnectedCount === 3) {
  54994. break;
  54995. }
  54996. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  54997. continue;
  54998. }
  54999. var otherP0 = indices[otherIndex * 3];
  55000. var otherP1 = indices[otherIndex * 3 + 1];
  55001. var otherP2 = indices[otherIndex * 3 + 2];
  55002. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  55003. var otherEdgeIndex;
  55004. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  55005. continue;
  55006. }
  55007. switch (edgeIndex) {
  55008. case 0:
  55009. if (this._checkVerticesInsteadOfIndices) {
  55010. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  55011. }
  55012. else {
  55013. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  55014. }
  55015. break;
  55016. case 1:
  55017. if (this._checkVerticesInsteadOfIndices) {
  55018. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  55019. }
  55020. else {
  55021. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  55022. }
  55023. break;
  55024. case 2:
  55025. if (this._checkVerticesInsteadOfIndices) {
  55026. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  55027. }
  55028. else {
  55029. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  55030. }
  55031. break;
  55032. }
  55033. if (otherEdgeIndex === -1) {
  55034. continue;
  55035. }
  55036. faceAdjacencies.edges[edgeIndex] = otherIndex;
  55037. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  55038. faceAdjacencies.edgesConnectedCount++;
  55039. otherFaceAdjacencies.edgesConnectedCount++;
  55040. if (faceAdjacencies.edgesConnectedCount === 3) {
  55041. break;
  55042. }
  55043. }
  55044. }
  55045. }
  55046. // Create lines
  55047. for (index = 0; index < adjacencies.length; index++) {
  55048. // 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
  55049. var current = adjacencies[index];
  55050. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  55051. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  55052. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  55053. }
  55054. // Merge into a single mesh
  55055. var engine = this._source.getScene().getEngine();
  55056. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  55057. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  55058. this._ib = engine.createIndexBuffer(this._linesIndices);
  55059. this._indicesCount = this._linesIndices.length;
  55060. };
  55061. EdgesRenderer.prototype.render = function () {
  55062. if (!this._lineShader.isReady()) {
  55063. return;
  55064. }
  55065. var scene = this._source.getScene();
  55066. var engine = scene.getEngine();
  55067. this._lineShader._preBind();
  55068. // VBOs
  55069. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  55070. scene.resetCachedMaterial();
  55071. this._lineShader.setColor4("color", this._source.edgesColor);
  55072. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  55073. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  55074. }
  55075. else {
  55076. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  55077. }
  55078. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  55079. this._lineShader.bind(this._source.getWorldMatrix());
  55080. // Draw order
  55081. engine.draw(true, 0, this._indicesCount);
  55082. this._lineShader.unbind();
  55083. engine.setDepthWrite(true);
  55084. };
  55085. return EdgesRenderer;
  55086. }());
  55087. BABYLON.EdgesRenderer = EdgesRenderer;
  55088. })(BABYLON || (BABYLON = {}));
  55089. //# sourceMappingURL=babylon.edgesRenderer.js.map
  55090. var BABYLON;
  55091. (function (BABYLON) {
  55092. var TonemappingOperator;
  55093. (function (TonemappingOperator) {
  55094. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  55095. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  55096. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  55097. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  55098. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  55099. ;
  55100. var TonemapPostProcess = (function (_super) {
  55101. __extends(TonemapPostProcess, _super);
  55102. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  55103. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55104. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55105. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  55106. _this._operator = _operator;
  55107. _this.exposureAdjustment = exposureAdjustment;
  55108. var defines = "#define ";
  55109. if (_this._operator === TonemappingOperator.Hable)
  55110. defines += "HABLE_TONEMAPPING";
  55111. else if (_this._operator === TonemappingOperator.Reinhard)
  55112. defines += "REINHARD_TONEMAPPING";
  55113. else if (_this._operator === TonemappingOperator.HejiDawson)
  55114. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  55115. else if (_this._operator === TonemappingOperator.Photographic)
  55116. defines += "PHOTOGRAPHIC_TONEMAPPING";
  55117. //sadly a second call to create the effect.
  55118. _this.updateEffect(defines);
  55119. _this.onApply = function (effect) {
  55120. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  55121. };
  55122. return _this;
  55123. }
  55124. return TonemapPostProcess;
  55125. }(BABYLON.PostProcess));
  55126. BABYLON.TonemapPostProcess = TonemapPostProcess;
  55127. })(BABYLON || (BABYLON = {}));
  55128. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  55129. var BABYLON;
  55130. (function (BABYLON) {
  55131. var ReflectionProbe = (function () {
  55132. function ReflectionProbe(name, size, scene, generateMipMaps) {
  55133. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55134. var _this = this;
  55135. this.name = name;
  55136. this._viewMatrix = BABYLON.Matrix.Identity();
  55137. this._target = BABYLON.Vector3.Zero();
  55138. this._add = BABYLON.Vector3.Zero();
  55139. this.invertYAxis = false;
  55140. this.position = BABYLON.Vector3.Zero();
  55141. this._scene = scene;
  55142. this._scene.reflectionProbes.push(this);
  55143. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  55144. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  55145. switch (faceIndex) {
  55146. case 0:
  55147. _this._add.copyFromFloats(1, 0, 0);
  55148. break;
  55149. case 1:
  55150. _this._add.copyFromFloats(-1, 0, 0);
  55151. break;
  55152. case 2:
  55153. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  55154. break;
  55155. case 3:
  55156. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  55157. break;
  55158. case 4:
  55159. _this._add.copyFromFloats(0, 0, 1);
  55160. break;
  55161. case 5:
  55162. _this._add.copyFromFloats(0, 0, -1);
  55163. break;
  55164. }
  55165. if (_this._attachedMesh) {
  55166. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  55167. }
  55168. _this.position.addToRef(_this._add, _this._target);
  55169. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  55170. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  55171. });
  55172. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  55173. scene.updateTransformMatrix(true);
  55174. });
  55175. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  55176. }
  55177. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  55178. get: function () {
  55179. return this._renderTargetTexture.samples;
  55180. },
  55181. set: function (value) {
  55182. this._renderTargetTexture.samples = value;
  55183. },
  55184. enumerable: true,
  55185. configurable: true
  55186. });
  55187. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  55188. get: function () {
  55189. return this._renderTargetTexture.refreshRate;
  55190. },
  55191. set: function (value) {
  55192. this._renderTargetTexture.refreshRate = value;
  55193. },
  55194. enumerable: true,
  55195. configurable: true
  55196. });
  55197. ReflectionProbe.prototype.getScene = function () {
  55198. return this._scene;
  55199. };
  55200. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  55201. get: function () {
  55202. return this._renderTargetTexture;
  55203. },
  55204. enumerable: true,
  55205. configurable: true
  55206. });
  55207. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  55208. get: function () {
  55209. return this._renderTargetTexture.renderList;
  55210. },
  55211. enumerable: true,
  55212. configurable: true
  55213. });
  55214. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  55215. this._attachedMesh = mesh;
  55216. };
  55217. ReflectionProbe.prototype.dispose = function () {
  55218. var index = this._scene.reflectionProbes.indexOf(this);
  55219. if (index !== -1) {
  55220. // Remove from the scene if found
  55221. this._scene.reflectionProbes.splice(index, 1);
  55222. }
  55223. if (this._renderTargetTexture) {
  55224. this._renderTargetTexture.dispose();
  55225. this._renderTargetTexture = null;
  55226. }
  55227. };
  55228. return ReflectionProbe;
  55229. }());
  55230. BABYLON.ReflectionProbe = ReflectionProbe;
  55231. })(BABYLON || (BABYLON = {}));
  55232. //# sourceMappingURL=babylon.reflectionProbe.js.map
  55233. var BABYLON;
  55234. (function (BABYLON) {
  55235. var SolidParticle = (function () {
  55236. /**
  55237. * Creates a Solid Particle object.
  55238. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  55239. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  55240. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  55241. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  55242. * `shapeId` (integer) is the model shape identifier in the SPS.
  55243. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  55244. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  55245. */
  55246. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  55247. this.idx = 0; // particle global index
  55248. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  55249. this.position = BABYLON.Vector3.Zero(); // position
  55250. this.rotation = BABYLON.Vector3.Zero(); // rotation
  55251. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  55252. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  55253. this.velocity = BABYLON.Vector3.Zero(); // velocity
  55254. this.alive = true; // alive
  55255. this.isVisible = true; // visibility
  55256. this._pos = 0; // index of this particle in the global "positions" array
  55257. this.shapeId = 0; // model shape id
  55258. this.idxInShape = 0; // index of the particle in its shape id
  55259. this.idx = particleIndex;
  55260. this._pos = positionIndex;
  55261. this._model = model;
  55262. this.shapeId = shapeId;
  55263. this.idxInShape = idxInShape;
  55264. this._sps = sps;
  55265. if (modelBoundingInfo) {
  55266. this._modelBoundingInfo = modelBoundingInfo;
  55267. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  55268. }
  55269. }
  55270. Object.defineProperty(SolidParticle.prototype, "scale", {
  55271. /**
  55272. * legacy support, changed scale to scaling
  55273. */
  55274. get: function () {
  55275. return this.scaling;
  55276. },
  55277. set: function (scale) {
  55278. this.scaling = scale;
  55279. },
  55280. enumerable: true,
  55281. configurable: true
  55282. });
  55283. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  55284. /**
  55285. * legacy support, changed quaternion to rotationQuaternion
  55286. */
  55287. get: function () {
  55288. return this.rotationQuaternion;
  55289. },
  55290. set: function (q) {
  55291. this.rotationQuaternion = q;
  55292. },
  55293. enumerable: true,
  55294. configurable: true
  55295. });
  55296. /**
  55297. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  55298. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  55299. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  55300. */
  55301. SolidParticle.prototype.intersectsMesh = function (target) {
  55302. if (!this._boundingInfo || !target._boundingInfo) {
  55303. return false;
  55304. }
  55305. if (this._sps._bSphereOnly) {
  55306. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  55307. }
  55308. return this._boundingInfo.intersects(target._boundingInfo, false);
  55309. };
  55310. return SolidParticle;
  55311. }());
  55312. BABYLON.SolidParticle = SolidParticle;
  55313. var ModelShape = (function () {
  55314. /**
  55315. * 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.
  55316. * SPS internal tool, don't use it manually.
  55317. */
  55318. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  55319. this.shapeID = id;
  55320. this._shape = shape;
  55321. this._shapeUV = shapeUV;
  55322. this._positionFunction = posFunction;
  55323. this._vertexFunction = vtxFunction;
  55324. }
  55325. return ModelShape;
  55326. }());
  55327. BABYLON.ModelShape = ModelShape;
  55328. })(BABYLON || (BABYLON = {}));
  55329. //# sourceMappingURL=babylon.solidParticle.js.map
  55330. var BABYLON;
  55331. (function (BABYLON) {
  55332. /**
  55333. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  55334. */
  55335. var SolidParticleSystem = (function () {
  55336. /**
  55337. * Creates a SPS (Solid Particle System) object.
  55338. * `name` (String) is the SPS name, this will be the underlying mesh name.
  55339. * `scene` (Scene) is the scene in which the SPS is added.
  55340. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  55341. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  55342. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  55343. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  55344. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  55345. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  55346. */
  55347. function SolidParticleSystem(name, scene, options) {
  55348. // public members
  55349. /**
  55350. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  55351. * Example : var p = SPS.particles[i];
  55352. */
  55353. this.particles = new Array();
  55354. /**
  55355. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  55356. */
  55357. this.nbParticles = 0;
  55358. /**
  55359. * If the particles must ever face the camera (default false). Useful for planar particles.
  55360. */
  55361. this.billboard = false;
  55362. /**
  55363. * Recompute normals when adding a shape
  55364. */
  55365. this.recomputeNormals = true;
  55366. /**
  55367. * This a counter ofr your own usage. It's not set by any SPS functions.
  55368. */
  55369. this.counter = 0;
  55370. /**
  55371. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  55372. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  55373. */
  55374. this.vars = {};
  55375. this._positions = new Array();
  55376. this._indices = new Array();
  55377. this._normals = new Array();
  55378. this._colors = new Array();
  55379. this._uvs = new Array();
  55380. this._index = 0; // indices index
  55381. this._updatable = true;
  55382. this._pickable = false;
  55383. this._isVisibilityBoxLocked = false;
  55384. this._alwaysVisible = false;
  55385. this._shapeCounter = 0;
  55386. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  55387. this._color = new BABYLON.Color4(0, 0, 0, 0);
  55388. this._computeParticleColor = true;
  55389. this._computeParticleTexture = true;
  55390. this._computeParticleRotation = true;
  55391. this._computeParticleVertex = false;
  55392. this._computeBoundingBox = false;
  55393. this._cam_axisZ = BABYLON.Vector3.Zero();
  55394. this._cam_axisY = BABYLON.Vector3.Zero();
  55395. this._cam_axisX = BABYLON.Vector3.Zero();
  55396. this._axisX = BABYLON.Axis.X;
  55397. this._axisY = BABYLON.Axis.Y;
  55398. this._axisZ = BABYLON.Axis.Z;
  55399. this._camDir = BABYLON.Vector3.Zero();
  55400. this._rotMatrix = new BABYLON.Matrix();
  55401. this._invertMatrix = new BABYLON.Matrix();
  55402. this._rotated = BABYLON.Vector3.Zero();
  55403. this._quaternion = new BABYLON.Quaternion();
  55404. this._vertex = BABYLON.Vector3.Zero();
  55405. this._normal = BABYLON.Vector3.Zero();
  55406. this._yaw = 0.0;
  55407. this._pitch = 0.0;
  55408. this._roll = 0.0;
  55409. this._halfroll = 0.0;
  55410. this._halfpitch = 0.0;
  55411. this._halfyaw = 0.0;
  55412. this._sinRoll = 0.0;
  55413. this._cosRoll = 0.0;
  55414. this._sinPitch = 0.0;
  55415. this._cosPitch = 0.0;
  55416. this._sinYaw = 0.0;
  55417. this._cosYaw = 0.0;
  55418. this._w = 0.0;
  55419. this._mustUnrotateFixedNormals = false;
  55420. this._minimum = BABYLON.Tmp.Vector3[0];
  55421. this._maximum = BABYLON.Tmp.Vector3[1];
  55422. this._scale = BABYLON.Tmp.Vector3[2];
  55423. this._translation = BABYLON.Tmp.Vector3[3];
  55424. this._minBbox = BABYLON.Tmp.Vector3[4];
  55425. this._maxBbox = BABYLON.Tmp.Vector3[5];
  55426. this._particlesIntersect = false;
  55427. this._bSphereOnly = false;
  55428. this._bSphereRadiusFactor = 1.0;
  55429. this.name = name;
  55430. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55431. this._camera = scene.activeCamera;
  55432. this._pickable = options ? options.isPickable : false;
  55433. this._particlesIntersect = options ? options.particleIntersection : false;
  55434. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  55435. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  55436. if (options && options.updatable) {
  55437. this._updatable = options.updatable;
  55438. }
  55439. else {
  55440. this._updatable = true;
  55441. }
  55442. if (this._pickable) {
  55443. this.pickedParticles = [];
  55444. }
  55445. }
  55446. /**
  55447. * Builds the SPS underlying mesh. Returns a standard Mesh.
  55448. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  55449. */
  55450. SolidParticleSystem.prototype.buildMesh = function () {
  55451. if (this.nbParticles === 0) {
  55452. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  55453. this.addShape(triangle, 1);
  55454. triangle.dispose();
  55455. }
  55456. this._positions32 = new Float32Array(this._positions);
  55457. this._uvs32 = new Float32Array(this._uvs);
  55458. this._colors32 = new Float32Array(this._colors);
  55459. if (this.recomputeNormals) {
  55460. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  55461. }
  55462. this._normals32 = new Float32Array(this._normals);
  55463. this._fixedNormal32 = new Float32Array(this._normals);
  55464. if (this._mustUnrotateFixedNormals) {
  55465. this._unrotateFixedNormals();
  55466. }
  55467. var vertexData = new BABYLON.VertexData();
  55468. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  55469. vertexData.indices = this._indices;
  55470. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  55471. if (this._uvs32) {
  55472. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  55473. ;
  55474. }
  55475. if (this._colors32) {
  55476. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  55477. }
  55478. var mesh = new BABYLON.Mesh(this.name, this._scene);
  55479. vertexData.applyToMesh(mesh, this._updatable);
  55480. this.mesh = mesh;
  55481. this.mesh.isPickable = this._pickable;
  55482. // free memory
  55483. this._positions = null;
  55484. this._normals = null;
  55485. this._uvs = null;
  55486. this._colors = null;
  55487. if (!this._updatable) {
  55488. this.particles.length = 0;
  55489. }
  55490. return mesh;
  55491. };
  55492. /**
  55493. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  55494. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  55495. * Thus the particles generated from `digest()` have their property `position` set yet.
  55496. * `mesh` ( Mesh ) is the mesh to be digested
  55497. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  55498. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  55499. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  55500. */
  55501. SolidParticleSystem.prototype.digest = function (mesh, options) {
  55502. var size = (options && options.facetNb) || 1;
  55503. var number = (options && options.number);
  55504. var delta = (options && options.delta) || 0;
  55505. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55506. var meshInd = mesh.getIndices();
  55507. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55508. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55509. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55510. var f = 0; // facet counter
  55511. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  55512. // compute size from number
  55513. if (number) {
  55514. number = (number > totalFacets) ? totalFacets : number;
  55515. size = Math.round(totalFacets / number);
  55516. delta = 0;
  55517. }
  55518. else {
  55519. size = (size > totalFacets) ? totalFacets : size;
  55520. }
  55521. var facetPos = []; // submesh positions
  55522. var facetInd = []; // submesh indices
  55523. var facetUV = []; // submesh UV
  55524. var facetCol = []; // submesh colors
  55525. var barycenter = BABYLON.Tmp.Vector3[0];
  55526. var rand;
  55527. var sizeO = size;
  55528. while (f < totalFacets) {
  55529. size = sizeO + Math.floor((1 + delta) * Math.random());
  55530. if (f > totalFacets - size) {
  55531. size = totalFacets - f;
  55532. }
  55533. // reset temp arrays
  55534. facetPos.length = 0;
  55535. facetInd.length = 0;
  55536. facetUV.length = 0;
  55537. facetCol.length = 0;
  55538. // iterate over "size" facets
  55539. var fi = 0;
  55540. for (var j = f * 3; j < (f + size) * 3; j++) {
  55541. facetInd.push(fi);
  55542. var i = meshInd[j];
  55543. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  55544. if (meshUV) {
  55545. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  55546. }
  55547. if (meshCol) {
  55548. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  55549. }
  55550. fi++;
  55551. }
  55552. // create a model shape for each single particle
  55553. var idx = this.nbParticles;
  55554. var shape = this._posToShape(facetPos);
  55555. var shapeUV = this._uvsToShapeUV(facetUV);
  55556. // compute the barycenter of the shape
  55557. var v;
  55558. for (v = 0; v < shape.length; v++) {
  55559. barycenter.addInPlace(shape[v]);
  55560. }
  55561. barycenter.scaleInPlace(1 / shape.length);
  55562. // shift the shape from its barycenter to the origin
  55563. for (v = 0; v < shape.length; v++) {
  55564. shape[v].subtractInPlace(barycenter);
  55565. }
  55566. var bInfo;
  55567. if (this._particlesIntersect) {
  55568. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  55569. }
  55570. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  55571. // add the particle in the SPS
  55572. var currentPos = this._positions.length;
  55573. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  55574. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  55575. // initialize the particle position
  55576. this.particles[this.nbParticles].position.addInPlace(barycenter);
  55577. this._index += shape.length;
  55578. idx++;
  55579. this.nbParticles++;
  55580. this._shapeCounter++;
  55581. f += size;
  55582. }
  55583. return this;
  55584. };
  55585. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  55586. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  55587. var index = 0;
  55588. var idx = 0;
  55589. for (var p = 0; p < this.particles.length; p++) {
  55590. this._particle = this.particles[p];
  55591. this._shape = this._particle._model._shape;
  55592. if (this._particle.rotationQuaternion) {
  55593. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  55594. }
  55595. else {
  55596. this._yaw = this._particle.rotation.y;
  55597. this._pitch = this._particle.rotation.x;
  55598. this._roll = this._particle.rotation.z;
  55599. this._quaternionRotationYPR();
  55600. }
  55601. this._quaternionToRotationMatrix();
  55602. this._rotMatrix.invertToRef(this._invertMatrix);
  55603. for (var pt = 0; pt < this._shape.length; pt++) {
  55604. idx = index + pt * 3;
  55605. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  55606. this._fixedNormal32[idx] = this._normal.x;
  55607. this._fixedNormal32[idx + 1] = this._normal.y;
  55608. this._fixedNormal32[idx + 2] = this._normal.z;
  55609. }
  55610. index = idx + 3;
  55611. }
  55612. };
  55613. //reset copy
  55614. SolidParticleSystem.prototype._resetCopy = function () {
  55615. this._copy.position.x = 0;
  55616. this._copy.position.y = 0;
  55617. this._copy.position.z = 0;
  55618. this._copy.rotation.x = 0;
  55619. this._copy.rotation.y = 0;
  55620. this._copy.rotation.z = 0;
  55621. this._copy.rotationQuaternion = null;
  55622. this._copy.scaling.x = 1;
  55623. this._copy.scaling.y = 1;
  55624. this._copy.scaling.z = 1;
  55625. this._copy.uvs.x = 0;
  55626. this._copy.uvs.y = 0;
  55627. this._copy.uvs.z = 1;
  55628. this._copy.uvs.w = 1;
  55629. this._copy.color = null;
  55630. };
  55631. // _meshBuilder : inserts the shape model in the global SPS mesh
  55632. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  55633. var i;
  55634. var u = 0;
  55635. var c = 0;
  55636. var n = 0;
  55637. this._resetCopy();
  55638. if (options && options.positionFunction) {
  55639. options.positionFunction(this._copy, idx, idxInShape);
  55640. this._mustUnrotateFixedNormals = true;
  55641. }
  55642. if (this._copy.rotationQuaternion) {
  55643. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55644. }
  55645. else {
  55646. this._yaw = this._copy.rotation.y;
  55647. this._pitch = this._copy.rotation.x;
  55648. this._roll = this._copy.rotation.z;
  55649. this._quaternionRotationYPR();
  55650. }
  55651. this._quaternionToRotationMatrix();
  55652. for (i = 0; i < shape.length; i++) {
  55653. this._vertex.x = shape[i].x;
  55654. this._vertex.y = shape[i].y;
  55655. this._vertex.z = shape[i].z;
  55656. if (options && options.vertexFunction) {
  55657. options.vertexFunction(this._copy, this._vertex, i);
  55658. }
  55659. this._vertex.x *= this._copy.scaling.x;
  55660. this._vertex.y *= this._copy.scaling.y;
  55661. this._vertex.z *= this._copy.scaling.z;
  55662. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55663. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  55664. if (meshUV) {
  55665. 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);
  55666. u += 2;
  55667. }
  55668. if (this._copy.color) {
  55669. this._color = this._copy.color;
  55670. }
  55671. else if (meshCol && meshCol[c] !== undefined) {
  55672. this._color.r = meshCol[c];
  55673. this._color.g = meshCol[c + 1];
  55674. this._color.b = meshCol[c + 2];
  55675. this._color.a = meshCol[c + 3];
  55676. }
  55677. else {
  55678. this._color.r = 1;
  55679. this._color.g = 1;
  55680. this._color.b = 1;
  55681. this._color.a = 1;
  55682. }
  55683. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  55684. c += 4;
  55685. if (!this.recomputeNormals && meshNor) {
  55686. this._normal.x = meshNor[n];
  55687. this._normal.y = meshNor[n + 1];
  55688. this._normal.z = meshNor[n + 2];
  55689. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  55690. normals.push(this._normal.x, this._normal.y, this._normal.z);
  55691. n += 3;
  55692. }
  55693. }
  55694. for (i = 0; i < meshInd.length; i++) {
  55695. indices.push(p + meshInd[i]);
  55696. }
  55697. if (this._pickable) {
  55698. var nbfaces = meshInd.length / 3;
  55699. for (i = 0; i < nbfaces; i++) {
  55700. this.pickedParticles.push({ idx: idx, faceId: i });
  55701. }
  55702. }
  55703. return this._copy;
  55704. };
  55705. // returns a shape array from positions array
  55706. SolidParticleSystem.prototype._posToShape = function (positions) {
  55707. var shape = [];
  55708. for (var i = 0; i < positions.length; i += 3) {
  55709. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  55710. }
  55711. return shape;
  55712. };
  55713. // returns a shapeUV array from a Vector4 uvs
  55714. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  55715. var shapeUV = [];
  55716. if (uvs) {
  55717. for (var i = 0; i < uvs.length; i++)
  55718. shapeUV.push(uvs[i]);
  55719. }
  55720. return shapeUV;
  55721. };
  55722. // adds a new particle object in the particles array
  55723. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  55724. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  55725. this.particles.push(sp);
  55726. return sp;
  55727. };
  55728. /**
  55729. * Adds some particles to the SPS from the model shape. Returns the shape id.
  55730. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  55731. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  55732. * `nb` (positive integer) the number of particles to be created from this model
  55733. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  55734. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  55735. */
  55736. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  55737. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55738. var meshInd = mesh.getIndices();
  55739. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55740. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55741. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55742. var bbInfo;
  55743. if (this._particlesIntersect) {
  55744. bbInfo = mesh.getBoundingInfo();
  55745. }
  55746. var shape = this._posToShape(meshPos);
  55747. var shapeUV = this._uvsToShapeUV(meshUV);
  55748. var posfunc = options ? options.positionFunction : null;
  55749. var vtxfunc = options ? options.vertexFunction : null;
  55750. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  55751. // particles
  55752. var sp;
  55753. var currentCopy;
  55754. var idx = this.nbParticles;
  55755. for (var i = 0; i < nb; i++) {
  55756. var currentPos = this._positions.length;
  55757. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  55758. if (this._updatable) {
  55759. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  55760. sp.position.copyFrom(currentCopy.position);
  55761. sp.rotation.copyFrom(currentCopy.rotation);
  55762. if (currentCopy.rotationQuaternion) {
  55763. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  55764. }
  55765. if (currentCopy.color) {
  55766. sp.color.copyFrom(currentCopy.color);
  55767. }
  55768. sp.scaling.copyFrom(currentCopy.scaling);
  55769. sp.uvs.copyFrom(currentCopy.uvs);
  55770. }
  55771. this._index += shape.length;
  55772. idx++;
  55773. }
  55774. this.nbParticles += nb;
  55775. this._shapeCounter++;
  55776. return this._shapeCounter - 1;
  55777. };
  55778. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  55779. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  55780. this._resetCopy();
  55781. if (particle._model._positionFunction) {
  55782. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  55783. }
  55784. if (this._copy.rotationQuaternion) {
  55785. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55786. }
  55787. else {
  55788. this._yaw = this._copy.rotation.y;
  55789. this._pitch = this._copy.rotation.x;
  55790. this._roll = this._copy.rotation.z;
  55791. this._quaternionRotationYPR();
  55792. }
  55793. this._quaternionToRotationMatrix();
  55794. this._shape = particle._model._shape;
  55795. for (var pt = 0; pt < this._shape.length; pt++) {
  55796. this._vertex.x = this._shape[pt].x;
  55797. this._vertex.y = this._shape[pt].y;
  55798. this._vertex.z = this._shape[pt].z;
  55799. if (particle._model._vertexFunction) {
  55800. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  55801. }
  55802. this._vertex.x *= this._copy.scaling.x;
  55803. this._vertex.y *= this._copy.scaling.y;
  55804. this._vertex.z *= this._copy.scaling.z;
  55805. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55806. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  55807. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  55808. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  55809. }
  55810. particle.position.x = 0.0;
  55811. particle.position.y = 0.0;
  55812. particle.position.z = 0.0;
  55813. particle.rotation.x = 0.0;
  55814. particle.rotation.y = 0.0;
  55815. particle.rotation.z = 0.0;
  55816. particle.rotationQuaternion = null;
  55817. particle.scaling.x = 1.0;
  55818. particle.scaling.y = 1.0;
  55819. particle.scaling.z = 1.0;
  55820. };
  55821. /**
  55822. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  55823. * Returns the SPS.
  55824. */
  55825. SolidParticleSystem.prototype.rebuildMesh = function () {
  55826. for (var p = 0; p < this.particles.length; p++) {
  55827. this._rebuildParticle(this.particles[p]);
  55828. }
  55829. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55830. return this;
  55831. };
  55832. /**
  55833. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  55834. * This method calls `updateParticle()` for each particle of the SPS.
  55835. * For an animated SPS, it is usually called within the render loop.
  55836. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  55837. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  55838. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  55839. * Returns the SPS.
  55840. */
  55841. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  55842. if (start === void 0) { start = 0; }
  55843. if (end === void 0) { end = this.nbParticles - 1; }
  55844. if (update === void 0) { update = true; }
  55845. if (!this._updatable) {
  55846. return;
  55847. }
  55848. // custom beforeUpdate
  55849. this.beforeUpdateParticles(start, end, update);
  55850. this._cam_axisX.x = 1.0;
  55851. this._cam_axisX.y = 0.0;
  55852. this._cam_axisX.z = 0.0;
  55853. this._cam_axisY.x = 0.0;
  55854. this._cam_axisY.y = 1.0;
  55855. this._cam_axisY.z = 0.0;
  55856. this._cam_axisZ.x = 0.0;
  55857. this._cam_axisZ.y = 0.0;
  55858. this._cam_axisZ.z = 1.0;
  55859. // if the particles will always face the camera
  55860. if (this.billboard) {
  55861. this.mesh.computeWorldMatrix(true);
  55862. // compute the camera position and un-rotate it by the current mesh rotation
  55863. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  55864. this._quaternionToRotationMatrix();
  55865. this._rotMatrix.invertToRef(this._invertMatrix);
  55866. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  55867. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  55868. this._cam_axisZ.normalize();
  55869. // same for camera up vector extracted from the cam view matrix
  55870. var view = this._camera.getViewMatrix(true);
  55871. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  55872. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  55873. this._cam_axisY.normalize();
  55874. this._cam_axisX.normalize();
  55875. }
  55876. }
  55877. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  55878. var idx = 0; // current position index in the global array positions32
  55879. var index = 0; // position start index in the global array positions32 of the current particle
  55880. var colidx = 0; // current color index in the global array colors32
  55881. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  55882. var uvidx = 0; // current uv index in the global array uvs32
  55883. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  55884. var pt = 0; // current index in the particle model shape
  55885. if (this.mesh.isFacetDataEnabled) {
  55886. this._computeBoundingBox = true;
  55887. }
  55888. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  55889. if (this._computeBoundingBox) {
  55890. if (start == 0 && end == this.nbParticles - 1) {
  55891. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  55892. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  55893. }
  55894. else {
  55895. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  55896. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  55897. }
  55898. }
  55899. // particle loop
  55900. index = this.particles[start]._pos;
  55901. var vpos = (index / 3) | 0;
  55902. colorIndex = vpos * 4;
  55903. uvIndex = vpos * 2;
  55904. for (var p = start; p <= end; p++) {
  55905. this._particle = this.particles[p];
  55906. this._shape = this._particle._model._shape;
  55907. this._shapeUV = this._particle._model._shapeUV;
  55908. // call to custom user function to update the particle properties
  55909. this.updateParticle(this._particle);
  55910. if (this._particle.isVisible) {
  55911. // particle rotation matrix
  55912. if (this.billboard) {
  55913. this._particle.rotation.x = 0.0;
  55914. this._particle.rotation.y = 0.0;
  55915. }
  55916. if (this._computeParticleRotation || this.billboard) {
  55917. if (this._particle.rotationQuaternion) {
  55918. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  55919. }
  55920. else {
  55921. this._yaw = this._particle.rotation.y;
  55922. this._pitch = this._particle.rotation.x;
  55923. this._roll = this._particle.rotation.z;
  55924. this._quaternionRotationYPR();
  55925. }
  55926. this._quaternionToRotationMatrix();
  55927. }
  55928. // particle vertex loop
  55929. for (pt = 0; pt < this._shape.length; pt++) {
  55930. idx = index + pt * 3;
  55931. colidx = colorIndex + pt * 4;
  55932. uvidx = uvIndex + pt * 2;
  55933. this._vertex.x = this._shape[pt].x;
  55934. this._vertex.y = this._shape[pt].y;
  55935. this._vertex.z = this._shape[pt].z;
  55936. if (this._computeParticleVertex) {
  55937. this.updateParticleVertex(this._particle, this._vertex, pt);
  55938. }
  55939. // positions
  55940. this._vertex.x *= this._particle.scaling.x;
  55941. this._vertex.y *= this._particle.scaling.y;
  55942. this._vertex.z *= this._particle.scaling.z;
  55943. 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];
  55944. 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;
  55945. 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;
  55946. 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;
  55947. 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;
  55948. 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;
  55949. 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;
  55950. if (this._computeBoundingBox) {
  55951. if (this._positions32[idx] < this._minimum.x) {
  55952. this._minimum.x = this._positions32[idx];
  55953. }
  55954. if (this._positions32[idx] > this._maximum.x) {
  55955. this._maximum.x = this._positions32[idx];
  55956. }
  55957. if (this._positions32[idx + 1] < this._minimum.y) {
  55958. this._minimum.y = this._positions32[idx + 1];
  55959. }
  55960. if (this._positions32[idx + 1] > this._maximum.y) {
  55961. this._maximum.y = this._positions32[idx + 1];
  55962. }
  55963. if (this._positions32[idx + 2] < this._minimum.z) {
  55964. this._minimum.z = this._positions32[idx + 2];
  55965. }
  55966. if (this._positions32[idx + 2] > this._maximum.z) {
  55967. this._maximum.z = this._positions32[idx + 2];
  55968. }
  55969. }
  55970. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  55971. if (!this._computeParticleVertex) {
  55972. this._normal.x = this._fixedNormal32[idx];
  55973. this._normal.y = this._fixedNormal32[idx + 1];
  55974. this._normal.z = this._fixedNormal32[idx + 2];
  55975. 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]);
  55976. 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]);
  55977. 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]);
  55978. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  55979. 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;
  55980. 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;
  55981. }
  55982. if (this._computeParticleColor) {
  55983. this._colors32[colidx] = this._particle.color.r;
  55984. this._colors32[colidx + 1] = this._particle.color.g;
  55985. this._colors32[colidx + 2] = this._particle.color.b;
  55986. this._colors32[colidx + 3] = this._particle.color.a;
  55987. }
  55988. if (this._computeParticleTexture) {
  55989. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  55990. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  55991. }
  55992. }
  55993. }
  55994. else {
  55995. for (pt = 0; pt < this._shape.length; pt++) {
  55996. idx = index + pt * 3;
  55997. colidx = colorIndex + pt * 4;
  55998. uvidx = uvIndex + pt * 2;
  55999. this._positions32[idx] = this._camera.position.x;
  56000. this._positions32[idx + 1] = this._camera.position.y;
  56001. this._positions32[idx + 2] = this._camera.position.z;
  56002. this._normals32[idx] = 0.0;
  56003. this._normals32[idx + 1] = 0.0;
  56004. this._normals32[idx + 2] = 0.0;
  56005. if (this._computeParticleColor) {
  56006. this._colors32[colidx] = this._particle.color.r;
  56007. this._colors32[colidx + 1] = this._particle.color.g;
  56008. this._colors32[colidx + 2] = this._particle.color.b;
  56009. this._colors32[colidx + 3] = this._particle.color.a;
  56010. }
  56011. if (this._computeParticleTexture) {
  56012. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  56013. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  56014. }
  56015. }
  56016. }
  56017. // if the particle intersections must be computed : update the bbInfo
  56018. if (this._particlesIntersect) {
  56019. var bInfo = this._particle._boundingInfo;
  56020. var bBox = bInfo.boundingBox;
  56021. var bSphere = bInfo.boundingSphere;
  56022. if (!this._bSphereOnly) {
  56023. // place, scale and rotate the particle bbox within the SPS local system, then update it
  56024. for (var b = 0; b < bBox.vectors.length; b++) {
  56025. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  56026. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  56027. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  56028. 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];
  56029. 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;
  56030. 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;
  56031. 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;
  56032. 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;
  56033. 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;
  56034. 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;
  56035. }
  56036. bBox._update(this.mesh._worldMatrix);
  56037. }
  56038. // place and scale the particle bouding sphere in the SPS local system, then update it
  56039. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  56040. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  56041. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  56042. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  56043. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  56044. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  56045. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  56046. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  56047. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  56048. 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));
  56049. bSphere._update(this.mesh._worldMatrix);
  56050. }
  56051. // increment indexes for the next particle
  56052. index = idx + 3;
  56053. colorIndex = colidx + 4;
  56054. uvIndex = uvidx + 2;
  56055. }
  56056. // if the VBO must be updated
  56057. if (update) {
  56058. if (this._computeParticleColor) {
  56059. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  56060. }
  56061. if (this._computeParticleTexture) {
  56062. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  56063. }
  56064. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  56065. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  56066. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  56067. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  56068. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  56069. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  56070. for (var i = 0; i < this._normals32.length; i++) {
  56071. this._fixedNormal32[i] = this._normals32[i];
  56072. }
  56073. }
  56074. if (!this.mesh.areNormalsFrozen) {
  56075. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  56076. }
  56077. }
  56078. }
  56079. if (this._computeBoundingBox) {
  56080. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  56081. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  56082. }
  56083. this.afterUpdateParticles(start, end, update);
  56084. return this;
  56085. };
  56086. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  56087. this._halfroll = this._roll * 0.5;
  56088. this._halfpitch = this._pitch * 0.5;
  56089. this._halfyaw = this._yaw * 0.5;
  56090. this._sinRoll = Math.sin(this._halfroll);
  56091. this._cosRoll = Math.cos(this._halfroll);
  56092. this._sinPitch = Math.sin(this._halfpitch);
  56093. this._cosPitch = Math.cos(this._halfpitch);
  56094. this._sinYaw = Math.sin(this._halfyaw);
  56095. this._cosYaw = Math.cos(this._halfyaw);
  56096. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  56097. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  56098. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  56099. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  56100. };
  56101. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  56102. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  56103. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  56104. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  56105. this._rotMatrix.m[3] = 0;
  56106. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  56107. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  56108. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  56109. this._rotMatrix.m[7] = 0;
  56110. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  56111. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  56112. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  56113. this._rotMatrix.m[11] = 0;
  56114. this._rotMatrix.m[12] = 0;
  56115. this._rotMatrix.m[13] = 0;
  56116. this._rotMatrix.m[14] = 0;
  56117. this._rotMatrix.m[15] = 1.0;
  56118. };
  56119. /**
  56120. * Disposes the SPS.
  56121. * Returns nothing.
  56122. */
  56123. SolidParticleSystem.prototype.dispose = function () {
  56124. this.mesh.dispose();
  56125. this.vars = null;
  56126. // drop references to internal big arrays for the GC
  56127. this._positions = null;
  56128. this._indices = null;
  56129. this._normals = null;
  56130. this._uvs = null;
  56131. this._colors = null;
  56132. this._positions32 = null;
  56133. this._normals32 = null;
  56134. this._fixedNormal32 = null;
  56135. this._uvs32 = null;
  56136. this._colors32 = null;
  56137. this.pickedParticles = null;
  56138. };
  56139. /**
  56140. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  56141. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56142. * Returns the SPS.
  56143. */
  56144. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  56145. if (!this._isVisibilityBoxLocked) {
  56146. this.mesh.refreshBoundingInfo();
  56147. }
  56148. return this;
  56149. };
  56150. /**
  56151. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  56152. * @param size the size (float) of the visibility box
  56153. * note : this doesn't lock the SPS mesh bounding box.
  56154. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56155. */
  56156. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  56157. var vis = size / 2;
  56158. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  56159. };
  56160. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  56161. // getter and setter
  56162. get: function () {
  56163. return this._alwaysVisible;
  56164. },
  56165. /**
  56166. * Sets the SPS as always visible or not
  56167. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56168. */
  56169. set: function (val) {
  56170. this._alwaysVisible = val;
  56171. this.mesh.alwaysSelectAsActiveMesh = val;
  56172. },
  56173. enumerable: true,
  56174. configurable: true
  56175. });
  56176. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  56177. get: function () {
  56178. return this._isVisibilityBoxLocked;
  56179. },
  56180. /**
  56181. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  56182. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56183. */
  56184. set: function (val) {
  56185. this._isVisibilityBoxLocked = val;
  56186. this.mesh.getBoundingInfo().isLocked = val;
  56187. },
  56188. enumerable: true,
  56189. configurable: true
  56190. });
  56191. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  56192. // getters
  56193. get: function () {
  56194. return this._computeParticleRotation;
  56195. },
  56196. // Optimizer setters
  56197. /**
  56198. * Tells to `setParticles()` to compute the particle rotations or not.
  56199. * Default value : true. The SPS is faster when it's set to false.
  56200. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  56201. */
  56202. set: function (val) {
  56203. this._computeParticleRotation = val;
  56204. },
  56205. enumerable: true,
  56206. configurable: true
  56207. });
  56208. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  56209. get: function () {
  56210. return this._computeParticleColor;
  56211. },
  56212. /**
  56213. * Tells to `setParticles()` to compute the particle colors or not.
  56214. * Default value : true. The SPS is faster when it's set to false.
  56215. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  56216. */
  56217. set: function (val) {
  56218. this._computeParticleColor = val;
  56219. },
  56220. enumerable: true,
  56221. configurable: true
  56222. });
  56223. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  56224. get: function () {
  56225. return this._computeParticleTexture;
  56226. },
  56227. /**
  56228. * Tells to `setParticles()` to compute the particle textures or not.
  56229. * Default value : true. The SPS is faster when it's set to false.
  56230. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  56231. */
  56232. set: function (val) {
  56233. this._computeParticleTexture = val;
  56234. },
  56235. enumerable: true,
  56236. configurable: true
  56237. });
  56238. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  56239. get: function () {
  56240. return this._computeParticleVertex;
  56241. },
  56242. /**
  56243. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  56244. * Default value : false. The SPS is faster when it's set to false.
  56245. * Note : the particle custom vertex positions aren't stored values.
  56246. */
  56247. set: function (val) {
  56248. this._computeParticleVertex = val;
  56249. },
  56250. enumerable: true,
  56251. configurable: true
  56252. });
  56253. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  56254. get: function () {
  56255. return this._computeBoundingBox;
  56256. },
  56257. /**
  56258. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  56259. */
  56260. set: function (val) {
  56261. this._computeBoundingBox = val;
  56262. },
  56263. enumerable: true,
  56264. configurable: true
  56265. });
  56266. // =======================================================================
  56267. // Particle behavior logic
  56268. // these following methods may be overwritten by the user to fit his needs
  56269. /**
  56270. * This function does nothing. It may be overwritten to set all the particle first values.
  56271. * The SPS doesn't call this function, you may have to call it by your own.
  56272. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56273. */
  56274. SolidParticleSystem.prototype.initParticles = function () {
  56275. };
  56276. /**
  56277. * This function does nothing. It may be overwritten to recycle a particle.
  56278. * The SPS doesn't call this function, you may have to call it by your own.
  56279. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56280. */
  56281. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  56282. return particle;
  56283. };
  56284. /**
  56285. * Updates a particle : this function should be overwritten by the user.
  56286. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  56287. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56288. * ex : just set a particle position or velocity and recycle conditions
  56289. */
  56290. SolidParticleSystem.prototype.updateParticle = function (particle) {
  56291. return particle;
  56292. };
  56293. /**
  56294. * Updates a vertex of a particle : it can be overwritten by the user.
  56295. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  56296. * @param particle the current particle
  56297. * @param vertex the current index of the current particle
  56298. * @param pt the index of the current vertex in the particle shape
  56299. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  56300. * ex : just set a vertex particle position
  56301. */
  56302. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  56303. return vertex;
  56304. };
  56305. /**
  56306. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  56307. * This does nothing and may be overwritten by the user.
  56308. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56309. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56310. * @param update the boolean update value actually passed to setParticles()
  56311. */
  56312. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  56313. };
  56314. /**
  56315. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  56316. * This will be passed three parameters.
  56317. * This does nothing and may be overwritten by the user.
  56318. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56319. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56320. * @param update the boolean update value actually passed to setParticles()
  56321. */
  56322. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  56323. };
  56324. return SolidParticleSystem;
  56325. }());
  56326. BABYLON.SolidParticleSystem = SolidParticleSystem;
  56327. })(BABYLON || (BABYLON = {}));
  56328. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  56329. var BABYLON;
  56330. (function (BABYLON) {
  56331. var Internals;
  56332. (function (Internals) {
  56333. var FileFaceOrientation = (function () {
  56334. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  56335. this.name = name;
  56336. this.worldAxisForNormal = worldAxisForNormal;
  56337. this.worldAxisForFileX = worldAxisForFileX;
  56338. this.worldAxisForFileY = worldAxisForFileY;
  56339. }
  56340. return FileFaceOrientation;
  56341. }());
  56342. ;
  56343. /**
  56344. * Helper class dealing with the extraction of spherical polynomial dataArray
  56345. * from a cube map.
  56346. */
  56347. var CubeMapToSphericalPolynomialTools = (function () {
  56348. function CubeMapToSphericalPolynomialTools() {
  56349. }
  56350. /**
  56351. * Converts a cubemap to the according Spherical Polynomial data.
  56352. * This extracts the first 3 orders only as they are the only one used in the lighting.
  56353. *
  56354. * @param cubeInfo The Cube map to extract the information from.
  56355. * @return The Spherical Polynomial data.
  56356. */
  56357. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  56358. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  56359. var totalSolidAngle = 0.0;
  56360. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  56361. var du = 2.0 / cubeInfo.size;
  56362. var dv = du;
  56363. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  56364. var minUV = du * 0.5 - 1.0;
  56365. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56366. var fileFace = this.FileFaces[faceIndex];
  56367. var dataArray = cubeInfo[fileFace.name];
  56368. var v = minUV;
  56369. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  56370. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  56371. // Because SP is still linear, so summation is fine in that basis.
  56372. for (var y = 0; y < cubeInfo.size; y++) {
  56373. var u = minUV;
  56374. for (var x = 0; x < cubeInfo.size; x++) {
  56375. // World direction (not normalised)
  56376. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  56377. worldDirection.normalize();
  56378. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  56379. if (1) {
  56380. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  56381. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  56382. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  56383. var color = new BABYLON.Color3(r, g, b);
  56384. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56385. }
  56386. else {
  56387. if (faceIndex == 0) {
  56388. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56389. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56390. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56391. }
  56392. else if (faceIndex == 1) {
  56393. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56394. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56395. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56396. }
  56397. else if (faceIndex == 2) {
  56398. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56399. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56400. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56401. }
  56402. else if (faceIndex == 3) {
  56403. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56404. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56405. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56406. }
  56407. else if (faceIndex == 4) {
  56408. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56409. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56410. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56411. }
  56412. else if (faceIndex == 5) {
  56413. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56414. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56415. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56416. }
  56417. 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]);
  56418. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56419. }
  56420. totalSolidAngle += deltaSolidAngle;
  56421. u += du;
  56422. }
  56423. v += dv;
  56424. }
  56425. }
  56426. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  56427. var correction = correctSolidAngle / totalSolidAngle;
  56428. sphericalHarmonics.scale(correction);
  56429. // Additionally scale by pi -- audit needed
  56430. sphericalHarmonics.scale(1.0 / Math.PI);
  56431. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  56432. };
  56433. return CubeMapToSphericalPolynomialTools;
  56434. }());
  56435. CubeMapToSphericalPolynomialTools.FileFaces = [
  56436. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  56437. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  56438. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  56439. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  56440. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  56441. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  56442. ];
  56443. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  56444. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56445. })(BABYLON || (BABYLON = {}));
  56446. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  56447. var BABYLON;
  56448. (function (BABYLON) {
  56449. var Internals;
  56450. (function (Internals) {
  56451. /**
  56452. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  56453. */
  56454. var PanoramaToCubeMapTools = (function () {
  56455. function PanoramaToCubeMapTools() {
  56456. }
  56457. /**
  56458. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  56459. *
  56460. * @param float32Array The source data.
  56461. * @param inputWidth The width of the input panorama.
  56462. * @param inputhHeight The height of the input panorama.
  56463. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  56464. * @return The cubemap data
  56465. */
  56466. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  56467. if (!float32Array) {
  56468. throw "ConvertPanoramaToCubemap: input cannot be null";
  56469. }
  56470. if (float32Array.length != inputWidth * inputHeight * 3) {
  56471. throw "ConvertPanoramaToCubemap: input size is wrong";
  56472. }
  56473. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  56474. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  56475. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  56476. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  56477. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  56478. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  56479. return {
  56480. front: textureFront,
  56481. back: textureBack,
  56482. left: textureLeft,
  56483. right: textureRight,
  56484. up: textureUp,
  56485. down: textureDown,
  56486. size: size
  56487. };
  56488. };
  56489. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  56490. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  56491. var textureArray = new Float32Array(buffer);
  56492. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  56493. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  56494. var dy = 1 / texSize;
  56495. var fy = 0;
  56496. for (var y = 0; y < texSize; y++) {
  56497. var xv1 = faceData[0];
  56498. var xv2 = faceData[2];
  56499. for (var x = 0; x < texSize; x++) {
  56500. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  56501. v.normalize();
  56502. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  56503. // 3 channels per pixels
  56504. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  56505. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  56506. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  56507. xv1 = xv1.add(rotDX1);
  56508. xv2 = xv2.add(rotDX2);
  56509. }
  56510. fy += dy;
  56511. }
  56512. return textureArray;
  56513. };
  56514. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  56515. var theta = Math.atan2(vDir.z, vDir.x);
  56516. var phi = Math.acos(vDir.y);
  56517. while (theta < -Math.PI)
  56518. theta += 2 * Math.PI;
  56519. while (theta > Math.PI)
  56520. theta -= 2 * Math.PI;
  56521. var dx = theta / Math.PI;
  56522. var dy = phi / Math.PI;
  56523. // recenter.
  56524. dx = dx * 0.5 + 0.5;
  56525. var px = Math.round(dx * inputWidth);
  56526. if (px < 0)
  56527. px = 0;
  56528. else if (px >= inputWidth)
  56529. px = inputWidth - 1;
  56530. var py = Math.round(dy * inputHeight);
  56531. if (py < 0)
  56532. py = 0;
  56533. else if (py >= inputHeight)
  56534. py = inputHeight - 1;
  56535. var inputY = (inputHeight - py - 1);
  56536. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  56537. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  56538. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  56539. return {
  56540. r: r,
  56541. g: g,
  56542. b: b
  56543. };
  56544. };
  56545. return PanoramaToCubeMapTools;
  56546. }());
  56547. PanoramaToCubeMapTools.FACE_FRONT = [
  56548. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56549. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56550. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56551. new BABYLON.Vector3(1.0, 1.0, -1.0)
  56552. ];
  56553. PanoramaToCubeMapTools.FACE_BACK = [
  56554. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56555. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56556. new BABYLON.Vector3(1.0, 1.0, 1.0),
  56557. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  56558. ];
  56559. PanoramaToCubeMapTools.FACE_RIGHT = [
  56560. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56561. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56562. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56563. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56564. ];
  56565. PanoramaToCubeMapTools.FACE_LEFT = [
  56566. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56567. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56568. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56569. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  56570. ];
  56571. PanoramaToCubeMapTools.FACE_DOWN = [
  56572. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56573. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56574. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56575. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56576. ];
  56577. PanoramaToCubeMapTools.FACE_UP = [
  56578. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56579. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56580. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56581. new BABYLON.Vector3(1.0, -1.0, -1.0)
  56582. ];
  56583. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  56584. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56585. })(BABYLON || (BABYLON = {}));
  56586. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  56587. var BABYLON;
  56588. (function (BABYLON) {
  56589. var Internals;
  56590. (function (Internals) {
  56591. ;
  56592. /**
  56593. * This groups tools to convert HDR texture to native colors array.
  56594. */
  56595. var HDRTools = (function () {
  56596. function HDRTools() {
  56597. }
  56598. HDRTools.Ldexp = function (mantissa, exponent) {
  56599. if (exponent > 1023) {
  56600. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  56601. }
  56602. if (exponent < -1074) {
  56603. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  56604. }
  56605. return mantissa * Math.pow(2, exponent);
  56606. };
  56607. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  56608. if (exponent > 0) {
  56609. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  56610. float32array[index + 0] = red * exponent;
  56611. float32array[index + 1] = green * exponent;
  56612. float32array[index + 2] = blue * exponent;
  56613. }
  56614. else {
  56615. float32array[index + 0] = 0;
  56616. float32array[index + 1] = 0;
  56617. float32array[index + 2] = 0;
  56618. }
  56619. };
  56620. HDRTools.readStringLine = function (uint8array, startIndex) {
  56621. var line = "";
  56622. var character = "";
  56623. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  56624. character = String.fromCharCode(uint8array[i]);
  56625. if (character == "\n") {
  56626. break;
  56627. }
  56628. line += character;
  56629. }
  56630. return line;
  56631. };
  56632. /**
  56633. * Reads header information from an RGBE texture stored in a native array.
  56634. * More information on this format are available here:
  56635. * https://en.wikipedia.org/wiki/RGBE_image_format
  56636. *
  56637. * @param uint8array The binary file stored in native array.
  56638. * @return The header information.
  56639. */
  56640. HDRTools.RGBE_ReadHeader = function (uint8array) {
  56641. var height = 0;
  56642. var width = 0;
  56643. var line = this.readStringLine(uint8array, 0);
  56644. if (line[0] != '#' || line[1] != '?') {
  56645. throw "Bad HDR Format.";
  56646. }
  56647. var endOfHeader = false;
  56648. var findFormat = false;
  56649. var lineIndex = 0;
  56650. do {
  56651. lineIndex += (line.length + 1);
  56652. line = this.readStringLine(uint8array, lineIndex);
  56653. if (line == "FORMAT=32-bit_rle_rgbe") {
  56654. findFormat = true;
  56655. }
  56656. else if (line.length == 0) {
  56657. endOfHeader = true;
  56658. }
  56659. } while (!endOfHeader);
  56660. if (!findFormat) {
  56661. throw "HDR Bad header format, unsupported FORMAT";
  56662. }
  56663. lineIndex += (line.length + 1);
  56664. line = this.readStringLine(uint8array, lineIndex);
  56665. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  56666. var match = sizeRegexp.exec(line);
  56667. // TODO. Support +Y and -X if needed.
  56668. if (match.length < 3) {
  56669. throw "HDR Bad header format, no size";
  56670. }
  56671. width = parseInt(match[2]);
  56672. height = parseInt(match[1]);
  56673. if (width < 8 || width > 0x7fff) {
  56674. throw "HDR Bad header format, unsupported size";
  56675. }
  56676. lineIndex += (line.length + 1);
  56677. return {
  56678. height: height,
  56679. width: width,
  56680. dataPosition: lineIndex
  56681. };
  56682. };
  56683. /**
  56684. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  56685. * This RGBE texture needs to store the information as a panorama.
  56686. *
  56687. * More information on this format are available here:
  56688. * https://en.wikipedia.org/wiki/RGBE_image_format
  56689. *
  56690. * @param buffer The binary file stored in an array buffer.
  56691. * @param size The expected size of the extracted cubemap.
  56692. * @return The Cube Map information.
  56693. */
  56694. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  56695. var uint8array = new Uint8Array(buffer);
  56696. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  56697. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56698. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  56699. return cubeMapData;
  56700. };
  56701. /**
  56702. * Returns the pixels data extracted from an RGBE texture.
  56703. * This pixels will be stored left to right up to down in the R G B order in one array.
  56704. *
  56705. * More information on this format are available here:
  56706. * https://en.wikipedia.org/wiki/RGBE_image_format
  56707. *
  56708. * @param uint8array The binary file stored in an array buffer.
  56709. * @param hdrInfo The header information of the file.
  56710. * @return The pixels data in RGB right to left up to down order.
  56711. */
  56712. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  56713. // Keep for multi format supports.
  56714. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56715. };
  56716. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  56717. var num_scanlines = hdrInfo.height;
  56718. var scanline_width = hdrInfo.width;
  56719. var a, b, c, d, count;
  56720. var dataIndex = hdrInfo.dataPosition;
  56721. var index = 0, endIndex = 0, i = 0;
  56722. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  56723. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  56724. // 3 channels of 4 bytes per pixel in float.
  56725. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  56726. var resultArray = new Float32Array(resultBuffer);
  56727. // read in each successive scanline
  56728. while (num_scanlines > 0) {
  56729. a = uint8array[dataIndex++];
  56730. b = uint8array[dataIndex++];
  56731. c = uint8array[dataIndex++];
  56732. d = uint8array[dataIndex++];
  56733. if (a != 2 || b != 2 || (c & 0x80)) {
  56734. // this file is not run length encoded
  56735. throw "HDR Bad header format, not RLE";
  56736. }
  56737. if (((c << 8) | d) != scanline_width) {
  56738. throw "HDR Bad header format, wrong scan line width";
  56739. }
  56740. index = 0;
  56741. // read each of the four channels for the scanline into the buffer
  56742. for (i = 0; i < 4; i++) {
  56743. endIndex = (i + 1) * scanline_width;
  56744. while (index < endIndex) {
  56745. a = uint8array[dataIndex++];
  56746. b = uint8array[dataIndex++];
  56747. if (a > 128) {
  56748. // a run of the same value
  56749. count = a - 128;
  56750. if ((count == 0) || (count > endIndex - index)) {
  56751. throw "HDR Bad Format, bad scanline data (run)";
  56752. }
  56753. while (count-- > 0) {
  56754. scanLineArray[index++] = b;
  56755. }
  56756. }
  56757. else {
  56758. // a non-run
  56759. count = a;
  56760. if ((count == 0) || (count > endIndex - index)) {
  56761. throw "HDR Bad Format, bad scanline data (non-run)";
  56762. }
  56763. scanLineArray[index++] = b;
  56764. if (--count > 0) {
  56765. for (var j = 0; j < count; j++) {
  56766. scanLineArray[index++] = uint8array[dataIndex++];
  56767. }
  56768. }
  56769. }
  56770. }
  56771. }
  56772. // now convert data from buffer into floats
  56773. for (i = 0; i < scanline_width; i++) {
  56774. a = scanLineArray[i];
  56775. b = scanLineArray[i + scanline_width];
  56776. c = scanLineArray[i + 2 * scanline_width];
  56777. d = scanLineArray[i + 3 * scanline_width];
  56778. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  56779. }
  56780. num_scanlines--;
  56781. }
  56782. return resultArray;
  56783. };
  56784. return HDRTools;
  56785. }());
  56786. Internals.HDRTools = HDRTools;
  56787. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56788. })(BABYLON || (BABYLON = {}));
  56789. //# sourceMappingURL=babylon.tools.hdr.js.map
  56790. //_______________________________________________________________
  56791. // Extracted from CubeMapGen:
  56792. // https://code.google.com/archive/p/cubemapgen/
  56793. //
  56794. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  56795. //_______________________________________________________________
  56796. var BABYLON;
  56797. (function (BABYLON) {
  56798. var Internals;
  56799. (function (Internals) {
  56800. /**
  56801. * The bounding box information used during the conversion process.
  56802. */
  56803. var CMGBoundinBox = (function () {
  56804. function CMGBoundinBox() {
  56805. this.min = new BABYLON.Vector3(0, 0, 0);
  56806. this.max = new BABYLON.Vector3(0, 0, 0);
  56807. this.clear();
  56808. }
  56809. CMGBoundinBox.prototype.clear = function () {
  56810. this.min.x = CMGBoundinBox.MAX;
  56811. this.min.y = CMGBoundinBox.MAX;
  56812. this.min.z = CMGBoundinBox.MAX;
  56813. this.max.x = CMGBoundinBox.MIN;
  56814. this.max.y = CMGBoundinBox.MIN;
  56815. this.max.z = CMGBoundinBox.MIN;
  56816. };
  56817. CMGBoundinBox.prototype.augment = function (x, y, z) {
  56818. this.min.x = Math.min(this.min.x, x);
  56819. this.min.y = Math.min(this.min.y, y);
  56820. this.min.z = Math.min(this.min.z, z);
  56821. this.max.x = Math.max(this.max.x, x);
  56822. this.max.y = Math.max(this.max.y, y);
  56823. this.max.z = Math.max(this.max.z, z);
  56824. };
  56825. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  56826. this.min.x = Math.max(this.min.x, x);
  56827. this.min.y = Math.max(this.min.y, y);
  56828. this.min.z = Math.max(this.min.z, z);
  56829. };
  56830. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  56831. this.max.x = Math.min(this.max.x, x);
  56832. this.max.y = Math.min(this.max.y, y);
  56833. this.max.z = Math.min(this.max.z, z);
  56834. };
  56835. CMGBoundinBox.prototype.empty = function () {
  56836. if ((this.min.x > this.max.y) ||
  56837. (this.min.y > this.max.y) ||
  56838. (this.min.z > this.max.y)) {
  56839. return true;
  56840. }
  56841. else {
  56842. return false;
  56843. }
  56844. };
  56845. return CMGBoundinBox;
  56846. }());
  56847. CMGBoundinBox.MAX = Number.MAX_VALUE;
  56848. CMGBoundinBox.MIN = Number.MIN_VALUE;
  56849. /**
  56850. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  56851. * required by the glossinees of a material.
  56852. *
  56853. * This only supports the cosine drop power as well as Warp fixup generation method.
  56854. *
  56855. * This is using the process from CubeMapGen described here:
  56856. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  56857. */
  56858. var PMREMGenerator = (function () {
  56859. /**
  56860. * Constructor of the generator.
  56861. *
  56862. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  56863. * @param inputSize The size of the cubemap faces
  56864. * @param outputSize The size of the output cubemap faces
  56865. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  56866. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  56867. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  56868. * @param specularPower The max specular level of the desired cubemap
  56869. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  56870. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  56871. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  56872. */
  56873. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  56874. this.input = input;
  56875. this.inputSize = inputSize;
  56876. this.outputSize = outputSize;
  56877. this.maxNumMipLevels = maxNumMipLevels;
  56878. this.numChannels = numChannels;
  56879. this.isFloat = isFloat;
  56880. this.specularPower = specularPower;
  56881. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  56882. this.excludeBase = excludeBase;
  56883. this.fixup = fixup;
  56884. this._outputSurface = [];
  56885. this._numMipLevels = 0;
  56886. }
  56887. /**
  56888. * Launches the filter process and return the result.
  56889. *
  56890. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  56891. */
  56892. PMREMGenerator.prototype.filterCubeMap = function () {
  56893. // Init cubemap processor
  56894. this.init();
  56895. // Filters the cubemap
  56896. this.filterCubeMapMipChain();
  56897. // Returns the filtered mips.
  56898. return this._outputSurface;
  56899. };
  56900. PMREMGenerator.prototype.init = function () {
  56901. var i;
  56902. var j;
  56903. var mipLevelSize;
  56904. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  56905. if (this.maxNumMipLevels == 0) {
  56906. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  56907. }
  56908. //first miplevel size
  56909. mipLevelSize = this.outputSize;
  56910. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  56911. for (j = 0; j < this.maxNumMipLevels; j++) {
  56912. this._outputSurface.length++;
  56913. this._outputSurface[j] = [];
  56914. //Iterate over faces for output images
  56915. for (i = 0; i < 6; i++) {
  56916. this._outputSurface[j].length++;
  56917. // Initializes a new array for the output.
  56918. if (this.isFloat) {
  56919. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  56920. }
  56921. else {
  56922. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  56923. }
  56924. }
  56925. //next mip level is half size
  56926. mipLevelSize >>= 1;
  56927. this._numMipLevels++;
  56928. //terminate if mip chain becomes too small
  56929. if (mipLevelSize == 0) {
  56930. this.maxNumMipLevels = j;
  56931. return;
  56932. }
  56933. }
  56934. };
  56935. //--------------------------------------------------------------------------------------
  56936. //Cube map filtering and mip chain generation.
  56937. // the cube map filtereing is specified using a number of parameters:
  56938. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  56939. // indicates the region of the hemisphere to filter over for each tap.
  56940. //
  56941. // Note that the top mip level is also a filtered version of the original input images
  56942. // as well in order to create mip chains for diffuse environment illumination.
  56943. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  56944. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  56945. //
  56946. // Then the mip angle used to genreate the next level of the mip chain from the first level
  56947. // is a_InitialMipAngle
  56948. //
  56949. // The angle for the subsequent levels of the mip chain are specified by their parents
  56950. // filtering angle and a per-level scale and bias
  56951. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  56952. //
  56953. //--------------------------------------------------------------------------------------
  56954. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  56955. // First, take count of the lighting model to modify SpecularPower
  56956. // 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;
  56957. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  56958. //Cone angle start (for generating subsequent mip levels)
  56959. var currentSpecularPower = this.specularPower;
  56960. //Build filter lookup tables based on the source miplevel size
  56961. this.precomputeFilterLookupTables(this.inputSize);
  56962. // Note that we need to filter the first level before generating mipmap
  56963. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  56964. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  56965. // TODO : Write a function to copy and scale the base mipmap in output
  56966. // I am just lazy here and just put a high specular power value, and do some if.
  56967. if (this.excludeBase && (levelIndex == 0)) {
  56968. // 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).
  56969. currentSpecularPower = 100000.0;
  56970. }
  56971. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  56972. var srcCubeImage = this.input;
  56973. var dstCubeImage = this._outputSurface[levelIndex];
  56974. var dstSize = this.outputSize >> levelIndex;
  56975. // Compute required angle.
  56976. var angle = this.getBaseFilterAngle(currentSpecularPower);
  56977. // filter cube surfaces
  56978. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  56979. // fix seams
  56980. if (this.fixup) {
  56981. this.fixupCubeEdges(dstCubeImage, dstSize);
  56982. }
  56983. // Decrease the specular power to generate the mipmap chain
  56984. // TODO : Use another method for Exclude (see first comment at start of the function
  56985. if (this.excludeBase && (levelIndex == 0)) {
  56986. currentSpecularPower = this.specularPower;
  56987. }
  56988. currentSpecularPower *= this.cosinePowerDropPerMip;
  56989. }
  56990. };
  56991. //--------------------------------------------------------------------------------------
  56992. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  56993. // It allow to optimize the texel to access base on the specular power.
  56994. //--------------------------------------------------------------------------------------
  56995. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  56996. // We want to find the alpha such that:
  56997. // cos(alpha)^cosinePower = epsilon
  56998. // That's: acos(epsilon^(1/cosinePower))
  56999. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  57000. var angle = 180.0;
  57001. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  57002. angle *= 180.0 / Math.PI; // Convert to degree
  57003. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  57004. return angle;
  57005. };
  57006. //--------------------------------------------------------------------------------------
  57007. //Builds the following lookup tables prior to filtering:
  57008. // -normalizer cube map
  57009. // -tap weight lookup table
  57010. //
  57011. //--------------------------------------------------------------------------------------
  57012. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  57013. var srcTexelAngle;
  57014. var iCubeFace;
  57015. //clear pre-existing normalizer cube map
  57016. this._normCubeMap = [];
  57017. //Normalized vectors per cubeface and per-texel solid angle
  57018. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  57019. };
  57020. //--------------------------------------------------------------------------------------
  57021. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  57022. //
  57023. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  57024. //
  57025. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  57026. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  57027. // below
  57028. //--------------------------------------------------------------------------------------
  57029. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  57030. var iCubeFace;
  57031. var u;
  57032. var v;
  57033. //iterate over cube faces
  57034. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  57035. //First three channels for norm cube, and last channel for solid angle
  57036. this._normCubeMap.push(new Float32Array(size * size * 4));
  57037. //fast texture walk, build normalizer cube map
  57038. var facesData = this.input[iCubeFace];
  57039. for (v = 0; v < size; v++) {
  57040. for (u = 0; u < size; u++) {
  57041. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  57042. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  57043. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  57044. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  57045. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  57046. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  57047. }
  57048. }
  57049. }
  57050. };
  57051. //--------------------------------------------------------------------------------------
  57052. // Convert cubemap face texel coordinates and face idx to 3D vector
  57053. // note the U and V coords are integer coords and range from 0 to size-1
  57054. // this routine can be used to generate a normalizer cube map
  57055. //--------------------------------------------------------------------------------------
  57056. // SL BEGIN
  57057. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  57058. var nvcU;
  57059. var nvcV;
  57060. var tempVec;
  57061. // Change from original AMD code
  57062. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  57063. // + 0.5f is for texel center addressing
  57064. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  57065. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  57066. // warp fixup
  57067. if (fixup && size > 1) {
  57068. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  57069. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  57070. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  57071. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  57072. }
  57073. // Get current vector
  57074. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  57075. // U contribution
  57076. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  57077. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  57078. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  57079. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  57080. // V contribution and Sum
  57081. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  57082. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  57083. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  57084. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  57085. //add face axis
  57086. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  57087. PMREMGenerator._vectorTemp.x += faceAxis[0];
  57088. PMREMGenerator._vectorTemp.y += faceAxis[1];
  57089. PMREMGenerator._vectorTemp.z += faceAxis[2];
  57090. //normalize vector
  57091. PMREMGenerator._vectorTemp.normalize();
  57092. return PMREMGenerator._vectorTemp;
  57093. };
  57094. //--------------------------------------------------------------------------------------
  57095. // Convert 3D vector to cubemap face texel coordinates and face idx
  57096. // note the U and V coords are integer coords and range from 0 to size-1
  57097. // this routine can be used to generate a normalizer cube map
  57098. //
  57099. // returns face IDX and texel coords
  57100. //--------------------------------------------------------------------------------------
  57101. // SL BEGIN
  57102. /*
  57103. Mapping Texture Coordinates to Cube Map Faces
  57104. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  57105. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  57106. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  57107. map arrangement in Pixar's RenderMan package.
  57108. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  57109. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  57110. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  57111. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  57112. the major axis direction). The target column in the table below explains how the major axis direction
  57113. maps to the 2D image of a particular cube map target.
  57114. major axis
  57115. direction target sc tc ma
  57116. ---------- --------------------------------- --- --- ---
  57117. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  57118. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  57119. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  57120. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  57121. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  57122. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  57123. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  57124. an updated (s,t) is calculated as follows
  57125. s = ( sc/|ma| + 1 ) / 2
  57126. t = ( tc/|ma| + 1 ) / 2
  57127. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  57128. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  57129. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  57130. */
  57131. // Note this method return U and V in range from 0 to size-1
  57132. // SL END
  57133. // Store the information in vector3 for convenience (faceindex, u, v)
  57134. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  57135. var maxCoord;
  57136. var faceIdx;
  57137. //absolute value 3
  57138. var absX = Math.abs(x);
  57139. var absY = Math.abs(y);
  57140. var absZ = Math.abs(z);
  57141. if (absX >= absY && absX >= absZ) {
  57142. maxCoord = absX;
  57143. if (x >= 0) {
  57144. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  57145. }
  57146. else {
  57147. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  57148. }
  57149. }
  57150. else if (absY >= absX && absY >= absZ) {
  57151. maxCoord = absY;
  57152. if (y >= 0) {
  57153. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  57154. }
  57155. else {
  57156. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  57157. }
  57158. }
  57159. else {
  57160. maxCoord = absZ;
  57161. if (z >= 0) {
  57162. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  57163. }
  57164. else {
  57165. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  57166. }
  57167. }
  57168. //divide through by max coord so face vector lies on cube face
  57169. var scale = 1 / maxCoord;
  57170. x *= scale;
  57171. y *= scale;
  57172. z *= scale;
  57173. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  57174. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  57175. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  57176. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  57177. // Modify original AMD code to return value from 0 to Size - 1
  57178. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  57179. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  57180. PMREMGenerator._vectorTemp.x = faceIdx;
  57181. PMREMGenerator._vectorTemp.y = u;
  57182. PMREMGenerator._vectorTemp.z = v;
  57183. return PMREMGenerator._vectorTemp;
  57184. };
  57185. //--------------------------------------------------------------------------------------
  57186. //Original code from Ignacio CastaÒo
  57187. // This formula is from Manne ÷hrstrˆm's thesis.
  57188. // Take two coordiantes in the range [-1, 1] that define a portion of a
  57189. // cube face and return the area of the projection of that portion on the
  57190. // surface of the sphere.
  57191. //--------------------------------------------------------------------------------------
  57192. PMREMGenerator.prototype.areaElement = function (x, y) {
  57193. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  57194. };
  57195. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  57196. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  57197. // (+ 0.5f is for texel center addressing)
  57198. u = (2.0 * (u + 0.5) / size) - 1.0;
  57199. v = (2.0 * (v + 0.5) / size) - 1.0;
  57200. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  57201. var invResolution = 1.0 / size;
  57202. // U and V are the -1..1 texture coordinate on the current face.
  57203. // Get projected area for this texel
  57204. var x0 = u - invResolution;
  57205. var y0 = v - invResolution;
  57206. var x1 = u + invResolution;
  57207. var y1 = v + invResolution;
  57208. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  57209. return solidAngle;
  57210. };
  57211. //--------------------------------------------------------------------------------------
  57212. //The key to the speed of these filtering routines is to quickly define a per-face
  57213. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  57214. // Later these pixels are selectively processed based on their dot products to see if
  57215. // they reside within the filtering cone.
  57216. //
  57217. //This is done by computing the smallest per-texel angle to get a conservative estimate
  57218. // of the number of texels needed to be covered in width and height order to filter the
  57219. // region. the bounding box for the center taps face is defined first, and if the
  57220. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  57221. // defined next
  57222. //--------------------------------------------------------------------------------------
  57223. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  57224. // note that pixels within these regions may be rejected
  57225. // based on the anlge
  57226. var iCubeFace;
  57227. var u;
  57228. var v;
  57229. // bounding box per face to specify region to process
  57230. var filterExtents = [];
  57231. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  57232. filterExtents.push(new CMGBoundinBox());
  57233. }
  57234. // min angle a src texel can cover (in degrees)
  57235. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  57236. // angle about center tap to define filter cone
  57237. // filter angle is 1/2 the cone angle
  57238. var filterAngle = filterConeAngle / 2.0;
  57239. //ensure filter angle is larger than a texel
  57240. if (filterAngle < srcTexelAngle) {
  57241. filterAngle = srcTexelAngle;
  57242. }
  57243. //ensure filter cone is always smaller than the hemisphere
  57244. if (filterAngle > 90.0) {
  57245. filterAngle = 90.0;
  57246. }
  57247. // the maximum number of texels in 1D the filter cone angle will cover
  57248. // used to determine bounding box size for filter extents
  57249. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  57250. // ensure conservative region always covers at least one texel
  57251. if (filterSize < 1) {
  57252. filterSize = 1;
  57253. }
  57254. // dotProdThresh threshold based on cone angle to determine whether or not taps
  57255. // reside within the cone angle
  57256. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  57257. // process required faces
  57258. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  57259. //iterate over dst cube map face texel
  57260. for (v = 0; v < dstSize; v++) {
  57261. for (u = 0; u < dstSize; u++) {
  57262. //get center tap direction
  57263. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  57264. //clear old per-face filter extents
  57265. this.clearFilterExtents(filterExtents);
  57266. //define per-face filter extents
  57267. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  57268. //perform filtering of src faces using filter extents
  57269. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  57270. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  57271. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  57272. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  57273. }
  57274. }
  57275. }
  57276. };
  57277. //--------------------------------------------------------------------------------------
  57278. //Clear filter extents for the 6 cube map faces
  57279. //--------------------------------------------------------------------------------------
  57280. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  57281. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  57282. filterExtents[iCubeFaces].clear();
  57283. }
  57284. };
  57285. //--------------------------------------------------------------------------------------
  57286. //Define per-face bounding box filter extents
  57287. //
  57288. // These define conservative texel regions in each of the faces the filter can possibly
  57289. // process. When the pixels in the regions are actually processed, the dot product
  57290. // between the tap vector and the center tap vector is used to determine the weight of
  57291. // the tap and whether or not the tap is within the cone.
  57292. //
  57293. //--------------------------------------------------------------------------------------
  57294. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  57295. //neighboring face and bleed over amount, and width of BBOX for
  57296. // left, right, top, and bottom edges of this face
  57297. var bleedOverAmount = [0, 0, 0, 0];
  57298. var bleedOverBBoxMin = [0, 0, 0, 0];
  57299. var bleedOverBBoxMax = [0, 0, 0, 0];
  57300. var neighborFace;
  57301. var neighborEdge;
  57302. var oppositeFaceIdx;
  57303. //get face idx, and u, v info from center tap dir
  57304. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  57305. var faceIdx = result.x;
  57306. var u = result.y;
  57307. var v = result.z;
  57308. //define bbox size within face
  57309. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  57310. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  57311. filterExtents[faceIdx].clampMin(0, 0, 0);
  57312. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  57313. //u and v extent in face corresponding to center tap
  57314. var minU = filterExtents[faceIdx].min.x;
  57315. var minV = filterExtents[faceIdx].min.y;
  57316. var maxU = filterExtents[faceIdx].max.x;
  57317. var maxV = filterExtents[faceIdx].max.y;
  57318. //bleed over amounts for face across u=0 edge (left)
  57319. bleedOverAmount[0] = (bboxSize - u);
  57320. bleedOverBBoxMin[0] = minV;
  57321. bleedOverBBoxMax[0] = maxV;
  57322. //bleed over amounts for face across u=1 edge (right)
  57323. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  57324. bleedOverBBoxMin[1] = minV;
  57325. bleedOverBBoxMax[1] = maxV;
  57326. //bleed over to face across v=0 edge (up)
  57327. bleedOverAmount[2] = (bboxSize - v);
  57328. bleedOverBBoxMin[2] = minU;
  57329. bleedOverBBoxMax[2] = maxU;
  57330. //bleed over to face across v=1 edge (down)
  57331. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  57332. bleedOverBBoxMin[3] = minU;
  57333. bleedOverBBoxMax[3] = maxU;
  57334. //compute bleed over regions in neighboring faces
  57335. for (var i = 0; i < 4; i++) {
  57336. if (bleedOverAmount[i] > 0) {
  57337. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  57338. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  57339. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  57340. // be flipped: the cases are
  57341. // if a left edge mates with a left or bottom edge on the neighbor
  57342. // if a top edge mates with a top or right edge on the neighbor
  57343. // if a right edge mates with a right or top edge on the neighbor
  57344. // if a bottom edge mates with a bottom or left edge on the neighbor
  57345. //Seeing as the edges are enumerated as follows
  57346. // left =0
  57347. // right =1
  57348. // top =2
  57349. // bottom =3
  57350. //
  57351. // so if the edge enums are the same, or the sum of the enums == 3,
  57352. // the bbox needs to be flipped
  57353. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  57354. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  57355. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  57356. }
  57357. //The way the bounding box is extended onto the neighboring face
  57358. // depends on which edge of neighboring face abuts with this one
  57359. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  57360. case PMREMGenerator.CP_EDGE_LEFT:
  57361. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  57362. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  57363. break;
  57364. case PMREMGenerator.CP_EDGE_RIGHT:
  57365. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  57366. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  57367. break;
  57368. case PMREMGenerator.CP_EDGE_TOP:
  57369. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  57370. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  57371. break;
  57372. case PMREMGenerator.CP_EDGE_BOTTOM:
  57373. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  57374. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  57375. break;
  57376. }
  57377. //clamp filter extents in non-center tap faces to remain within surface
  57378. filterExtents[neighborFace].clampMin(0, 0, 0);
  57379. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  57380. }
  57381. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  57382. // from the center tap face, then process the opposite face entirely for now.
  57383. //Note that the cases in which this happens, what usually happens is that
  57384. // more than one edge bleeds onto the opposite face, and the bounding box
  57385. // encompasses the entire cube map face.
  57386. if (bleedOverAmount[i] > srcSize) {
  57387. //determine opposite face
  57388. switch (faceIdx) {
  57389. case PMREMGenerator.CP_FACE_X_POS:
  57390. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  57391. break;
  57392. case PMREMGenerator.CP_FACE_X_NEG:
  57393. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  57394. break;
  57395. case PMREMGenerator.CP_FACE_Y_POS:
  57396. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  57397. break;
  57398. case PMREMGenerator.CP_FACE_Y_NEG:
  57399. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  57400. break;
  57401. case PMREMGenerator.CP_FACE_Z_POS:
  57402. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  57403. break;
  57404. case PMREMGenerator.CP_FACE_Z_NEG:
  57405. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  57406. break;
  57407. default:
  57408. break;
  57409. }
  57410. //just encompass entire face for now
  57411. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  57412. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  57413. }
  57414. }
  57415. };
  57416. //--------------------------------------------------------------------------------------
  57417. //ProcessFilterExtents
  57418. // Process bounding box in each cube face
  57419. //
  57420. //--------------------------------------------------------------------------------------
  57421. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  57422. //accumulators are 64-bit floats in order to have the precision needed
  57423. // over a summation of a large number of pixels
  57424. var dstAccum = [0, 0, 0, 0];
  57425. var weightAccum = 0;
  57426. var k = 0;
  57427. var nSrcChannels = this.numChannels;
  57428. // norm cube map and srcCubeMap have same face width
  57429. var faceWidth = srcSize;
  57430. //amount to add to pointer to move to next scanline in images
  57431. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  57432. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  57433. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  57434. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  57435. // iterate over cubefaces
  57436. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  57437. //if bbox is non empty
  57438. if (!filterExtents[iFaceIdx].empty()) {
  57439. var uStart = filterExtents[iFaceIdx].min.x;
  57440. var vStart = filterExtents[iFaceIdx].min.y;
  57441. var uEnd = filterExtents[iFaceIdx].max.x;
  57442. var vEnd = filterExtents[iFaceIdx].max.y;
  57443. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  57444. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  57445. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  57446. for (var v = vStart; v <= vEnd; v++) {
  57447. var normCubeRowWalk = 0;
  57448. var srcCubeRowWalk = 0;
  57449. for (var u = uStart; u <= uEnd; u++) {
  57450. //pointer to direction in cube map associated with texel
  57451. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  57452. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  57453. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  57454. //check dot product to see if texel is within cone
  57455. var tapDotProd = texelVectX * centerTapDir.x +
  57456. texelVectY * centerTapDir.y +
  57457. texelVectZ * centerTapDir.z;
  57458. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  57459. //solid angle stored in 4th channel of normalizer/solid angle cube map
  57460. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  57461. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  57462. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  57463. // so just adding one to specularpower do the trick.
  57464. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  57465. //iterate over channels
  57466. for (k = 0; k < nSrcChannels; k++) {
  57467. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  57468. srcCubeRowWalk++;
  57469. }
  57470. weightAccum += weight; //accumulate weight
  57471. }
  57472. else {
  57473. //step across source pixel
  57474. srcCubeRowWalk += nSrcChannels;
  57475. }
  57476. normCubeRowWalk += 4; // 4 channels per norm cube map.
  57477. }
  57478. startIndexNormCubeMap += normCubePitch;
  57479. startIndexSrcCubeMap += srcCubePitch;
  57480. }
  57481. }
  57482. }
  57483. //divide through by weights if weight is non zero
  57484. if (weightAccum != 0.0) {
  57485. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  57486. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  57487. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  57488. if (this.numChannels > 3) {
  57489. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  57490. }
  57491. }
  57492. else {
  57493. // otherwise sample nearest
  57494. // get face idx and u, v texel coordinate in face
  57495. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  57496. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  57497. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  57498. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  57499. if (this.numChannels > 3) {
  57500. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  57501. }
  57502. }
  57503. return PMREMGenerator._vectorTemp;
  57504. };
  57505. //--------------------------------------------------------------------------------------
  57506. // Fixup cube edges
  57507. //
  57508. // average texels on cube map faces across the edges
  57509. // WARP/BENT Method Only.
  57510. //--------------------------------------------------------------------------------------
  57511. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  57512. var k;
  57513. var j;
  57514. var i;
  57515. var iFace;
  57516. var iCorner = 0;
  57517. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  57518. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  57519. // note that if functionality to filter across the three texels for each corner, then
  57520. //indexed by corner and face idx. the array contains the face the start points belongs to.
  57521. var cornerPtr = [
  57522. [[], [], []],
  57523. [[], [], []],
  57524. [[], [], []],
  57525. [[], [], []],
  57526. [[], [], []],
  57527. [[], [], []],
  57528. [[], [], []],
  57529. [[], [], []]
  57530. ];
  57531. //if there is no fixup, or fixup width = 0, do nothing
  57532. if (cubeMapSize < 1) {
  57533. return;
  57534. }
  57535. //special case 1x1 cubemap, average face colors
  57536. if (cubeMapSize == 1) {
  57537. //iterate over channels
  57538. for (k = 0; k < this.numChannels; k++) {
  57539. var accum = 0.0;
  57540. //iterate over faces to accumulate face colors
  57541. for (iFace = 0; iFace < 6; iFace++) {
  57542. accum += cubeMap[iFace][k];
  57543. }
  57544. //compute average over 6 face colors
  57545. accum /= 6.0;
  57546. //iterate over faces to distribute face colors
  57547. for (iFace = 0; iFace < 6; iFace++) {
  57548. cubeMap[iFace][k] = accum;
  57549. }
  57550. }
  57551. return;
  57552. }
  57553. //iterate over faces to collect list of corner texel pointers
  57554. for (iFace = 0; iFace < 6; iFace++) {
  57555. //the 4 corner pointers for this face
  57556. faceCornerStartIndicies[0] = [iFace, 0];
  57557. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  57558. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  57559. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  57560. //iterate over face corners to collect cube corner pointers
  57561. for (iCorner = 0; iCorner < 4; iCorner++) {
  57562. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  57563. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  57564. cornerNumPtrs[corner]++;
  57565. }
  57566. }
  57567. //iterate over corners to average across corner tap values
  57568. for (iCorner = 0; iCorner < 8; iCorner++) {
  57569. for (k = 0; k < this.numChannels; k++) {
  57570. var cornerTapAccum = 0.0;
  57571. //iterate over corner texels and average results
  57572. for (i = 0; i < 3; i++) {
  57573. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  57574. }
  57575. //divide by 3 to compute average of corner tap values
  57576. cornerTapAccum *= (1.0 / 3.0);
  57577. //iterate over corner texels and average results
  57578. for (i = 0; i < 3; i++) {
  57579. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  57580. }
  57581. }
  57582. }
  57583. //iterate over the twelve edges of the cube to average across edges
  57584. for (i = 0; i < 12; i++) {
  57585. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  57586. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  57587. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  57588. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  57589. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  57590. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  57591. var edgeWalk = 0;
  57592. var neighborEdgeWalk = 0;
  57593. //Determine walking pointers based on edge type
  57594. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  57595. switch (edge) {
  57596. case PMREMGenerator.CP_EDGE_LEFT:
  57597. // no change to faceEdgeStartPtr
  57598. edgeWalk = this.numChannels * cubeMapSize;
  57599. break;
  57600. case PMREMGenerator.CP_EDGE_RIGHT:
  57601. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57602. edgeWalk = this.numChannels * cubeMapSize;
  57603. break;
  57604. case PMREMGenerator.CP_EDGE_TOP:
  57605. // no change to faceEdgeStartPtr
  57606. edgeWalk = this.numChannels;
  57607. break;
  57608. case PMREMGenerator.CP_EDGE_BOTTOM:
  57609. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  57610. edgeWalk = this.numChannels;
  57611. break;
  57612. }
  57613. //For certain types of edge abutments, the neighbor edge walk needs to
  57614. // be flipped: the cases are
  57615. // if a left edge mates with a left or bottom edge on the neighbor
  57616. // if a top edge mates with a top or right edge on the neighbor
  57617. // if a right edge mates with a right or top edge on the neighbor
  57618. // if a bottom edge mates with a bottom or left edge on the neighbor
  57619. //Seeing as the edges are enumerated as follows
  57620. // left =0
  57621. // right =1
  57622. // top =2
  57623. // bottom =3
  57624. //
  57625. //If the edge enums are the same, or the sum of the enums == 3,
  57626. // the neighbor edge walk needs to be flipped
  57627. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  57628. switch (neighborEdge) {
  57629. case PMREMGenerator.CP_EDGE_LEFT:
  57630. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  57631. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  57632. break;
  57633. case PMREMGenerator.CP_EDGE_RIGHT:
  57634. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  57635. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  57636. break;
  57637. case PMREMGenerator.CP_EDGE_TOP:
  57638. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57639. neighborEdgeWalk = -this.numChannels;
  57640. break;
  57641. case PMREMGenerator.CP_EDGE_BOTTOM:
  57642. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  57643. neighborEdgeWalk = -this.numChannels;
  57644. break;
  57645. }
  57646. }
  57647. else {
  57648. //swapped direction neighbor edge walk
  57649. switch (neighborEdge) {
  57650. case PMREMGenerator.CP_EDGE_LEFT:
  57651. //no change to neighborEdgeStartPtr for this case since it points
  57652. // to the upper left corner already
  57653. neighborEdgeWalk = this.numChannels * cubeMapSize;
  57654. break;
  57655. case PMREMGenerator.CP_EDGE_RIGHT:
  57656. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57657. neighborEdgeWalk = this.numChannels * cubeMapSize;
  57658. break;
  57659. case PMREMGenerator.CP_EDGE_TOP:
  57660. //no change to neighborEdgeStartPtr for this case since it points
  57661. // to the upper left corner already
  57662. neighborEdgeWalk = this.numChannels;
  57663. break;
  57664. case PMREMGenerator.CP_EDGE_BOTTOM:
  57665. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  57666. neighborEdgeWalk = this.numChannels;
  57667. break;
  57668. }
  57669. }
  57670. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  57671. //nearby neighborhood
  57672. //step ahead one texel on edge
  57673. edgeStartIndex += edgeWalk;
  57674. neighborEdgeStartIndex += neighborEdgeWalk;
  57675. // note that this loop does not process the corner texels, since they have already been
  57676. // averaged across faces across earlier
  57677. for (j = 1; j < (cubeMapSize - 1); j++) {
  57678. //for each set of taps along edge, average them
  57679. // and rewrite the results into the edges
  57680. for (k = 0; k < this.numChannels; k++) {
  57681. var edgeTap = cubeMap[face][edgeStartIndex + k];
  57682. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  57683. //compute average of tap intensity values
  57684. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  57685. //propagate average of taps to edge taps
  57686. cubeMap[face][edgeStartIndex + k] = avgTap;
  57687. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  57688. }
  57689. edgeStartIndex += edgeWalk;
  57690. neighborEdgeStartIndex += neighborEdgeWalk;
  57691. }
  57692. }
  57693. };
  57694. return PMREMGenerator;
  57695. }());
  57696. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  57697. PMREMGenerator.CP_UDIR = 0;
  57698. PMREMGenerator.CP_VDIR = 1;
  57699. PMREMGenerator.CP_FACEAXIS = 2;
  57700. //used to index cube faces
  57701. PMREMGenerator.CP_FACE_X_POS = 0;
  57702. PMREMGenerator.CP_FACE_X_NEG = 1;
  57703. PMREMGenerator.CP_FACE_Y_POS = 2;
  57704. PMREMGenerator.CP_FACE_Y_NEG = 3;
  57705. PMREMGenerator.CP_FACE_Z_POS = 4;
  57706. PMREMGenerator.CP_FACE_Z_NEG = 5;
  57707. //used to index image edges
  57708. // NOTE.. the actual number corresponding to the edge is important
  57709. // do not change these, or the code will break
  57710. //
  57711. // CP_EDGE_LEFT is u = 0
  57712. // CP_EDGE_RIGHT is u = width-1
  57713. // CP_EDGE_TOP is v = 0
  57714. // CP_EDGE_BOTTOM is v = height-1
  57715. PMREMGenerator.CP_EDGE_LEFT = 0;
  57716. PMREMGenerator.CP_EDGE_RIGHT = 1;
  57717. PMREMGenerator.CP_EDGE_TOP = 2;
  57718. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  57719. //corners of CUBE map (P or N specifys if it corresponds to the
  57720. // positive or negative direction each of X, Y, and Z
  57721. PMREMGenerator.CP_CORNER_NNN = 0;
  57722. PMREMGenerator.CP_CORNER_NNP = 1;
  57723. PMREMGenerator.CP_CORNER_NPN = 2;
  57724. PMREMGenerator.CP_CORNER_NPP = 3;
  57725. PMREMGenerator.CP_CORNER_PNN = 4;
  57726. PMREMGenerator.CP_CORNER_PNP = 5;
  57727. PMREMGenerator.CP_CORNER_PPN = 6;
  57728. PMREMGenerator.CP_CORNER_PPP = 7;
  57729. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  57730. //3x2 matrices that map cube map indexing vectors in 3d
  57731. // (after face selection and divide through by the
  57732. // _ABSOLUTE VALUE_ of the max coord)
  57733. // into NVC space
  57734. //Note this currently assumes the D3D cube face ordering and orientation
  57735. PMREMGenerator._sgFace2DMapping = [
  57736. //XPOS face
  57737. [[0, 0, -1],
  57738. [0, -1, 0],
  57739. [1, 0, 0]],
  57740. //XNEG face
  57741. [[0, 0, 1],
  57742. [0, -1, 0],
  57743. [-1, 0, 0]],
  57744. //YPOS face
  57745. [[1, 0, 0],
  57746. [0, 0, 1],
  57747. [0, 1, 0]],
  57748. //YNEG face
  57749. [[1, 0, 0],
  57750. [0, 0, -1],
  57751. [0, -1, 0]],
  57752. //ZPOS face
  57753. [[1, 0, 0],
  57754. [0, -1, 0],
  57755. [0, 0, 1]],
  57756. //ZNEG face
  57757. [[-1, 0, 0],
  57758. [0, -1, 0],
  57759. [0, 0, -1]],
  57760. ];
  57761. //------------------------------------------------------------------------------
  57762. // D3D cube map face specification
  57763. // mapping from 3D x,y,z cube map lookup coordinates
  57764. // to 2D within face u,v coordinates
  57765. //
  57766. // --------------------> U direction
  57767. // | (within-face texture space)
  57768. // | _____
  57769. // | | |
  57770. // | | +Y |
  57771. // | _____|_____|_____ _____
  57772. // | | | | | |
  57773. // | | -X | +Z | +X | -Z |
  57774. // | |_____|_____|_____|_____|
  57775. // | | |
  57776. // | | -Y |
  57777. // | |_____|
  57778. // |
  57779. // v V direction
  57780. // (within-face texture space)
  57781. //------------------------------------------------------------------------------
  57782. //Information about neighbors and how texture coorrdinates change across faces
  57783. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  57784. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  57785. //Note this currently assumes the D3D cube face ordering and orientation
  57786. PMREMGenerator._sgCubeNgh = [
  57787. //XPOS face
  57788. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57789. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57790. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57791. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  57792. //XNEG face
  57793. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57794. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  57795. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  57796. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  57797. //YPOS face
  57798. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  57799. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  57800. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  57801. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  57802. //YNEG face
  57803. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  57804. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57805. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57806. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  57807. //ZPOS face
  57808. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57809. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  57810. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57811. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  57812. //ZNEG face
  57813. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57814. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57815. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  57816. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  57817. ];
  57818. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  57819. // this table is used to average over the edges.
  57820. PMREMGenerator._sgCubeEdgeList = [
  57821. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  57822. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57823. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  57824. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57825. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57826. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57827. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  57828. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  57829. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  57830. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57831. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  57832. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  57833. ];
  57834. //Information about which of the 8 cube corners are correspond to the
  57835. // the 4 corners in each cube face
  57836. // the order is upper left, upper right, lower left, lower right
  57837. PMREMGenerator._sgCubeCornerList = [
  57838. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  57839. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  57840. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  57841. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  57842. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  57843. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  57844. ];
  57845. Internals.PMREMGenerator = PMREMGenerator;
  57846. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57847. })(BABYLON || (BABYLON = {}));
  57848. //# sourceMappingURL=babylon.tools.pmremGenerator.js.map
  57849. var BABYLON;
  57850. (function (BABYLON) {
  57851. /**
  57852. * This represents a texture coming from an HDR input.
  57853. *
  57854. * The only supported format is currently panorama picture stored in RGBE format.
  57855. * Example of such files can be found on HDRLib: http://hdrlib.com/
  57856. */
  57857. var HDRCubeTexture = (function (_super) {
  57858. __extends(HDRCubeTexture, _super);
  57859. /**
  57860. * Instantiates an HDRTexture from the following parameters.
  57861. *
  57862. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  57863. * @param scene The scene the texture will be used in
  57864. * @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.
  57865. * @param noMipmap Forces to not generate the mipmap if true
  57866. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  57867. * @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)
  57868. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  57869. */
  57870. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  57871. if (noMipmap === void 0) { noMipmap = false; }
  57872. if (generateHarmonics === void 0) { generateHarmonics = true; }
  57873. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  57874. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  57875. if (onLoad === void 0) { onLoad = null; }
  57876. if (onError === void 0) { onError = null; }
  57877. var _this = _super.call(this, scene) || this;
  57878. _this._useInGammaSpace = false;
  57879. _this._generateHarmonics = true;
  57880. _this._isBABYLONPreprocessed = false;
  57881. _this._onLoad = null;
  57882. _this._onError = null;
  57883. /**
  57884. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  57885. */
  57886. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57887. /**
  57888. * The spherical polynomial data extracted from the texture.
  57889. */
  57890. _this.sphericalPolynomial = null;
  57891. /**
  57892. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  57893. * This is usefull at run time to apply the good shader.
  57894. */
  57895. _this.isPMREM = false;
  57896. if (!url) {
  57897. return _this;
  57898. }
  57899. _this.name = url;
  57900. _this.url = url;
  57901. _this.hasAlpha = false;
  57902. _this.isCube = true;
  57903. _this._textureMatrix = BABYLON.Matrix.Identity();
  57904. _this._onLoad = onLoad;
  57905. _this._onError = onError;
  57906. if (size) {
  57907. _this._isBABYLONPreprocessed = false;
  57908. _this._noMipmap = noMipmap;
  57909. _this._size = size;
  57910. _this._useInGammaSpace = useInGammaSpace;
  57911. _this._usePMREMGenerator = usePMREMGenerator &&
  57912. scene.getEngine().getCaps().textureLOD &&
  57913. _this.getScene().getEngine().getCaps().textureFloat &&
  57914. !_this._useInGammaSpace;
  57915. }
  57916. else {
  57917. _this._isBABYLONPreprocessed = true;
  57918. _this._noMipmap = false;
  57919. _this._useInGammaSpace = false;
  57920. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  57921. _this.getScene().getEngine().getCaps().textureFloat &&
  57922. !_this._useInGammaSpace;
  57923. }
  57924. _this.isPMREM = _this._usePMREMGenerator;
  57925. _this._texture = _this._getFromCache(url, _this._noMipmap);
  57926. if (!_this._texture) {
  57927. if (!scene.useDelayedTextureLoading) {
  57928. _this.loadTexture();
  57929. }
  57930. else {
  57931. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57932. }
  57933. }
  57934. return _this;
  57935. }
  57936. /**
  57937. * Occurs when the file is a preprocessed .babylon.hdr file.
  57938. */
  57939. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  57940. var _this = this;
  57941. var mipLevels = 0;
  57942. var floatArrayView = null;
  57943. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  57944. var mips = [];
  57945. var startIndex = 30;
  57946. for (var level = 0; level < mipLevels; level++) {
  57947. mips.push([]);
  57948. // Fill each pixel of the mip level.
  57949. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  57950. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57951. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  57952. mips[level].push(faceData);
  57953. startIndex += faceSize;
  57954. }
  57955. }
  57956. return mips;
  57957. } : null;
  57958. var callback = function (buffer) {
  57959. // Create Native Array Views
  57960. var intArrayView = new Int32Array(buffer);
  57961. floatArrayView = new Float32Array(buffer);
  57962. // Fill header.
  57963. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  57964. _this._size = intArrayView[1]; // CubeMap max mip face size.
  57965. // Update Texture Information.
  57966. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  57967. // Fill polynomial information.
  57968. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  57969. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  57970. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  57971. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  57972. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  57973. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  57974. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  57975. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  57976. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  57977. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  57978. // Fill pixel data.
  57979. mipLevels = intArrayView[29]; // Number of mip levels.
  57980. var startIndex = 30;
  57981. var data = [];
  57982. var faceSize = Math.pow(_this._size, 2) * 3;
  57983. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57984. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  57985. startIndex += faceSize;
  57986. }
  57987. var results = [];
  57988. var byteArray = null;
  57989. // Push each faces.
  57990. for (var k = 0; k < 6; k++) {
  57991. var dataFace = null;
  57992. // If special cases.
  57993. if (!mipmapGenerator) {
  57994. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  57995. dataFace = data[j];
  57996. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57997. // 3 channels of 1 bytes per pixel in bytes.
  57998. var byteBuffer = new ArrayBuffer(faceSize);
  57999. byteArray = new Uint8Array(byteBuffer);
  58000. }
  58001. for (var i = 0; i < _this._size * _this._size; i++) {
  58002. // Put in gamma space if requested.
  58003. if (_this._useInGammaSpace) {
  58004. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  58005. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  58006. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  58007. }
  58008. // Convert to int texture for fallback.
  58009. if (byteArray) {
  58010. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  58011. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  58012. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  58013. // May use luminance instead if the result is not accurate.
  58014. var max = Math.max(Math.max(r, g), b);
  58015. if (max > 255) {
  58016. var scale = 255 / max;
  58017. r *= scale;
  58018. g *= scale;
  58019. b *= scale;
  58020. }
  58021. byteArray[(i * 3) + 0] = r;
  58022. byteArray[(i * 3) + 1] = g;
  58023. byteArray[(i * 3) + 2] = b;
  58024. }
  58025. }
  58026. }
  58027. else {
  58028. dataFace = data[k];
  58029. }
  58030. // Fill the array accordingly.
  58031. if (byteArray) {
  58032. results.push(byteArray);
  58033. }
  58034. else {
  58035. results.push(dataFace);
  58036. }
  58037. }
  58038. return results;
  58039. };
  58040. 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);
  58041. };
  58042. /**
  58043. * Occurs when the file is raw .hdr file.
  58044. */
  58045. HDRCubeTexture.prototype.loadHDRTexture = function () {
  58046. var _this = this;
  58047. var callback = function (buffer) {
  58048. // Extract the raw linear data.
  58049. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  58050. // Generate harmonics if needed.
  58051. if (_this._generateHarmonics) {
  58052. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  58053. }
  58054. var results = [];
  58055. var byteArray = null;
  58056. // Push each faces.
  58057. for (var j = 0; j < 6; j++) {
  58058. // Create uintarray fallback.
  58059. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  58060. // 3 channels of 1 bytes per pixel in bytes.
  58061. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  58062. byteArray = new Uint8Array(byteBuffer);
  58063. }
  58064. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  58065. // If special cases.
  58066. if (_this._useInGammaSpace || byteArray) {
  58067. for (var i = 0; i < _this._size * _this._size; i++) {
  58068. // Put in gamma space if requested.
  58069. if (_this._useInGammaSpace) {
  58070. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  58071. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  58072. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  58073. }
  58074. // Convert to int texture for fallback.
  58075. if (byteArray) {
  58076. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  58077. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  58078. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  58079. // May use luminance instead if the result is not accurate.
  58080. var max = Math.max(Math.max(r, g), b);
  58081. if (max > 255) {
  58082. var scale = 255 / max;
  58083. r *= scale;
  58084. g *= scale;
  58085. b *= scale;
  58086. }
  58087. byteArray[(i * 3) + 0] = r;
  58088. byteArray[(i * 3) + 1] = g;
  58089. byteArray[(i * 3) + 2] = b;
  58090. }
  58091. }
  58092. }
  58093. if (byteArray) {
  58094. results.push(byteArray);
  58095. }
  58096. else {
  58097. results.push(dataFace);
  58098. }
  58099. }
  58100. return results;
  58101. };
  58102. var mipmapGenerator = null;
  58103. if (!this._noMipmap &&
  58104. this._usePMREMGenerator) {
  58105. mipmapGenerator = function (data) {
  58106. // Custom setup of the generator matching with the PBR shader values.
  58107. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  58108. return generator.filterCubeMap();
  58109. };
  58110. }
  58111. 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);
  58112. };
  58113. /**
  58114. * Starts the loading process of the texture.
  58115. */
  58116. HDRCubeTexture.prototype.loadTexture = function () {
  58117. if (this._isBABYLONPreprocessed) {
  58118. this.loadBabylonTexture();
  58119. }
  58120. else {
  58121. this.loadHDRTexture();
  58122. }
  58123. };
  58124. HDRCubeTexture.prototype.clone = function () {
  58125. var size = this._isBABYLONPreprocessed ? null : this._size;
  58126. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  58127. // Base texture
  58128. newTexture.level = this.level;
  58129. newTexture.wrapU = this.wrapU;
  58130. newTexture.wrapV = this.wrapV;
  58131. newTexture.coordinatesIndex = this.coordinatesIndex;
  58132. newTexture.coordinatesMode = this.coordinatesMode;
  58133. return newTexture;
  58134. };
  58135. // Methods
  58136. HDRCubeTexture.prototype.delayLoad = function () {
  58137. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58138. return;
  58139. }
  58140. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58141. this._texture = this._getFromCache(this.url, this._noMipmap);
  58142. if (!this._texture) {
  58143. this.loadTexture();
  58144. }
  58145. };
  58146. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  58147. return this._textureMatrix;
  58148. };
  58149. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58150. var texture = null;
  58151. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  58152. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  58153. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  58154. texture.name = parsedTexture.name;
  58155. texture.hasAlpha = parsedTexture.hasAlpha;
  58156. texture.level = parsedTexture.level;
  58157. texture.coordinatesMode = parsedTexture.coordinatesMode;
  58158. }
  58159. return texture;
  58160. };
  58161. HDRCubeTexture.prototype.serialize = function () {
  58162. if (!this.name) {
  58163. return null;
  58164. }
  58165. var serializationObject = {};
  58166. serializationObject.name = this.name;
  58167. serializationObject.hasAlpha = this.hasAlpha;
  58168. serializationObject.isCube = true;
  58169. serializationObject.level = this.level;
  58170. serializationObject.size = this._size;
  58171. serializationObject.coordinatesMode = this.coordinatesMode;
  58172. serializationObject.useInGammaSpace = this._useInGammaSpace;
  58173. serializationObject.generateHarmonics = this._generateHarmonics;
  58174. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  58175. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  58176. serializationObject.customType = "BABYLON.HDRCubeTexture";
  58177. serializationObject.noMipmap = this._noMipmap;
  58178. return serializationObject;
  58179. };
  58180. /**
  58181. * Saves as a file the data contained in the texture in a binary format.
  58182. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  58183. * as the spherical used in the lighting.
  58184. * @param url The HDR file url.
  58185. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  58186. * @param onError Method called if any error happens during download.
  58187. * @return The packed binary data.
  58188. */
  58189. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  58190. if (onError === void 0) { onError = null; }
  58191. var callback = function (buffer) {
  58192. var data = new Blob([buffer], { type: 'application/octet-stream' });
  58193. // Returns a URL you can use as a href.
  58194. var objUrl = window.URL.createObjectURL(data);
  58195. // Simulates a link to it and click to dowload.
  58196. var a = document.createElement("a");
  58197. document.body.appendChild(a);
  58198. a.style.display = "none";
  58199. a.href = objUrl;
  58200. a.download = "envmap.babylon.hdr";
  58201. a.click();
  58202. };
  58203. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  58204. };
  58205. /**
  58206. * Serializes the data contained in the texture in a binary format.
  58207. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  58208. * as the spherical used in the lighting.
  58209. * @param url The HDR file url.
  58210. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  58211. * @param onError Method called if any error happens during download.
  58212. * @return The packed binary data.
  58213. */
  58214. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  58215. if (onError === void 0) { onError = null; }
  58216. // Needs the url tho create the texture.
  58217. if (!url) {
  58218. return null;
  58219. }
  58220. // Check Power of two size.
  58221. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  58222. return null;
  58223. }
  58224. var getDataCallback = function (dataBuffer) {
  58225. // Extract the raw linear data.
  58226. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  58227. // Generate harmonics if needed.
  58228. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  58229. // Generate seamless faces
  58230. var mipGeneratorArray = [];
  58231. // Data are known to be in +X +Y +Z -X -Y -Z
  58232. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  58233. mipGeneratorArray.push(cubeData.right); // +X
  58234. mipGeneratorArray.push(cubeData.left); // -X
  58235. mipGeneratorArray.push(cubeData.up); // +Y
  58236. mipGeneratorArray.push(cubeData.down); // -Y
  58237. mipGeneratorArray.push(cubeData.front); // +Z
  58238. mipGeneratorArray.push(cubeData.back); // -Z
  58239. // Custom setup of the generator matching with the PBR shader values.
  58240. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  58241. var mippedData = generator.filterCubeMap();
  58242. // Compute required byte length.
  58243. var byteLength = 1 * 4; // Raw Data Version int32.
  58244. byteLength += 4; // CubeMap max mip face size int32.
  58245. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  58246. // Add data size.
  58247. byteLength += 4; // Number of mip levels int32.
  58248. for (var level = 0; level < mippedData.length; level++) {
  58249. var mipSize = size >> level;
  58250. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  58251. }
  58252. // Prepare binary structure.
  58253. var buffer = new ArrayBuffer(byteLength);
  58254. var intArrayView = new Int32Array(buffer);
  58255. var floatArrayView = new Float32Array(buffer);
  58256. // Fill header.
  58257. intArrayView[0] = 1; // Version 1.
  58258. intArrayView[1] = size; // CubeMap max mip face size.
  58259. // Fill polynomial information.
  58260. sphericalPolynomial.x.toArray(floatArrayView, 2);
  58261. sphericalPolynomial.y.toArray(floatArrayView, 5);
  58262. sphericalPolynomial.z.toArray(floatArrayView, 8);
  58263. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  58264. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  58265. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  58266. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  58267. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  58268. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  58269. // Fill pixel data.
  58270. intArrayView[29] = mippedData.length; // Number of mip levels.
  58271. var startIndex = 30;
  58272. for (var level = 0; level < mippedData.length; level++) {
  58273. // Fill each pixel of the mip level.
  58274. var faceSize = Math.pow(size >> level, 2) * 3;
  58275. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58276. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  58277. startIndex += faceSize;
  58278. }
  58279. }
  58280. // Callback.
  58281. callback(buffer);
  58282. };
  58283. // Download and process.
  58284. BABYLON.Tools.LoadFile(url, function (data) {
  58285. getDataCallback(data);
  58286. }, null, null, true, onError);
  58287. };
  58288. return HDRCubeTexture;
  58289. }(BABYLON.BaseTexture));
  58290. HDRCubeTexture._facesMapping = [
  58291. "right",
  58292. "up",
  58293. "front",
  58294. "left",
  58295. "down",
  58296. "back"
  58297. ];
  58298. BABYLON.HDRCubeTexture = HDRCubeTexture;
  58299. })(BABYLON || (BABYLON = {}));
  58300. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  58301. var BABYLON;
  58302. (function (BABYLON) {
  58303. var Debug;
  58304. (function (Debug) {
  58305. /**
  58306. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  58307. */
  58308. var SkeletonViewer = (function () {
  58309. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  58310. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  58311. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  58312. this.skeleton = skeleton;
  58313. this.mesh = mesh;
  58314. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  58315. this.renderingGroupId = renderingGroupId;
  58316. this.color = BABYLON.Color3.White();
  58317. this._debugLines = [];
  58318. this._isEnabled = false;
  58319. this._scene = scene;
  58320. this.update();
  58321. this._renderFunction = this.update.bind(this);
  58322. }
  58323. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  58324. get: function () {
  58325. return this._isEnabled;
  58326. },
  58327. set: function (value) {
  58328. if (this._isEnabled === value) {
  58329. return;
  58330. }
  58331. this._isEnabled = value;
  58332. if (value) {
  58333. this._scene.registerBeforeRender(this._renderFunction);
  58334. }
  58335. else {
  58336. this._scene.unregisterBeforeRender(this._renderFunction);
  58337. }
  58338. },
  58339. enumerable: true,
  58340. configurable: true
  58341. });
  58342. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  58343. if (x === void 0) { x = 0; }
  58344. if (y === void 0) { y = 0; }
  58345. if (z === void 0) { z = 0; }
  58346. var tmat = BABYLON.Tmp.Matrix[0];
  58347. var parentBone = bone.getParent();
  58348. tmat.copyFrom(bone.getLocalMatrix());
  58349. if (x !== 0 || y !== 0 || z !== 0) {
  58350. var tmat2 = BABYLON.Tmp.Matrix[1];
  58351. BABYLON.Matrix.IdentityToRef(tmat2);
  58352. tmat2.m[12] = x;
  58353. tmat2.m[13] = y;
  58354. tmat2.m[14] = z;
  58355. tmat2.multiplyToRef(tmat, tmat);
  58356. }
  58357. if (parentBone) {
  58358. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  58359. }
  58360. tmat.multiplyToRef(meshMat, tmat);
  58361. position.x = tmat.m[12];
  58362. position.y = tmat.m[13];
  58363. position.z = tmat.m[14];
  58364. };
  58365. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  58366. var len = bones.length;
  58367. for (var i = 0; i < len; i++) {
  58368. var bone = bones[i];
  58369. var points = this._debugLines[i];
  58370. if (!points) {
  58371. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58372. this._debugLines[i] = points;
  58373. }
  58374. this._getBonePosition(points[0], bone, meshMat);
  58375. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  58376. }
  58377. };
  58378. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  58379. var len = bones.length;
  58380. var boneNum = 0;
  58381. for (var i = len - 1; i >= 0; i--) {
  58382. var childBone = bones[i];
  58383. var parentBone = childBone.getParent();
  58384. if (!parentBone) {
  58385. continue;
  58386. }
  58387. var points = this._debugLines[boneNum];
  58388. if (!points) {
  58389. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58390. this._debugLines[boneNum] = points;
  58391. }
  58392. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  58393. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  58394. boneNum++;
  58395. }
  58396. };
  58397. SkeletonViewer.prototype.update = function () {
  58398. if (this.autoUpdateBonesMatrices) {
  58399. this.skeleton.computeAbsoluteTransforms();
  58400. }
  58401. if (this.skeleton.bones[0].length === undefined) {
  58402. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58403. }
  58404. else {
  58405. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58406. }
  58407. if (!this._debugMesh) {
  58408. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  58409. this._debugMesh.renderingGroupId = this.renderingGroupId;
  58410. }
  58411. else {
  58412. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  58413. }
  58414. this._debugMesh.color = this.color;
  58415. };
  58416. SkeletonViewer.prototype.dispose = function () {
  58417. if (this._debugMesh) {
  58418. this.isEnabled = false;
  58419. this._debugMesh.dispose();
  58420. this._debugMesh = null;
  58421. }
  58422. };
  58423. return SkeletonViewer;
  58424. }());
  58425. Debug.SkeletonViewer = SkeletonViewer;
  58426. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58427. })(BABYLON || (BABYLON = {}));
  58428. //# sourceMappingURL=babylon.skeletonViewer.js.map
  58429. var BABYLON;
  58430. (function (BABYLON) {
  58431. var Debug;
  58432. (function (Debug) {
  58433. var AxesViewer = (function () {
  58434. function AxesViewer(scene, scaleLines) {
  58435. if (scaleLines === void 0) { scaleLines = 1; }
  58436. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58437. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58438. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58439. this.scaleLines = 1;
  58440. this.scaleLines = scaleLines;
  58441. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  58442. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  58443. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  58444. this._xmesh.renderingGroupId = 2;
  58445. this._ymesh.renderingGroupId = 2;
  58446. this._zmesh.renderingGroupId = 2;
  58447. this._xmesh.material.checkReadyOnlyOnce = true;
  58448. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  58449. this._ymesh.material.checkReadyOnlyOnce = true;
  58450. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  58451. this._zmesh.material.checkReadyOnlyOnce = true;
  58452. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  58453. this.scene = scene;
  58454. }
  58455. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  58456. var scaleLines = this.scaleLines;
  58457. var point1 = this._xline[0];
  58458. var point2 = this._xline[1];
  58459. point1.x = position.x;
  58460. point1.y = position.y;
  58461. point1.z = position.z;
  58462. point2.x = point1.x + xaxis.x * scaleLines;
  58463. point2.y = point1.y + xaxis.y * scaleLines;
  58464. point2.z = point1.z + xaxis.z * scaleLines;
  58465. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  58466. point1 = this._yline[0];
  58467. point2 = this._yline[1];
  58468. point1.x = position.x;
  58469. point1.y = position.y;
  58470. point1.z = position.z;
  58471. point2.x = point1.x + yaxis.x * scaleLines;
  58472. point2.y = point1.y + yaxis.y * scaleLines;
  58473. point2.z = point1.z + yaxis.z * scaleLines;
  58474. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  58475. point1 = this._zline[0];
  58476. point2 = this._zline[1];
  58477. point1.x = position.x;
  58478. point1.y = position.y;
  58479. point1.z = position.z;
  58480. point2.x = point1.x + zaxis.x * scaleLines;
  58481. point2.y = point1.y + zaxis.y * scaleLines;
  58482. point2.z = point1.z + zaxis.z * scaleLines;
  58483. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  58484. };
  58485. AxesViewer.prototype.dispose = function () {
  58486. if (this._xmesh) {
  58487. this._xmesh.dispose();
  58488. this._ymesh.dispose();
  58489. this._zmesh.dispose();
  58490. this._xmesh = null;
  58491. this._ymesh = null;
  58492. this._zmesh = null;
  58493. this._xline = null;
  58494. this._yline = null;
  58495. this._zline = null;
  58496. this.scene = null;
  58497. }
  58498. };
  58499. return AxesViewer;
  58500. }());
  58501. Debug.AxesViewer = AxesViewer;
  58502. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58503. })(BABYLON || (BABYLON = {}));
  58504. //# sourceMappingURL=babylon.axesViewer.js.map
  58505. var BABYLON;
  58506. (function (BABYLON) {
  58507. var Debug;
  58508. (function (Debug) {
  58509. var BoneAxesViewer = (function (_super) {
  58510. __extends(BoneAxesViewer, _super);
  58511. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  58512. if (scaleLines === void 0) { scaleLines = 1; }
  58513. var _this = _super.call(this, scene, scaleLines) || this;
  58514. _this.pos = BABYLON.Vector3.Zero();
  58515. _this.xaxis = BABYLON.Vector3.Zero();
  58516. _this.yaxis = BABYLON.Vector3.Zero();
  58517. _this.zaxis = BABYLON.Vector3.Zero();
  58518. _this.mesh = mesh;
  58519. _this.bone = bone;
  58520. return _this;
  58521. }
  58522. BoneAxesViewer.prototype.update = function () {
  58523. var bone = this.bone;
  58524. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  58525. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  58526. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  58527. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  58528. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  58529. };
  58530. BoneAxesViewer.prototype.dispose = function () {
  58531. if (this.pos) {
  58532. this.pos = null;
  58533. this.xaxis = null;
  58534. this.yaxis = null;
  58535. this.zaxis = null;
  58536. this.mesh = null;
  58537. this.bone = null;
  58538. _super.prototype.dispose.call(this);
  58539. }
  58540. };
  58541. return BoneAxesViewer;
  58542. }(Debug.AxesViewer));
  58543. Debug.BoneAxesViewer = BoneAxesViewer;
  58544. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58545. })(BABYLON || (BABYLON = {}));
  58546. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  58547. var BABYLON;
  58548. (function (BABYLON) {
  58549. /**
  58550. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  58551. * It can help converting any input color in a desired output one. This can then be used to create effects
  58552. * from sepia, black and white to sixties or futuristic rendering...
  58553. *
  58554. * The only supported format is currently 3dl.
  58555. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  58556. */
  58557. var ColorGradingTexture = (function (_super) {
  58558. __extends(ColorGradingTexture, _super);
  58559. /**
  58560. * Instantiates a ColorGradingTexture from the following parameters.
  58561. *
  58562. * @param url The location of the color gradind data (currently only supporting 3dl)
  58563. * @param scene The scene the texture will be used in
  58564. */
  58565. function ColorGradingTexture(url, scene) {
  58566. var _this = _super.call(this, scene) || this;
  58567. if (!url) {
  58568. return _this;
  58569. }
  58570. _this._textureMatrix = BABYLON.Matrix.Identity();
  58571. _this.name = url;
  58572. _this.url = url;
  58573. _this.hasAlpha = false;
  58574. _this.isCube = false;
  58575. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58576. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58577. _this.anisotropicFilteringLevel = 1;
  58578. _this._texture = _this._getFromCache(url, true);
  58579. if (!_this._texture) {
  58580. if (!scene.useDelayedTextureLoading) {
  58581. _this.loadTexture();
  58582. }
  58583. else {
  58584. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58585. }
  58586. }
  58587. return _this;
  58588. }
  58589. /**
  58590. * Returns the texture matrix used in most of the material.
  58591. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  58592. */
  58593. ColorGradingTexture.prototype.getTextureMatrix = function () {
  58594. return this._textureMatrix;
  58595. };
  58596. /**
  58597. * Occurs when the file being loaded is a .3dl LUT file.
  58598. */
  58599. ColorGradingTexture.prototype.load3dlTexture = function () {
  58600. var _this = this;
  58601. var mipLevels = 0;
  58602. var floatArrayView = null;
  58603. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58604. this._texture = texture;
  58605. var callback = function (text) {
  58606. var data;
  58607. var tempData;
  58608. var line;
  58609. var lines = text.split('\n');
  58610. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  58611. var maxColor = 0;
  58612. for (var i = 0; i < lines.length; i++) {
  58613. line = lines[i];
  58614. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  58615. continue;
  58616. if (line.indexOf('#') === 0)
  58617. continue;
  58618. var words = line.split(" ");
  58619. if (size === 0) {
  58620. // Number of space + one
  58621. size = words.length;
  58622. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  58623. tempData = new Float32Array(size * size * size * 4);
  58624. continue;
  58625. }
  58626. if (size != 0) {
  58627. var r = Math.max(parseInt(words[0]), 0);
  58628. var g = Math.max(parseInt(words[1]), 0);
  58629. var b = Math.max(parseInt(words[2]), 0);
  58630. maxColor = Math.max(r, maxColor);
  58631. maxColor = Math.max(g, maxColor);
  58632. maxColor = Math.max(b, maxColor);
  58633. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  58634. tempData[pixelStorageIndex + 0] = r;
  58635. tempData[pixelStorageIndex + 1] = g;
  58636. tempData[pixelStorageIndex + 2] = b;
  58637. tempData[pixelStorageIndex + 3] = 0;
  58638. pixelIndexSlice++;
  58639. if (pixelIndexSlice % size == 0) {
  58640. pixelIndexH++;
  58641. pixelIndexSlice = 0;
  58642. if (pixelIndexH % size == 0) {
  58643. pixelIndexW++;
  58644. pixelIndexH = 0;
  58645. }
  58646. }
  58647. }
  58648. }
  58649. for (var i = 0; i < tempData.length; i++) {
  58650. var value = tempData[i];
  58651. data[i] = (value / maxColor * 255);
  58652. }
  58653. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  58654. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  58655. };
  58656. BABYLON.Tools.LoadFile(this.url, callback);
  58657. return this._texture;
  58658. };
  58659. /**
  58660. * Starts the loading process of the texture.
  58661. */
  58662. ColorGradingTexture.prototype.loadTexture = function () {
  58663. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  58664. this.load3dlTexture();
  58665. }
  58666. };
  58667. /**
  58668. * Clones the color gradind texture.
  58669. */
  58670. ColorGradingTexture.prototype.clone = function () {
  58671. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  58672. // Base texture
  58673. newTexture.level = this.level;
  58674. return newTexture;
  58675. };
  58676. /**
  58677. * Called during delayed load for textures.
  58678. */
  58679. ColorGradingTexture.prototype.delayLoad = function () {
  58680. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58681. return;
  58682. }
  58683. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58684. this._texture = this._getFromCache(this.url, true);
  58685. if (!this._texture) {
  58686. this.loadTexture();
  58687. }
  58688. };
  58689. /**
  58690. * Binds the color grading to the shader.
  58691. * @param colorGrading The texture to bind
  58692. * @param effect The effect to bind to
  58693. */
  58694. ColorGradingTexture.Bind = function (colorGrading, effect) {
  58695. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  58696. var x = colorGrading.level; // Texture Level
  58697. var y = colorGrading.getSize().height; // Texture Size example with 8
  58698. var z = y - 1.0; // SizeMinusOne 8 - 1
  58699. var w = 1 / y; // Space of 1 slice 1 / 8
  58700. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  58701. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  58702. 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
  58703. 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
  58704. 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
  58705. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  58706. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  58707. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  58708. };
  58709. /**
  58710. * Prepare the list of uniforms associated with the ColorGrading effects.
  58711. * @param uniformsList The list of uniforms used in the effect
  58712. * @param samplersList The list of samplers used in the effect
  58713. */
  58714. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  58715. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  58716. samplersList.push("cameraColorGrading2DSampler");
  58717. };
  58718. /**
  58719. * Parses a color grading texture serialized by Babylon.
  58720. * @param parsedTexture The texture information being parsedTexture
  58721. * @param scene The scene to load the texture in
  58722. * @param rootUrl The root url of the data assets to load
  58723. * @return A color gradind texture
  58724. */
  58725. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58726. var texture = null;
  58727. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  58728. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  58729. texture.name = parsedTexture.name;
  58730. texture.level = parsedTexture.level;
  58731. }
  58732. return texture;
  58733. };
  58734. /**
  58735. * Serializes the LUT texture to json format.
  58736. */
  58737. ColorGradingTexture.prototype.serialize = function () {
  58738. if (!this.name) {
  58739. return null;
  58740. }
  58741. var serializationObject = {};
  58742. serializationObject.name = this.name;
  58743. serializationObject.level = this.level;
  58744. serializationObject.customType = "BABYLON.ColorGradingTexture";
  58745. return serializationObject;
  58746. };
  58747. return ColorGradingTexture;
  58748. }(BABYLON.BaseTexture));
  58749. /**
  58750. * Empty line regex stored for GC.
  58751. */
  58752. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  58753. BABYLON.ColorGradingTexture = ColorGradingTexture;
  58754. })(BABYLON || (BABYLON = {}));
  58755. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  58756. var BABYLON;
  58757. (function (BABYLON) {
  58758. /**
  58759. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  58760. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  58761. * 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;
  58762. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  58763. */
  58764. var ColorCurves = (function () {
  58765. function ColorCurves() {
  58766. this._dirty = true;
  58767. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  58768. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  58769. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  58770. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  58771. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  58772. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  58773. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  58774. this._globalHue = 30;
  58775. this._globalDensity = 0;
  58776. this._globalSaturation = 0;
  58777. this._globalExposure = 0;
  58778. this._highlightsHue = 30;
  58779. this._highlightsDensity = 0;
  58780. this._highlightsSaturation = 0;
  58781. this._highlightsExposure = 0;
  58782. this._midtonesHue = 30;
  58783. this._midtonesDensity = 0;
  58784. this._midtonesSaturation = 0;
  58785. this._midtonesExposure = 0;
  58786. this._shadowsHue = 30;
  58787. this._shadowsDensity = 0;
  58788. this._shadowsSaturation = 0;
  58789. this._shadowsExposure = 0;
  58790. }
  58791. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  58792. /**
  58793. * Gets the global Hue value.
  58794. * 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).
  58795. */
  58796. get: function () {
  58797. return this._globalHue;
  58798. },
  58799. /**
  58800. * Sets the global Hue value.
  58801. * 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).
  58802. */
  58803. set: function (value) {
  58804. this._globalHue = value;
  58805. this._dirty = true;
  58806. },
  58807. enumerable: true,
  58808. configurable: true
  58809. });
  58810. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  58811. /**
  58812. * Gets the global Density value.
  58813. * 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.
  58814. * Values less than zero provide a filter of opposite hue.
  58815. */
  58816. get: function () {
  58817. return this._globalDensity;
  58818. },
  58819. /**
  58820. * Sets the global Density value.
  58821. * 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.
  58822. * Values less than zero provide a filter of opposite hue.
  58823. */
  58824. set: function (value) {
  58825. this._globalDensity = value;
  58826. this._dirty = true;
  58827. },
  58828. enumerable: true,
  58829. configurable: true
  58830. });
  58831. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  58832. /**
  58833. * Gets the global Saturation value.
  58834. * 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.
  58835. */
  58836. get: function () {
  58837. return this._globalSaturation;
  58838. },
  58839. /**
  58840. * Sets the global Saturation value.
  58841. * 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.
  58842. */
  58843. set: function (value) {
  58844. this._globalSaturation = value;
  58845. this._dirty = true;
  58846. },
  58847. enumerable: true,
  58848. configurable: true
  58849. });
  58850. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  58851. /**
  58852. * Gets the highlights Hue value.
  58853. * 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).
  58854. */
  58855. get: function () {
  58856. return this._highlightsHue;
  58857. },
  58858. /**
  58859. * Sets the highlights Hue value.
  58860. * 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).
  58861. */
  58862. set: function (value) {
  58863. this._highlightsHue = value;
  58864. this._dirty = true;
  58865. },
  58866. enumerable: true,
  58867. configurable: true
  58868. });
  58869. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  58870. /**
  58871. * Gets the highlights Density value.
  58872. * 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.
  58873. * Values less than zero provide a filter of opposite hue.
  58874. */
  58875. get: function () {
  58876. return this._highlightsDensity;
  58877. },
  58878. /**
  58879. * Sets the highlights Density value.
  58880. * 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.
  58881. * Values less than zero provide a filter of opposite hue.
  58882. */
  58883. set: function (value) {
  58884. this._highlightsDensity = value;
  58885. this._dirty = true;
  58886. },
  58887. enumerable: true,
  58888. configurable: true
  58889. });
  58890. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  58891. /**
  58892. * Gets the highlights Saturation value.
  58893. * 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.
  58894. */
  58895. get: function () {
  58896. return this._highlightsSaturation;
  58897. },
  58898. /**
  58899. * Sets the highlights Saturation value.
  58900. * 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.
  58901. */
  58902. set: function (value) {
  58903. this._highlightsSaturation = value;
  58904. this._dirty = true;
  58905. },
  58906. enumerable: true,
  58907. configurable: true
  58908. });
  58909. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  58910. /**
  58911. * Gets the highlights Exposure value.
  58912. * 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.
  58913. */
  58914. get: function () {
  58915. return this._highlightsExposure;
  58916. },
  58917. /**
  58918. * Sets the highlights Exposure value.
  58919. * 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.
  58920. */
  58921. set: function (value) {
  58922. this._highlightsExposure = value;
  58923. this._dirty = true;
  58924. },
  58925. enumerable: true,
  58926. configurable: true
  58927. });
  58928. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  58929. /**
  58930. * Gets the midtones Hue value.
  58931. * 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).
  58932. */
  58933. get: function () {
  58934. return this._midtonesHue;
  58935. },
  58936. /**
  58937. * Sets the midtones Hue value.
  58938. * 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).
  58939. */
  58940. set: function (value) {
  58941. this._midtonesHue = value;
  58942. this._dirty = true;
  58943. },
  58944. enumerable: true,
  58945. configurable: true
  58946. });
  58947. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  58948. /**
  58949. * Gets the midtones Density value.
  58950. * 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.
  58951. * Values less than zero provide a filter of opposite hue.
  58952. */
  58953. get: function () {
  58954. return this._midtonesDensity;
  58955. },
  58956. /**
  58957. * Sets the midtones Density value.
  58958. * 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.
  58959. * Values less than zero provide a filter of opposite hue.
  58960. */
  58961. set: function (value) {
  58962. this._midtonesDensity = value;
  58963. this._dirty = true;
  58964. },
  58965. enumerable: true,
  58966. configurable: true
  58967. });
  58968. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  58969. /**
  58970. * Gets the midtones Saturation value.
  58971. * 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.
  58972. */
  58973. get: function () {
  58974. return this._midtonesSaturation;
  58975. },
  58976. /**
  58977. * Sets the midtones Saturation value.
  58978. * 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.
  58979. */
  58980. set: function (value) {
  58981. this._midtonesSaturation = value;
  58982. this._dirty = true;
  58983. },
  58984. enumerable: true,
  58985. configurable: true
  58986. });
  58987. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  58988. /**
  58989. * Gets the midtones Exposure value.
  58990. * 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.
  58991. */
  58992. get: function () {
  58993. return this._midtonesExposure;
  58994. },
  58995. /**
  58996. * Sets the midtones Exposure value.
  58997. * 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.
  58998. */
  58999. set: function (value) {
  59000. this._midtonesExposure = value;
  59001. this._dirty = true;
  59002. },
  59003. enumerable: true,
  59004. configurable: true
  59005. });
  59006. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  59007. /**
  59008. * Gets the shadows Hue value.
  59009. * 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).
  59010. */
  59011. get: function () {
  59012. return this._shadowsHue;
  59013. },
  59014. /**
  59015. * Sets the shadows Hue value.
  59016. * 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).
  59017. */
  59018. set: function (value) {
  59019. this._shadowsHue = value;
  59020. this._dirty = true;
  59021. },
  59022. enumerable: true,
  59023. configurable: true
  59024. });
  59025. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  59026. /**
  59027. * Gets the shadows Density value.
  59028. * 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.
  59029. * Values less than zero provide a filter of opposite hue.
  59030. */
  59031. get: function () {
  59032. return this._shadowsDensity;
  59033. },
  59034. /**
  59035. * Sets the shadows Density value.
  59036. * 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.
  59037. * Values less than zero provide a filter of opposite hue.
  59038. */
  59039. set: function (value) {
  59040. this._shadowsDensity = value;
  59041. this._dirty = true;
  59042. },
  59043. enumerable: true,
  59044. configurable: true
  59045. });
  59046. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  59047. /**
  59048. * Gets the shadows Saturation value.
  59049. * 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.
  59050. */
  59051. get: function () {
  59052. return this._shadowsSaturation;
  59053. },
  59054. /**
  59055. * Sets the shadows Saturation value.
  59056. * 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.
  59057. */
  59058. set: function (value) {
  59059. this._shadowsSaturation = value;
  59060. this._dirty = true;
  59061. },
  59062. enumerable: true,
  59063. configurable: true
  59064. });
  59065. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  59066. /**
  59067. * Gets the shadows Exposure value.
  59068. * 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.
  59069. */
  59070. get: function () {
  59071. return this._shadowsExposure;
  59072. },
  59073. /**
  59074. * Sets the shadows Exposure value.
  59075. * 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.
  59076. */
  59077. set: function (value) {
  59078. this._shadowsExposure = value;
  59079. this._dirty = true;
  59080. },
  59081. enumerable: true,
  59082. configurable: true
  59083. });
  59084. /**
  59085. * Binds the color curves to the shader.
  59086. * @param colorCurves The color curve to bind
  59087. * @param effect The effect to bind to
  59088. */
  59089. ColorCurves.Bind = function (colorCurves, effect) {
  59090. if (colorCurves._dirty) {
  59091. colorCurves._dirty = false;
  59092. // Fill in global info.
  59093. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  59094. // Compute highlights info.
  59095. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  59096. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  59097. // Compute midtones info.
  59098. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  59099. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  59100. // Compute shadows info.
  59101. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  59102. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  59103. // Compute deltas (neutral is midtones).
  59104. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  59105. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  59106. }
  59107. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  59108. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  59109. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  59110. };
  59111. /**
  59112. * Prepare the list of uniforms associated with the ColorCurves effects.
  59113. * @param uniformsList The list of uniforms used in the effect
  59114. */
  59115. ColorCurves.PrepareUniforms = function (uniformsList) {
  59116. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  59117. };
  59118. /**
  59119. * Returns color grading data based on a hue, density, saturation and exposure value.
  59120. * @param filterHue The hue of the color filter.
  59121. * @param filterDensity The density of the color filter.
  59122. * @param saturation The saturation.
  59123. * @param exposure The exposure.
  59124. * @param result The result data container.
  59125. */
  59126. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  59127. if (hue == null) {
  59128. return;
  59129. }
  59130. hue = ColorCurves.clamp(hue, 0, 360);
  59131. density = ColorCurves.clamp(density, -100, 100);
  59132. saturation = ColorCurves.clamp(saturation, -100, 100);
  59133. exposure = ColorCurves.clamp(exposure, -100, 100);
  59134. // Remap the slider/config filter density with non-linear mapping and also scale by half
  59135. // so that the maximum filter density is only 50% control. This provides fine control
  59136. // for small values and reasonable range.
  59137. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  59138. density *= 0.5;
  59139. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  59140. if (density < 0) {
  59141. density *= -1;
  59142. hue = (hue + 180) % 360;
  59143. }
  59144. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  59145. result.scaleToRef(2, result);
  59146. result.a = 1 + 0.01 * saturation;
  59147. };
  59148. /**
  59149. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  59150. * @param value The input slider value in range [-100,100].
  59151. * @returns Adjusted value.
  59152. */
  59153. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  59154. value /= 100;
  59155. var x = Math.abs(value);
  59156. x = Math.pow(x, 2);
  59157. if (value < 0) {
  59158. x *= -1;
  59159. }
  59160. x *= 100;
  59161. return x;
  59162. };
  59163. /**
  59164. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  59165. * @param hue The hue (H) input.
  59166. * @param saturation The saturation (S) input.
  59167. * @param brightness The brightness (B) input.
  59168. * @result An RGBA color represented as Vector4.
  59169. */
  59170. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  59171. var h = ColorCurves.clamp(hue, 0, 360);
  59172. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  59173. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  59174. if (s === 0) {
  59175. result.r = v;
  59176. result.g = v;
  59177. result.b = v;
  59178. }
  59179. else {
  59180. // sector 0 to 5
  59181. h /= 60;
  59182. var i = Math.floor(h);
  59183. // fractional part of h
  59184. var f = h - i;
  59185. var p = v * (1 - s);
  59186. var q = v * (1 - s * f);
  59187. var t = v * (1 - s * (1 - f));
  59188. switch (i) {
  59189. case 0:
  59190. result.r = v;
  59191. result.g = t;
  59192. result.b = p;
  59193. break;
  59194. case 1:
  59195. result.r = q;
  59196. result.g = v;
  59197. result.b = p;
  59198. break;
  59199. case 2:
  59200. result.r = p;
  59201. result.g = v;
  59202. result.b = t;
  59203. break;
  59204. case 3:
  59205. result.r = p;
  59206. result.g = q;
  59207. result.b = v;
  59208. break;
  59209. case 4:
  59210. result.r = t;
  59211. result.g = p;
  59212. result.b = v;
  59213. break;
  59214. default:
  59215. result.r = v;
  59216. result.g = p;
  59217. result.b = q;
  59218. break;
  59219. }
  59220. }
  59221. result.a = 1;
  59222. };
  59223. /**
  59224. * Returns a value clamped between min and max
  59225. * @param value The value to clamp
  59226. * @param min The minimum of value
  59227. * @param max The maximum of value
  59228. * @returns The clamped value.
  59229. */
  59230. ColorCurves.clamp = function (value, min, max) {
  59231. return Math.min(Math.max(value, min), max);
  59232. };
  59233. /**
  59234. * Clones the current color curve instance.
  59235. * @return The cloned curves
  59236. */
  59237. ColorCurves.prototype.clone = function () {
  59238. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  59239. };
  59240. /**
  59241. * Serializes the current color curve instance to a json representation.
  59242. * @return a JSON representation
  59243. */
  59244. ColorCurves.prototype.serialize = function () {
  59245. return BABYLON.SerializationHelper.Serialize(this);
  59246. };
  59247. /**
  59248. * Parses the color curve from a json representation.
  59249. * @param source the JSON source to parse
  59250. * @return The parsed curves
  59251. */
  59252. ColorCurves.Parse = function (source) {
  59253. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  59254. };
  59255. return ColorCurves;
  59256. }());
  59257. __decorate([
  59258. BABYLON.serialize()
  59259. ], ColorCurves.prototype, "_globalHue", void 0);
  59260. __decorate([
  59261. BABYLON.serialize()
  59262. ], ColorCurves.prototype, "_globalDensity", void 0);
  59263. __decorate([
  59264. BABYLON.serialize()
  59265. ], ColorCurves.prototype, "_globalSaturation", void 0);
  59266. __decorate([
  59267. BABYLON.serialize()
  59268. ], ColorCurves.prototype, "_globalExposure", void 0);
  59269. __decorate([
  59270. BABYLON.serialize()
  59271. ], ColorCurves.prototype, "_highlightsHue", void 0);
  59272. __decorate([
  59273. BABYLON.serialize()
  59274. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  59275. __decorate([
  59276. BABYLON.serialize()
  59277. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  59278. __decorate([
  59279. BABYLON.serialize()
  59280. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  59281. __decorate([
  59282. BABYLON.serialize()
  59283. ], ColorCurves.prototype, "_midtonesHue", void 0);
  59284. __decorate([
  59285. BABYLON.serialize()
  59286. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  59287. __decorate([
  59288. BABYLON.serialize()
  59289. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  59290. __decorate([
  59291. BABYLON.serialize()
  59292. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  59293. BABYLON.ColorCurves = ColorCurves;
  59294. })(BABYLON || (BABYLON = {}));
  59295. //# sourceMappingURL=babylon.colorCurves.js.map
  59296. var BABYLON;
  59297. (function (BABYLON) {
  59298. var PBRMaterialDefines = (function (_super) {
  59299. __extends(PBRMaterialDefines, _super);
  59300. function PBRMaterialDefines() {
  59301. var _this = _super.call(this) || this;
  59302. _this.ALBEDO = false;
  59303. _this.AMBIENT = false;
  59304. _this.OPACITY = false;
  59305. _this.OPACITYRGB = false;
  59306. _this.REFLECTION = false;
  59307. _this.EMISSIVE = false;
  59308. _this.REFLECTIVITY = false;
  59309. _this.BUMP = false;
  59310. _this.PARALLAX = false;
  59311. _this.PARALLAXOCCLUSION = false;
  59312. _this.SPECULAROVERALPHA = false;
  59313. _this.CLIPPLANE = false;
  59314. _this.ALPHATEST = false;
  59315. _this.ALPHAFROMALBEDO = false;
  59316. _this.POINTSIZE = false;
  59317. _this.FOG = false;
  59318. _this.SPECULARTERM = false;
  59319. _this.OPACITYFRESNEL = false;
  59320. _this.EMISSIVEFRESNEL = false;
  59321. _this.FRESNEL = false;
  59322. _this.NORMAL = false;
  59323. _this.TANGENT = false;
  59324. _this.UV1 = false;
  59325. _this.UV2 = false;
  59326. _this.VERTEXCOLOR = false;
  59327. _this.VERTEXALPHA = false;
  59328. _this.NUM_BONE_INFLUENCERS = 0;
  59329. _this.BonesPerMesh = 0;
  59330. _this.INSTANCES = false;
  59331. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  59332. _this.MICROSURFACEAUTOMATIC = false;
  59333. _this.EMISSIVEASILLUMINATION = false;
  59334. _this.LINKEMISSIVEWITHALBEDO = false;
  59335. _this.LIGHTMAP = false;
  59336. _this.USELIGHTMAPASSHADOWMAP = false;
  59337. _this.REFLECTIONMAP_3D = false;
  59338. _this.REFLECTIONMAP_SPHERICAL = false;
  59339. _this.REFLECTIONMAP_PLANAR = false;
  59340. _this.REFLECTIONMAP_CUBIC = false;
  59341. _this.REFLECTIONMAP_PROJECTION = false;
  59342. _this.REFLECTIONMAP_SKYBOX = false;
  59343. _this.REFLECTIONMAP_EXPLICIT = false;
  59344. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  59345. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  59346. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  59347. _this.INVERTCUBICMAP = false;
  59348. _this.LOGARITHMICDEPTH = false;
  59349. _this.CAMERATONEMAP = false;
  59350. _this.CAMERACONTRAST = false;
  59351. _this.CAMERACOLORGRADING = false;
  59352. _this.CAMERACOLORCURVES = false;
  59353. _this.OVERLOADEDVALUES = false;
  59354. _this.OVERLOADEDSHADOWVALUES = false;
  59355. _this.USESPHERICALFROMREFLECTIONMAP = false;
  59356. _this.REFRACTION = false;
  59357. _this.REFRACTIONMAP_3D = false;
  59358. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  59359. _this.REFRACTIONMAPINLINEARSPACE = false;
  59360. _this.LODBASEDMICROSFURACE = false;
  59361. _this.USEPHYSICALLIGHTFALLOFF = false;
  59362. _this.RADIANCEOVERALPHA = false;
  59363. _this.USEPMREMREFLECTION = false;
  59364. _this.USEPMREMREFRACTION = false;
  59365. _this.INVERTNORMALMAPX = false;
  59366. _this.INVERTNORMALMAPY = false;
  59367. _this.TWOSIDEDLIGHTING = false;
  59368. _this.SHADOWFULLFLOAT = false;
  59369. _this.METALLICWORKFLOW = false;
  59370. _this.METALLICROUGHNESSMAP = false;
  59371. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  59372. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  59373. _this.rebuild();
  59374. return _this;
  59375. }
  59376. return PBRMaterialDefines;
  59377. }(BABYLON.MaterialDefines));
  59378. /**
  59379. * The Physically based material of BJS.
  59380. *
  59381. * This offers the main features of a standard PBR material.
  59382. * For more information, please refer to the documentation :
  59383. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  59384. */
  59385. var PBRMaterial = (function (_super) {
  59386. __extends(PBRMaterial, _super);
  59387. /**
  59388. * Instantiates a new PBRMaterial instance.
  59389. *
  59390. * @param name The material name
  59391. * @param scene The scene the material will be use in.
  59392. */
  59393. function PBRMaterial(name, scene) {
  59394. var _this = _super.call(this, name, scene) || this;
  59395. /**
  59396. * Intensity of the direct lights e.g. the four lights available in your scene.
  59397. * This impacts both the direct diffuse and specular highlights.
  59398. */
  59399. _this.directIntensity = 1.0;
  59400. /**
  59401. * Intensity of the emissive part of the material.
  59402. * This helps controlling the emissive effect without modifying the emissive color.
  59403. */
  59404. _this.emissiveIntensity = 1.0;
  59405. /**
  59406. * Intensity of the environment e.g. how much the environment will light the object
  59407. * either through harmonics for rough material or through the refelction for shiny ones.
  59408. */
  59409. _this.environmentIntensity = 1.0;
  59410. /**
  59411. * This is a special control allowing the reduction of the specular highlights coming from the
  59412. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  59413. */
  59414. _this.specularIntensity = 1.0;
  59415. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  59416. /**
  59417. * Debug Control allowing disabling the bump map on this material.
  59418. */
  59419. _this.disableBumpMap = false;
  59420. /**
  59421. * Debug Control helping enforcing or dropping the darkness of shadows.
  59422. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  59423. */
  59424. _this.overloadedShadowIntensity = 1.0;
  59425. /**
  59426. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  59427. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  59428. */
  59429. _this.overloadedShadeIntensity = 1.0;
  59430. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  59431. /**
  59432. * The camera exposure used on this material.
  59433. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  59434. * This corresponds to a photographic exposure.
  59435. */
  59436. _this.cameraExposure = 1.0;
  59437. /**
  59438. * The camera contrast used on this material.
  59439. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  59440. */
  59441. _this.cameraContrast = 1.0;
  59442. /**
  59443. * Color Grading 2D Lookup Texture.
  59444. * This allows special effects like sepia, black and white to sixties rendering style.
  59445. */
  59446. _this.cameraColorGradingTexture = null;
  59447. /**
  59448. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  59449. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  59450. * 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;
  59451. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  59452. */
  59453. _this.cameraColorCurves = null;
  59454. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  59455. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  59456. /**
  59457. * Debug Control allowing to overload the ambient color.
  59458. * This as to be use with the overloadedAmbientIntensity parameter.
  59459. */
  59460. _this.overloadedAmbient = BABYLON.Color3.White();
  59461. /**
  59462. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  59463. */
  59464. _this.overloadedAmbientIntensity = 0.0;
  59465. /**
  59466. * Debug Control allowing to overload the albedo color.
  59467. * This as to be use with the overloadedAlbedoIntensity parameter.
  59468. */
  59469. _this.overloadedAlbedo = BABYLON.Color3.White();
  59470. /**
  59471. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  59472. */
  59473. _this.overloadedAlbedoIntensity = 0.0;
  59474. /**
  59475. * Debug Control allowing to overload the reflectivity color.
  59476. * This as to be use with the overloadedReflectivityIntensity parameter.
  59477. */
  59478. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  59479. /**
  59480. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  59481. */
  59482. _this.overloadedReflectivityIntensity = 0.0;
  59483. /**
  59484. * Debug Control allowing to overload the emissive color.
  59485. * This as to be use with the overloadedEmissiveIntensity parameter.
  59486. */
  59487. _this.overloadedEmissive = BABYLON.Color3.White();
  59488. /**
  59489. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  59490. */
  59491. _this.overloadedEmissiveIntensity = 0.0;
  59492. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  59493. /**
  59494. * Debug Control allowing to overload the reflection color.
  59495. * This as to be use with the overloadedReflectionIntensity parameter.
  59496. */
  59497. _this.overloadedReflection = BABYLON.Color3.White();
  59498. /**
  59499. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  59500. */
  59501. _this.overloadedReflectionIntensity = 0.0;
  59502. /**
  59503. * Debug Control allowing to overload the microsurface.
  59504. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  59505. */
  59506. _this.overloadedMicroSurface = 0.0;
  59507. /**
  59508. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  59509. */
  59510. _this.overloadedMicroSurfaceIntensity = 0.0;
  59511. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  59512. /**
  59513. * AKA Occlusion Texture Intensity in other nomenclature.
  59514. */
  59515. _this.ambientTextureStrength = 1.0;
  59516. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  59517. /**
  59518. * AKA Diffuse Color in other nomenclature.
  59519. */
  59520. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  59521. /**
  59522. * AKA Specular Color in other nomenclature.
  59523. */
  59524. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  59525. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  59526. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  59527. /**
  59528. * AKA Glossiness in other nomenclature.
  59529. */
  59530. _this.microSurface = 0.9;
  59531. /**
  59532. * source material index of refraction (IOR)' / 'destination material IOR.
  59533. */
  59534. _this.indexOfRefraction = 0.66;
  59535. /**
  59536. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  59537. */
  59538. _this.invertRefractionY = false;
  59539. /**
  59540. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  59541. * Materials half opaque for instance using refraction could benefit from this control.
  59542. */
  59543. _this.linkRefractionWithTransparency = false;
  59544. /**
  59545. * The emissive and albedo are linked to never be more than one (Energy conservation).
  59546. */
  59547. _this.linkEmissiveWithAlbedo = false;
  59548. _this.useLightmapAsShadowmap = false;
  59549. /**
  59550. * In this mode, the emissive informtaion will always be added to the lighting once.
  59551. * A light for instance can be thought as emissive.
  59552. */
  59553. _this.useEmissiveAsIllumination = false;
  59554. /**
  59555. * Secifies that the alpha is coming form the albedo channel alpha channel.
  59556. */
  59557. _this.useAlphaFromAlbedoTexture = false;
  59558. /**
  59559. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  59560. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  59561. */
  59562. _this.useSpecularOverAlpha = true;
  59563. /**
  59564. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  59565. */
  59566. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  59567. /**
  59568. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  59569. */
  59570. _this.useRoughnessFromMetallicTextureAlpha = true;
  59571. /**
  59572. * Specifies if the metallic texture contains the roughness information in its green channel.
  59573. */
  59574. _this.useRoughnessFromMetallicTextureGreen = false;
  59575. /**
  59576. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  59577. * The material will try to infer what glossiness each pixel should be.
  59578. */
  59579. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  59580. /**
  59581. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  59582. * the creation of the material.
  59583. */
  59584. _this.useScalarInLinearSpace = false;
  59585. /**
  59586. * BJS is using an harcoded light falloff based on a manually sets up range.
  59587. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  59588. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  59589. */
  59590. _this.usePhysicalLightFalloff = true;
  59591. /**
  59592. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  59593. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  59594. */
  59595. _this.useRadianceOverAlpha = true;
  59596. /**
  59597. * Allows using the bump map in parallax mode.
  59598. */
  59599. _this.useParallax = false;
  59600. /**
  59601. * Allows using the bump map in parallax occlusion mode.
  59602. */
  59603. _this.useParallaxOcclusion = false;
  59604. /**
  59605. * Controls the scale bias of the parallax mode.
  59606. */
  59607. _this.parallaxScaleBias = 0.05;
  59608. /**
  59609. * If sets to true, disables all the lights affecting the material.
  59610. */
  59611. _this.disableLighting = false;
  59612. /**
  59613. * Number of Simultaneous lights allowed on the material.
  59614. */
  59615. _this.maxSimultaneousLights = 4;
  59616. /**
  59617. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  59618. */
  59619. _this.invertNormalMapX = false;
  59620. /**
  59621. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  59622. */
  59623. _this.invertNormalMapY = false;
  59624. /**
  59625. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  59626. */
  59627. _this.twoSidedLighting = false;
  59628. _this._renderTargets = new BABYLON.SmartArray(16);
  59629. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  59630. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  59631. _this._tempColor = new BABYLON.Color3();
  59632. _this._defines = new PBRMaterialDefines();
  59633. _this._cachedDefines = new PBRMaterialDefines();
  59634. _this._myScene = null;
  59635. _this._myShadowGenerator = null;
  59636. _this._cachedDefines.BonesPerMesh = -1;
  59637. _this.getRenderTargetTextures = function () {
  59638. _this._renderTargets.reset();
  59639. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  59640. _this._renderTargets.push(_this.reflectionTexture);
  59641. }
  59642. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  59643. _this._renderTargets.push(_this.refractionTexture);
  59644. }
  59645. return _this._renderTargets;
  59646. };
  59647. return _this;
  59648. }
  59649. PBRMaterial.prototype.getClassName = function () {
  59650. return "PBRMaterial";
  59651. };
  59652. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  59653. get: function () {
  59654. return this._useLogarithmicDepth;
  59655. },
  59656. set: function (value) {
  59657. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  59658. },
  59659. enumerable: true,
  59660. configurable: true
  59661. });
  59662. PBRMaterial.prototype.needAlphaBlending = function () {
  59663. if (this.linkRefractionWithTransparency) {
  59664. return false;
  59665. }
  59666. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  59667. };
  59668. PBRMaterial.prototype.needAlphaTesting = function () {
  59669. if (this.linkRefractionWithTransparency) {
  59670. return false;
  59671. }
  59672. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  59673. };
  59674. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  59675. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  59676. };
  59677. PBRMaterial.prototype.getAlphaTestTexture = function () {
  59678. return this.albedoTexture;
  59679. };
  59680. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59681. if (!mesh) {
  59682. return true;
  59683. }
  59684. if (this._defines.INSTANCES !== useInstances) {
  59685. return false;
  59686. }
  59687. return false;
  59688. };
  59689. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  59690. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  59691. };
  59692. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  59693. if (!useScalarInLinear) {
  59694. color.toLinearSpaceToRef(ref);
  59695. }
  59696. else {
  59697. ref.r = color.r;
  59698. ref.g = color.g;
  59699. ref.b = color.b;
  59700. }
  59701. };
  59702. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  59703. var lightIndex = 0;
  59704. var depthValuesAlreadySet = false;
  59705. for (var index = 0; index < scene.lights.length; index++) {
  59706. var light = scene.lights[index];
  59707. if (!light.isEnabled()) {
  59708. continue;
  59709. }
  59710. if (!light.canAffectMesh(mesh)) {
  59711. continue;
  59712. }
  59713. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  59714. // GAMMA CORRECTION.
  59715. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  59716. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  59717. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  59718. if (defines["SPECULARTERM"]) {
  59719. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  59720. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  59721. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  59722. }
  59723. // Shadows
  59724. if (scene.shadowsEnabled) {
  59725. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  59726. }
  59727. lightIndex++;
  59728. if (lightIndex === maxSimultaneousLights)
  59729. break;
  59730. }
  59731. };
  59732. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  59733. if (this.isFrozen) {
  59734. if (this._wasPreviouslyReady) {
  59735. return true;
  59736. }
  59737. }
  59738. var scene = this.getScene();
  59739. var engine = scene.getEngine();
  59740. var needNormals = false;
  59741. var needUVs = false;
  59742. this._defines.reset();
  59743. if (scene.lightsEnabled && !this.disableLighting) {
  59744. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  59745. }
  59746. if (!this.checkReadyOnEveryCall) {
  59747. if (this._renderId === scene.getRenderId()) {
  59748. if (this._checkCache(scene, mesh, useInstances)) {
  59749. return true;
  59750. }
  59751. }
  59752. }
  59753. if (scene.texturesEnabled) {
  59754. if (scene.getEngine().getCaps().textureLOD) {
  59755. this._defines.LODBASEDMICROSFURACE = true;
  59756. }
  59757. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  59758. if (!this.albedoTexture.isReady()) {
  59759. return false;
  59760. }
  59761. else {
  59762. needUVs = true;
  59763. this._defines.ALBEDO = true;
  59764. }
  59765. }
  59766. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  59767. if (!this.ambientTexture.isReady()) {
  59768. return false;
  59769. }
  59770. else {
  59771. needUVs = true;
  59772. this._defines.AMBIENT = true;
  59773. }
  59774. }
  59775. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  59776. if (!this.opacityTexture.isReady()) {
  59777. return false;
  59778. }
  59779. else {
  59780. needUVs = true;
  59781. this._defines.OPACITY = true;
  59782. if (this.opacityTexture.getAlphaFromRGB) {
  59783. this._defines.OPACITYRGB = true;
  59784. }
  59785. }
  59786. }
  59787. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  59788. if (!this.reflectionTexture.isReady()) {
  59789. return false;
  59790. }
  59791. else {
  59792. needNormals = true;
  59793. this._defines.REFLECTION = true;
  59794. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  59795. this._defines.INVERTCUBICMAP = true;
  59796. }
  59797. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  59798. switch (this.reflectionTexture.coordinatesMode) {
  59799. case BABYLON.Texture.CUBIC_MODE:
  59800. case BABYLON.Texture.INVCUBIC_MODE:
  59801. this._defines.REFLECTIONMAP_CUBIC = true;
  59802. break;
  59803. case BABYLON.Texture.EXPLICIT_MODE:
  59804. this._defines.REFLECTIONMAP_EXPLICIT = true;
  59805. break;
  59806. case BABYLON.Texture.PLANAR_MODE:
  59807. this._defines.REFLECTIONMAP_PLANAR = true;
  59808. break;
  59809. case BABYLON.Texture.PROJECTION_MODE:
  59810. this._defines.REFLECTIONMAP_PROJECTION = true;
  59811. break;
  59812. case BABYLON.Texture.SKYBOX_MODE:
  59813. this._defines.REFLECTIONMAP_SKYBOX = true;
  59814. break;
  59815. case BABYLON.Texture.SPHERICAL_MODE:
  59816. this._defines.REFLECTIONMAP_SPHERICAL = true;
  59817. break;
  59818. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  59819. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  59820. break;
  59821. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  59822. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  59823. break;
  59824. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  59825. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  59826. break;
  59827. }
  59828. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  59829. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  59830. needNormals = true;
  59831. if (this.reflectionTexture.isPMREM) {
  59832. this._defines.USEPMREMREFLECTION = true;
  59833. }
  59834. }
  59835. }
  59836. }
  59837. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  59838. if (!this.lightmapTexture.isReady()) {
  59839. return false;
  59840. }
  59841. else {
  59842. needUVs = true;
  59843. this._defines.LIGHTMAP = true;
  59844. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  59845. }
  59846. }
  59847. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  59848. if (!this.emissiveTexture.isReady()) {
  59849. return false;
  59850. }
  59851. else {
  59852. needUVs = true;
  59853. this._defines.EMISSIVE = true;
  59854. }
  59855. }
  59856. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  59857. if (this.metallicTexture) {
  59858. if (!this.metallicTexture.isReady()) {
  59859. return false;
  59860. }
  59861. else {
  59862. needUVs = true;
  59863. this._defines.METALLICWORKFLOW = true;
  59864. this._defines.METALLICROUGHNESSMAP = true;
  59865. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  59866. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  59867. }
  59868. }
  59869. else if (this.reflectivityTexture) {
  59870. if (!this.reflectivityTexture.isReady()) {
  59871. return false;
  59872. }
  59873. else {
  59874. needUVs = true;
  59875. this._defines.REFLECTIVITY = true;
  59876. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  59877. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  59878. }
  59879. }
  59880. }
  59881. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  59882. if (!this.bumpTexture.isReady()) {
  59883. return false;
  59884. }
  59885. else {
  59886. needUVs = true;
  59887. this._defines.BUMP = true;
  59888. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  59889. this._defines.PARALLAX = true;
  59890. if (this.useParallaxOcclusion) {
  59891. this._defines.PARALLAXOCCLUSION = true;
  59892. }
  59893. }
  59894. if (this.invertNormalMapX) {
  59895. this._defines.INVERTNORMALMAPX = true;
  59896. }
  59897. if (this.invertNormalMapY) {
  59898. this._defines.INVERTNORMALMAPY = true;
  59899. }
  59900. if (scene._mirroredCameraPosition) {
  59901. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  59902. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  59903. }
  59904. }
  59905. }
  59906. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  59907. if (!this.refractionTexture.isReady()) {
  59908. return false;
  59909. }
  59910. else {
  59911. needUVs = true;
  59912. this._defines.REFRACTION = true;
  59913. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  59914. if (this.linkRefractionWithTransparency) {
  59915. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  59916. }
  59917. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  59918. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  59919. if (this.refractionTexture.isPMREM) {
  59920. this._defines.USEPMREMREFRACTION = true;
  59921. }
  59922. }
  59923. }
  59924. }
  59925. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  59926. if (!this.cameraColorGradingTexture.isReady()) {
  59927. return false;
  59928. }
  59929. else {
  59930. this._defines.CAMERACOLORGRADING = true;
  59931. }
  59932. }
  59933. if (!this.backFaceCulling && this.twoSidedLighting) {
  59934. this._defines.TWOSIDEDLIGHTING = true;
  59935. }
  59936. }
  59937. // Effect
  59938. if (scene.clipPlane) {
  59939. this._defines.CLIPPLANE = true;
  59940. }
  59941. if (engine.getAlphaTesting()) {
  59942. this._defines.ALPHATEST = true;
  59943. }
  59944. if (this._shouldUseAlphaFromAlbedoTexture()) {
  59945. this._defines.ALPHAFROMALBEDO = true;
  59946. }
  59947. if (this.useEmissiveAsIllumination) {
  59948. this._defines.EMISSIVEASILLUMINATION = true;
  59949. }
  59950. if (this.linkEmissiveWithAlbedo) {
  59951. this._defines.LINKEMISSIVEWITHALBEDO = true;
  59952. }
  59953. if (this.useLogarithmicDepth) {
  59954. this._defines.LOGARITHMICDEPTH = true;
  59955. }
  59956. if (this.cameraContrast != 1) {
  59957. this._defines.CAMERACONTRAST = true;
  59958. }
  59959. if (this.cameraExposure != 1) {
  59960. this._defines.CAMERATONEMAP = true;
  59961. }
  59962. if (this.cameraColorCurves) {
  59963. this._defines.CAMERACOLORCURVES = true;
  59964. }
  59965. if (this.overloadedShadeIntensity != 1 ||
  59966. this.overloadedShadowIntensity != 1) {
  59967. this._defines.OVERLOADEDSHADOWVALUES = true;
  59968. }
  59969. if (this.overloadedMicroSurfaceIntensity > 0 ||
  59970. this.overloadedEmissiveIntensity > 0 ||
  59971. this.overloadedReflectivityIntensity > 0 ||
  59972. this.overloadedAlbedoIntensity > 0 ||
  59973. this.overloadedAmbientIntensity > 0 ||
  59974. this.overloadedReflectionIntensity > 0) {
  59975. this._defines.OVERLOADEDVALUES = true;
  59976. }
  59977. // Point size
  59978. if (this.pointsCloud || scene.forcePointsCloud) {
  59979. this._defines.POINTSIZE = true;
  59980. }
  59981. // Fog
  59982. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  59983. this._defines.FOG = true;
  59984. }
  59985. if (BABYLON.StandardMaterial.FresnelEnabled) {
  59986. // Fresnel
  59987. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  59988. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59989. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  59990. this._defines.OPACITYFRESNEL = true;
  59991. }
  59992. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59993. this._defines.EMISSIVEFRESNEL = true;
  59994. }
  59995. needNormals = true;
  59996. this._defines.FRESNEL = true;
  59997. }
  59998. }
  59999. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  60000. this._defines.SPECULAROVERALPHA = true;
  60001. }
  60002. if (this.usePhysicalLightFalloff) {
  60003. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  60004. }
  60005. if (this.useRadianceOverAlpha) {
  60006. this._defines.RADIANCEOVERALPHA = true;
  60007. }
  60008. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  60009. this._defines.METALLICWORKFLOW = true;
  60010. }
  60011. // Attribs
  60012. if (mesh) {
  60013. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  60014. this._defines.NORMAL = true;
  60015. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  60016. this._defines.TANGENT = true;
  60017. }
  60018. }
  60019. if (needUVs) {
  60020. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60021. this._defines.UV1 = true;
  60022. }
  60023. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60024. this._defines.UV2 = true;
  60025. }
  60026. }
  60027. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60028. this._defines.VERTEXCOLOR = true;
  60029. if (mesh.hasVertexAlpha) {
  60030. this._defines.VERTEXALPHA = true;
  60031. }
  60032. }
  60033. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60034. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  60035. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  60036. }
  60037. // Instances
  60038. if (useInstances) {
  60039. this._defines.INSTANCES = true;
  60040. }
  60041. }
  60042. // Get correct effect
  60043. if (!this._defines.isEqual(this._cachedDefines)) {
  60044. this._defines.cloneTo(this._cachedDefines);
  60045. scene.resetCachedMaterial();
  60046. // Fallbacks
  60047. var fallbacks = new BABYLON.EffectFallbacks();
  60048. if (this._defines.REFLECTION) {
  60049. fallbacks.addFallback(0, "REFLECTION");
  60050. }
  60051. if (this._defines.REFRACTION) {
  60052. fallbacks.addFallback(0, "REFRACTION");
  60053. }
  60054. if (this._defines.REFLECTIVITY) {
  60055. fallbacks.addFallback(0, "REFLECTIVITY");
  60056. }
  60057. if (this._defines.BUMP) {
  60058. fallbacks.addFallback(0, "BUMP");
  60059. }
  60060. if (this._defines.PARALLAX) {
  60061. fallbacks.addFallback(1, "PARALLAX");
  60062. }
  60063. if (this._defines.PARALLAXOCCLUSION) {
  60064. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  60065. }
  60066. if (this._defines.SPECULAROVERALPHA) {
  60067. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  60068. }
  60069. if (this._defines.FOG) {
  60070. fallbacks.addFallback(1, "FOG");
  60071. }
  60072. if (this._defines.POINTSIZE) {
  60073. fallbacks.addFallback(0, "POINTSIZE");
  60074. }
  60075. if (this._defines.LOGARITHMICDEPTH) {
  60076. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  60077. }
  60078. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  60079. if (this._defines.SPECULARTERM) {
  60080. fallbacks.addFallback(0, "SPECULARTERM");
  60081. }
  60082. if (this._defines.OPACITYFRESNEL) {
  60083. fallbacks.addFallback(1, "OPACITYFRESNEL");
  60084. }
  60085. if (this._defines.EMISSIVEFRESNEL) {
  60086. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  60087. }
  60088. if (this._defines.FRESNEL) {
  60089. fallbacks.addFallback(3, "FRESNEL");
  60090. }
  60091. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  60092. fallbacks.addCPUSkinningFallback(0, mesh);
  60093. }
  60094. //Attributes
  60095. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60096. if (this._defines.NORMAL) {
  60097. attribs.push(BABYLON.VertexBuffer.NormalKind);
  60098. }
  60099. if (this._defines.TANGENT) {
  60100. attribs.push(BABYLON.VertexBuffer.TangentKind);
  60101. }
  60102. if (this._defines.UV1) {
  60103. attribs.push(BABYLON.VertexBuffer.UVKind);
  60104. }
  60105. if (this._defines.UV2) {
  60106. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60107. }
  60108. if (this._defines.VERTEXCOLOR) {
  60109. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60110. }
  60111. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  60112. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  60113. // Legacy browser patch
  60114. var join = this._defines.toString();
  60115. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  60116. "vFogInfos", "vFogColor", "pointSize",
  60117. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  60118. "mBones",
  60119. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  60120. "depthValues",
  60121. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  60122. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  60123. "logarithmicDepthConstant",
  60124. "vSphericalX", "vSphericalY", "vSphericalZ",
  60125. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  60126. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  60127. "vMicrosurfaceTextureLods",
  60128. "vCameraInfos"
  60129. ];
  60130. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  60131. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  60132. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  60133. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  60134. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  60135. }
  60136. if (!this._effect.isReady()) {
  60137. return false;
  60138. }
  60139. this._renderId = scene.getRenderId();
  60140. this._wasPreviouslyReady = true;
  60141. return true;
  60142. };
  60143. PBRMaterial.prototype.unbind = function () {
  60144. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  60145. this._effect.setTexture("reflection2DSampler", null);
  60146. }
  60147. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  60148. this._effect.setTexture("refraction2DSampler", null);
  60149. }
  60150. _super.prototype.unbind.call(this);
  60151. };
  60152. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60153. this._effect.setMatrix("world", world);
  60154. };
  60155. PBRMaterial.prototype.bind = function (world, mesh) {
  60156. this._myScene = this.getScene();
  60157. // Matrices
  60158. this.bindOnlyWorldMatrix(world);
  60159. // Bones
  60160. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60161. if (this._myScene.getCachedMaterial() !== this) {
  60162. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  60163. if (BABYLON.StandardMaterial.FresnelEnabled) {
  60164. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  60165. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  60166. }
  60167. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  60168. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  60169. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  60170. }
  60171. }
  60172. // Textures
  60173. if (this._myScene.texturesEnabled) {
  60174. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  60175. this._effect.setTexture("albedoSampler", this.albedoTexture);
  60176. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  60177. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  60178. }
  60179. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  60180. this._effect.setTexture("ambientSampler", this.ambientTexture);
  60181. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  60182. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  60183. }
  60184. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  60185. this._effect.setTexture("opacitySampler", this.opacityTexture);
  60186. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  60187. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  60188. }
  60189. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  60190. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  60191. if (this.reflectionTexture.isCube) {
  60192. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  60193. }
  60194. else {
  60195. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  60196. }
  60197. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  60198. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  60199. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  60200. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  60201. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  60202. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  60203. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  60204. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  60205. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  60206. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  60207. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  60208. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  60209. }
  60210. }
  60211. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  60212. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  60213. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  60214. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  60215. }
  60216. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  60217. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  60218. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  60219. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  60220. }
  60221. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  60222. if (this.metallicTexture) {
  60223. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  60224. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  60225. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  60226. }
  60227. else if (this.reflectivityTexture) {
  60228. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  60229. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  60230. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  60231. }
  60232. }
  60233. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  60234. this._effect.setTexture("bumpSampler", this.bumpTexture);
  60235. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  60236. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  60237. }
  60238. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  60239. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  60240. var depth = 1.0;
  60241. if (this.refractionTexture.isCube) {
  60242. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  60243. }
  60244. else {
  60245. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  60246. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  60247. if (this.refractionTexture.depth) {
  60248. depth = this.refractionTexture.depth;
  60249. }
  60250. }
  60251. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  60252. }
  60253. if ((this.reflectionTexture || this.refractionTexture)) {
  60254. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  60255. }
  60256. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  60257. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  60258. }
  60259. }
  60260. // Clip plane
  60261. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  60262. // Point size
  60263. if (this.pointsCloud) {
  60264. this._effect.setFloat("pointSize", this.pointSize);
  60265. }
  60266. // Colors
  60267. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  60268. if (this._defines.METALLICWORKFLOW) {
  60269. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  60270. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  60271. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  60272. }
  60273. else {
  60274. // GAMMA CORRECTION.
  60275. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  60276. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  60277. }
  60278. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  60279. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  60280. // GAMMA CORRECTION.
  60281. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  60282. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  60283. // GAMMA CORRECTION.
  60284. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  60285. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  60286. }
  60287. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  60288. // GAMMA CORRECTION.
  60289. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  60290. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  60291. // Lights
  60292. if (this._myScene.lightsEnabled && !this.disableLighting) {
  60293. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  60294. }
  60295. // View
  60296. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  60297. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  60298. }
  60299. // Fog
  60300. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  60301. this._lightingInfos.x = this.directIntensity;
  60302. this._lightingInfos.y = this.emissiveIntensity;
  60303. this._lightingInfos.z = this.environmentIntensity;
  60304. this._lightingInfos.w = this.specularIntensity;
  60305. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  60306. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  60307. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  60308. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  60309. this._cameraInfos.x = this.cameraExposure;
  60310. this._cameraInfos.y = this.cameraContrast;
  60311. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  60312. if (this.cameraColorCurves) {
  60313. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  60314. }
  60315. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  60316. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  60317. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  60318. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  60319. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  60320. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  60321. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  60322. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  60323. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  60324. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  60325. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  60326. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  60327. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  60328. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  60329. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  60330. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  60331. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  60332. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  60333. // Log. depth
  60334. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  60335. }
  60336. _super.prototype.bind.call(this, world, mesh);
  60337. this._myScene = null;
  60338. };
  60339. PBRMaterial.prototype.getAnimatables = function () {
  60340. var results = [];
  60341. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  60342. results.push(this.albedoTexture);
  60343. }
  60344. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  60345. results.push(this.ambientTexture);
  60346. }
  60347. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  60348. results.push(this.opacityTexture);
  60349. }
  60350. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  60351. results.push(this.reflectionTexture);
  60352. }
  60353. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  60354. results.push(this.emissiveTexture);
  60355. }
  60356. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  60357. results.push(this.metallicTexture);
  60358. }
  60359. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  60360. results.push(this.reflectivityTexture);
  60361. }
  60362. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  60363. results.push(this.bumpTexture);
  60364. }
  60365. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  60366. results.push(this.lightmapTexture);
  60367. }
  60368. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  60369. results.push(this.refractionTexture);
  60370. }
  60371. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  60372. results.push(this.cameraColorGradingTexture);
  60373. }
  60374. return results;
  60375. };
  60376. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60377. if (forceDisposeTextures) {
  60378. if (this.albedoTexture) {
  60379. this.albedoTexture.dispose();
  60380. }
  60381. if (this.ambientTexture) {
  60382. this.ambientTexture.dispose();
  60383. }
  60384. if (this.opacityTexture) {
  60385. this.opacityTexture.dispose();
  60386. }
  60387. if (this.reflectionTexture) {
  60388. this.reflectionTexture.dispose();
  60389. }
  60390. if (this.emissiveTexture) {
  60391. this.emissiveTexture.dispose();
  60392. }
  60393. if (this.metallicTexture) {
  60394. this.metallicTexture.dispose();
  60395. }
  60396. if (this.reflectivityTexture) {
  60397. this.reflectivityTexture.dispose();
  60398. }
  60399. if (this.bumpTexture) {
  60400. this.bumpTexture.dispose();
  60401. }
  60402. if (this.lightmapTexture) {
  60403. this.lightmapTexture.dispose();
  60404. }
  60405. if (this.refractionTexture) {
  60406. this.refractionTexture.dispose();
  60407. }
  60408. if (this.cameraColorGradingTexture) {
  60409. this.cameraColorGradingTexture.dispose();
  60410. }
  60411. }
  60412. this._renderTargets.dispose();
  60413. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60414. };
  60415. PBRMaterial.prototype.clone = function (name) {
  60416. var _this = this;
  60417. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  60418. };
  60419. PBRMaterial.prototype.serialize = function () {
  60420. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60421. serializationObject.customType = "BABYLON.PBRMaterial";
  60422. return serializationObject;
  60423. };
  60424. // Statics
  60425. PBRMaterial.Parse = function (source, scene, rootUrl) {
  60426. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  60427. };
  60428. return PBRMaterial;
  60429. }(BABYLON.Material));
  60430. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  60431. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  60432. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  60433. PBRMaterial._scaledReflection = new BABYLON.Color3();
  60434. __decorate([
  60435. BABYLON.serialize()
  60436. ], PBRMaterial.prototype, "directIntensity", void 0);
  60437. __decorate([
  60438. BABYLON.serialize()
  60439. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  60440. __decorate([
  60441. BABYLON.serialize()
  60442. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  60443. __decorate([
  60444. BABYLON.serialize()
  60445. ], PBRMaterial.prototype, "specularIntensity", void 0);
  60446. __decorate([
  60447. BABYLON.serialize()
  60448. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  60449. __decorate([
  60450. BABYLON.serialize()
  60451. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  60452. __decorate([
  60453. BABYLON.serialize()
  60454. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  60455. __decorate([
  60456. BABYLON.serialize()
  60457. ], PBRMaterial.prototype, "cameraExposure", void 0);
  60458. __decorate([
  60459. BABYLON.serialize()
  60460. ], PBRMaterial.prototype, "cameraContrast", void 0);
  60461. __decorate([
  60462. BABYLON.serializeAsTexture()
  60463. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  60464. __decorate([
  60465. BABYLON.serializeAsColorCurves()
  60466. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  60467. __decorate([
  60468. BABYLON.serializeAsColor3()
  60469. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  60470. __decorate([
  60471. BABYLON.serialize()
  60472. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  60473. __decorate([
  60474. BABYLON.serializeAsColor3()
  60475. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  60476. __decorate([
  60477. BABYLON.serialize()
  60478. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  60479. __decorate([
  60480. BABYLON.serializeAsColor3()
  60481. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  60482. __decorate([
  60483. BABYLON.serialize()
  60484. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  60485. __decorate([
  60486. BABYLON.serializeAsColor3()
  60487. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  60488. __decorate([
  60489. BABYLON.serialize()
  60490. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  60491. __decorate([
  60492. BABYLON.serializeAsColor3()
  60493. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  60494. __decorate([
  60495. BABYLON.serialize()
  60496. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  60497. __decorate([
  60498. BABYLON.serialize()
  60499. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  60500. __decorate([
  60501. BABYLON.serialize()
  60502. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  60503. __decorate([
  60504. BABYLON.serializeAsTexture()
  60505. ], PBRMaterial.prototype, "albedoTexture", void 0);
  60506. __decorate([
  60507. BABYLON.serializeAsTexture()
  60508. ], PBRMaterial.prototype, "ambientTexture", void 0);
  60509. __decorate([
  60510. BABYLON.serialize()
  60511. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  60512. __decorate([
  60513. BABYLON.serializeAsTexture()
  60514. ], PBRMaterial.prototype, "opacityTexture", void 0);
  60515. __decorate([
  60516. BABYLON.serializeAsTexture()
  60517. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  60518. __decorate([
  60519. BABYLON.serializeAsTexture()
  60520. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  60521. __decorate([
  60522. BABYLON.serializeAsTexture()
  60523. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  60524. __decorate([
  60525. BABYLON.serializeAsTexture()
  60526. ], PBRMaterial.prototype, "metallicTexture", void 0);
  60527. __decorate([
  60528. BABYLON.serialize()
  60529. ], PBRMaterial.prototype, "metallic", void 0);
  60530. __decorate([
  60531. BABYLON.serialize()
  60532. ], PBRMaterial.prototype, "roughness", void 0);
  60533. __decorate([
  60534. BABYLON.serializeAsTexture()
  60535. ], PBRMaterial.prototype, "bumpTexture", void 0);
  60536. __decorate([
  60537. BABYLON.serializeAsTexture()
  60538. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  60539. __decorate([
  60540. BABYLON.serializeAsTexture()
  60541. ], PBRMaterial.prototype, "refractionTexture", void 0);
  60542. __decorate([
  60543. BABYLON.serializeAsColor3("ambient")
  60544. ], PBRMaterial.prototype, "ambientColor", void 0);
  60545. __decorate([
  60546. BABYLON.serializeAsColor3("albedo")
  60547. ], PBRMaterial.prototype, "albedoColor", void 0);
  60548. __decorate([
  60549. BABYLON.serializeAsColor3("reflectivity")
  60550. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  60551. __decorate([
  60552. BABYLON.serializeAsColor3("reflection")
  60553. ], PBRMaterial.prototype, "reflectionColor", void 0);
  60554. __decorate([
  60555. BABYLON.serializeAsColor3("emissive")
  60556. ], PBRMaterial.prototype, "emissiveColor", void 0);
  60557. __decorate([
  60558. BABYLON.serialize()
  60559. ], PBRMaterial.prototype, "microSurface", void 0);
  60560. __decorate([
  60561. BABYLON.serialize()
  60562. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  60563. __decorate([
  60564. BABYLON.serialize()
  60565. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  60566. __decorate([
  60567. BABYLON.serializeAsFresnelParameters()
  60568. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  60569. __decorate([
  60570. BABYLON.serializeAsFresnelParameters()
  60571. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  60572. __decorate([
  60573. BABYLON.serialize()
  60574. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  60575. __decorate([
  60576. BABYLON.serialize()
  60577. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  60578. __decorate([
  60579. BABYLON.serialize()
  60580. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  60581. __decorate([
  60582. BABYLON.serialize()
  60583. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  60584. __decorate([
  60585. BABYLON.serialize()
  60586. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  60587. __decorate([
  60588. BABYLON.serialize()
  60589. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  60590. __decorate([
  60591. BABYLON.serialize()
  60592. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  60593. __decorate([
  60594. BABYLON.serialize()
  60595. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  60596. __decorate([
  60597. BABYLON.serialize()
  60598. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  60599. __decorate([
  60600. BABYLON.serialize()
  60601. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  60602. __decorate([
  60603. BABYLON.serialize()
  60604. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  60605. __decorate([
  60606. BABYLON.serialize()
  60607. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  60608. __decorate([
  60609. BABYLON.serialize()
  60610. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  60611. __decorate([
  60612. BABYLON.serialize()
  60613. ], PBRMaterial.prototype, "useParallax", void 0);
  60614. __decorate([
  60615. BABYLON.serialize()
  60616. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  60617. __decorate([
  60618. BABYLON.serialize()
  60619. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  60620. __decorate([
  60621. BABYLON.serialize()
  60622. ], PBRMaterial.prototype, "disableLighting", void 0);
  60623. __decorate([
  60624. BABYLON.serialize()
  60625. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  60626. __decorate([
  60627. BABYLON.serialize()
  60628. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  60629. __decorate([
  60630. BABYLON.serialize()
  60631. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  60632. __decorate([
  60633. BABYLON.serialize()
  60634. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  60635. __decorate([
  60636. BABYLON.serialize()
  60637. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  60638. BABYLON.PBRMaterial = PBRMaterial;
  60639. })(BABYLON || (BABYLON = {}));
  60640. //# sourceMappingURL=babylon.pbrMaterial.js.map
  60641. var BABYLON;
  60642. (function (BABYLON) {
  60643. var DebugLayer = (function () {
  60644. function DebugLayer(scene) {
  60645. this._scene = scene;
  60646. }
  60647. /** Creates the inspector window. */
  60648. DebugLayer.prototype._createInspector = function (config) {
  60649. if (config === void 0) { config = {}; }
  60650. var popup = config.popup || false;
  60651. var initialTab = config.initialTab || 0;
  60652. var parentElement = config.parentElement || null;
  60653. if (!this._inspector) {
  60654. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  60655. } // else nothing to do,; instance is already existing
  60656. };
  60657. DebugLayer.prototype.isVisible = function () {
  60658. if (!this._inspector) {
  60659. return false;
  60660. }
  60661. return true;
  60662. };
  60663. DebugLayer.prototype.hide = function () {
  60664. if (this._inspector) {
  60665. this._inspector.dispose();
  60666. this._inspector = null;
  60667. }
  60668. };
  60669. DebugLayer.prototype.show = function (config) {
  60670. if (config === void 0) { config = {}; }
  60671. if (typeof INSPECTOR == 'undefined') {
  60672. // Load inspector and add it to the DOM
  60673. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60674. }
  60675. else {
  60676. // Otherwise creates the inspector
  60677. this._createInspector(config);
  60678. }
  60679. };
  60680. return DebugLayer;
  60681. }());
  60682. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  60683. BABYLON.DebugLayer = DebugLayer;
  60684. })(BABYLON || (BABYLON = {}));
  60685. //# sourceMappingURL=babylon.debugLayer.js.map
  60686. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  60687. var BABYLON;
  60688. (function (BABYLON) {
  60689. var StandardRenderingPipeline = (function (_super) {
  60690. __extends(StandardRenderingPipeline, _super);
  60691. /**
  60692. * @constructor
  60693. * @param {string} name - The rendering pipeline name
  60694. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60695. * @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)
  60696. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  60697. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60698. */
  60699. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  60700. if (originalPostProcess === void 0) { originalPostProcess = null; }
  60701. var _this = _super.call(this, scene.getEngine(), name) || this;
  60702. _this.downSampleX4PostProcess = null;
  60703. _this.brightPassPostProcess = null;
  60704. _this.gaussianBlurHPostProcesses = [];
  60705. _this.gaussianBlurVPostProcesses = [];
  60706. _this.textureAdderPostProcess = null;
  60707. _this.textureAdderFinalPostProcess = null;
  60708. _this.lensFlareFinalPostProcess = null;
  60709. _this.lensFlarePostProcess = null;
  60710. _this.lensFlareComposePostProcess = null;
  60711. _this.depthOfFieldPostProcess = null;
  60712. // Values
  60713. _this.brightThreshold = 1.0;
  60714. _this.blurWidth = 2.0;
  60715. _this.horizontalBlur = false;
  60716. _this.gaussianCoefficient = 0.25;
  60717. _this.gaussianMean = 1.0;
  60718. _this.gaussianStandardDeviation = 1.0;
  60719. _this.exposure = 1.0;
  60720. _this.lensTexture = null;
  60721. _this.lensColorTexture = null;
  60722. _this.lensFlareStrength = 20.0;
  60723. _this.lensFlareGhostDispersal = 1.4;
  60724. _this.lensFlareHaloWidth = 0.7;
  60725. _this.lensFlareDistortionStrength = 16.0;
  60726. _this.lensStarTexture = null;
  60727. _this.lensFlareDirtTexture = null;
  60728. _this.depthOfFieldDistance = 10.0;
  60729. _this.depthOfFieldBlurWidth = 2.0;
  60730. // IAnimatable
  60731. _this.animations = [];
  60732. _this._depthRenderer = null;
  60733. _this._currentDepthOfFieldSource = null;
  60734. // Getters and setters
  60735. _this._depthOfFieldEnabled = true;
  60736. _this._lensFlareEnabled = true;
  60737. // Initialize
  60738. _this._scene = scene;
  60739. // Create pass post-processe
  60740. if (!originalPostProcess) {
  60741. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  60742. }
  60743. else {
  60744. _this.originalPostProcess = originalPostProcess;
  60745. }
  60746. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  60747. // Create down sample X4 post-process
  60748. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  60749. // Create bright pass post-process
  60750. _this._createBrightPassPostProcess(scene, ratio / 2);
  60751. // Create gaussian blur post-processes (down sampling blurs)
  60752. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  60753. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  60754. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  60755. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  60756. // Create texture adder post-process
  60757. _this._createTextureAdderPostProcess(scene, ratio);
  60758. // Create depth-of-field source post-process
  60759. _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);
  60760. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  60761. // Create lens flare post-process
  60762. _this._createLensFlarePostProcess(scene, ratio);
  60763. // Create depth-of-field source post-process post lens-flare and disable it now
  60764. _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);
  60765. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  60766. // Create gaussian blur used by depth-of-field
  60767. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  60768. // Create depth-of-field post-process
  60769. _this._createDepthOfFieldPostProcess(scene, ratio);
  60770. // Finish
  60771. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60772. if (cameras !== null) {
  60773. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60774. }
  60775. // Deactivate
  60776. _this.LensFlareEnabled = false;
  60777. _this.DepthOfFieldEnabled = false;
  60778. return _this;
  60779. }
  60780. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  60781. get: function () {
  60782. return this._depthOfFieldEnabled;
  60783. },
  60784. set: function (enabled) {
  60785. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  60786. if (enabled && !this._depthOfFieldEnabled) {
  60787. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  60788. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  60789. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  60790. this._depthRenderer = this._scene.enableDepthRenderer();
  60791. }
  60792. else if (!enabled && this._depthOfFieldEnabled) {
  60793. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  60794. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  60795. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  60796. }
  60797. this._depthOfFieldEnabled = enabled;
  60798. },
  60799. enumerable: true,
  60800. configurable: true
  60801. });
  60802. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  60803. get: function () {
  60804. return this._lensFlareEnabled;
  60805. },
  60806. set: function (enabled) {
  60807. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  60808. if (enabled && !this._lensFlareEnabled) {
  60809. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  60810. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  60811. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  60812. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  60813. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  60814. this._setDepthOfFieldSavePostProcess("HDRPostLensFlareDepthOfFieldSource");
  60815. }
  60816. else if (!enabled && this._lensFlareEnabled) {
  60817. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  60818. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  60819. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  60820. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  60821. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  60822. this._setDepthOfFieldSavePostProcess("HDRBaseDepthOfFieldSource");
  60823. }
  60824. this._lensFlareEnabled = enabled;
  60825. },
  60826. enumerable: true,
  60827. configurable: true
  60828. });
  60829. // Sets depth-of-field save post-process
  60830. StandardRenderingPipeline.prototype._setDepthOfFieldSavePostProcess = function (name) {
  60831. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  60832. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, name, this._scene.cameras);
  60833. switch (name) {
  60834. case "HDRBaseDepthOfFieldSource":
  60835. this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;
  60836. break;
  60837. case "HDRPostLensFlareDepthOfFieldSource":
  60838. this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;
  60839. break;
  60840. default: break;
  60841. }
  60842. };
  60843. // Down Sample X4 Post-Processs
  60844. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  60845. var _this = this;
  60846. var downSampleX4Offsets = new Array(32);
  60847. 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);
  60848. this.downSampleX4PostProcess.onApply = function (effect) {
  60849. var id = 0;
  60850. for (var i = -2; i < 2; i++) {
  60851. for (var j = -2; j < 2; j++) {
  60852. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  60853. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  60854. id += 2;
  60855. }
  60856. }
  60857. effect.setArray2("dsOffsets", downSampleX4Offsets);
  60858. };
  60859. // Add to pipeline
  60860. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  60861. };
  60862. // Brightpass Post-Process
  60863. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  60864. var _this = this;
  60865. var brightOffsets = new Array(8);
  60866. 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);
  60867. this.brightPassPostProcess.onApply = function (effect) {
  60868. var sU = (1.0 / _this.brightPassPostProcess.width);
  60869. var sV = (1.0 / _this.brightPassPostProcess.height);
  60870. brightOffsets[0] = -0.5 * sU;
  60871. brightOffsets[1] = 0.5 * sV;
  60872. brightOffsets[2] = 0.5 * sU;
  60873. brightOffsets[3] = 0.5 * sV;
  60874. brightOffsets[4] = -0.5 * sU;
  60875. brightOffsets[5] = -0.5 * sV;
  60876. brightOffsets[6] = 0.5 * sU;
  60877. brightOffsets[7] = -0.5 * sV;
  60878. effect.setArray2("dsOffsets", brightOffsets);
  60879. effect.setFloat("brightThreshold", _this.brightThreshold);
  60880. };
  60881. // Add to pipeline
  60882. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  60883. };
  60884. // Create gaussian blur H&V post-processes
  60885. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  60886. var _this = this;
  60887. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  60888. var blurOffsets = new Array(9);
  60889. var blurWeights = new Array(9);
  60890. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  60891. var callback = function (height) {
  60892. return function (effect) {
  60893. // Weights
  60894. var x = 0.0;
  60895. for (var i = 0; i < 9; i++) {
  60896. x = (i - 4.0) / 4.0;
  60897. blurWeights[i] =
  60898. _this.gaussianCoefficient
  60899. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  60900. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  60901. }
  60902. var lastOutputDimensions = {
  60903. width: scene.getEngine().getRenderWidth(),
  60904. height: scene.getEngine().getRenderHeight()
  60905. };
  60906. for (var i = 0; i < 9; i++) {
  60907. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  60908. blurOffsets[i] = value;
  60909. }
  60910. effect.setArray("blurOffsets", blurOffsets);
  60911. effect.setArray("blurWeights", blurWeights);
  60912. if (height) {
  60913. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  60914. }
  60915. else {
  60916. effect.setFloat("blurWidth", _this[blurWidthKey]);
  60917. }
  60918. };
  60919. };
  60920. // Create horizontal gaussian blur post-processes
  60921. 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);
  60922. gaussianBlurHPostProcess.onApply = callback(false);
  60923. // Create vertical gaussian blur post-process
  60924. 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);
  60925. gaussianBlurVPostProcess.onApply = callback(true);
  60926. // Add to pipeline
  60927. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  60928. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  60929. // Finish
  60930. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  60931. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  60932. };
  60933. // Create texture adder post-process
  60934. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  60935. var _this = this;
  60936. 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);
  60937. this.textureAdderPostProcess.onApply = function (effect) {
  60938. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  60939. effect.setTexture("lensSampler", _this.lensTexture);
  60940. effect.setFloat("exposure", _this.exposure);
  60941. };
  60942. // Add to pipeline
  60943. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  60944. };
  60945. // Create lens flare post-process
  60946. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  60947. var _this = this;
  60948. 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);
  60949. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  60950. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  60951. 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);
  60952. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  60953. var resolution = new BABYLON.Vector2(0, 0);
  60954. // Lens flare
  60955. this.lensFlarePostProcess.onApply = function (effect) {
  60956. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  60957. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  60958. effect.setFloat("strength", _this.lensFlareStrength);
  60959. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  60960. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  60961. // Shift
  60962. resolution.x = _this.lensFlarePostProcess.width;
  60963. resolution.y = _this.lensFlarePostProcess.height;
  60964. effect.setVector2("resolution", resolution);
  60965. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  60966. };
  60967. // Compose
  60968. 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);
  60969. 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);
  60970. this.lensFlareComposePostProcess.onApply = function (effect) {
  60971. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  60972. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  60973. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  60974. // Lens start rotation matrix
  60975. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  60976. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  60977. 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));
  60978. camRot *= 4.0;
  60979. 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);
  60980. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  60981. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  60982. };
  60983. };
  60984. // Create depth-of-field post-process
  60985. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  60986. var _this = this;
  60987. 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);
  60988. this.depthOfFieldPostProcess.onApply = function (effect) {
  60989. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  60990. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  60991. effect.setFloat("distance", _this.depthOfFieldDistance);
  60992. };
  60993. // Add to pipeline
  60994. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  60995. };
  60996. // Dispose
  60997. StandardRenderingPipeline.prototype.dispose = function () {
  60998. for (var i = 0; i < this._scene.cameras.length; i++) {
  60999. var camera = this._scene.cameras[i];
  61000. this.originalPostProcess.dispose(camera);
  61001. this.downSampleX4PostProcess.dispose(camera);
  61002. this.brightPassPostProcess.dispose(camera);
  61003. this.textureAdderPostProcess.dispose(camera);
  61004. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  61005. this.gaussianBlurHPostProcesses[j].dispose(camera);
  61006. }
  61007. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  61008. this.gaussianBlurVPostProcesses[j].dispose(camera);
  61009. }
  61010. this.textureAdderFinalPostProcess.dispose(camera);
  61011. this.lensFlarePostProcess.dispose(camera);
  61012. this.lensFlareComposePostProcess.dispose(camera);
  61013. this.depthOfFieldPostProcess.dispose(camera);
  61014. }
  61015. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  61016. _super.prototype.dispose.call(this);
  61017. };
  61018. // Serialize rendering pipeline
  61019. StandardRenderingPipeline.prototype.serialize = function () {
  61020. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61021. serializationObject.customType = "StandardRenderingPipeline";
  61022. return serializationObject;
  61023. };
  61024. // Parse serialized pipeline
  61025. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61026. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  61027. };
  61028. return StandardRenderingPipeline;
  61029. }(BABYLON.PostProcessRenderPipeline));
  61030. __decorate([
  61031. BABYLON.serialize()
  61032. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  61033. __decorate([
  61034. BABYLON.serialize()
  61035. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  61036. __decorate([
  61037. BABYLON.serialize()
  61038. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  61039. __decorate([
  61040. BABYLON.serialize()
  61041. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  61042. __decorate([
  61043. BABYLON.serialize()
  61044. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  61045. __decorate([
  61046. BABYLON.serialize()
  61047. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  61048. __decorate([
  61049. BABYLON.serialize()
  61050. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  61051. __decorate([
  61052. BABYLON.serializeAsTexture("lensTexture")
  61053. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  61054. __decorate([
  61055. BABYLON.serializeAsTexture("lensColorTexture")
  61056. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  61057. __decorate([
  61058. BABYLON.serialize()
  61059. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  61060. __decorate([
  61061. BABYLON.serialize()
  61062. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  61063. __decorate([
  61064. BABYLON.serialize()
  61065. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  61066. __decorate([
  61067. BABYLON.serialize()
  61068. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  61069. __decorate([
  61070. BABYLON.serializeAsTexture("lensStarTexture")
  61071. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  61072. __decorate([
  61073. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  61074. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  61075. __decorate([
  61076. BABYLON.serialize()
  61077. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  61078. __decorate([
  61079. BABYLON.serialize()
  61080. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  61081. __decorate([
  61082. BABYLON.serialize()
  61083. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  61084. __decorate([
  61085. BABYLON.serialize()
  61086. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  61087. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  61088. })(BABYLON || (BABYLON = {}));
  61089. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  61090. BABYLON.Effect.ShadersStore={"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}","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}","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}","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}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\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}","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}","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}","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#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) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,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}","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}","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}","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}","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","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\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}","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}","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","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\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}","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}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\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}","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}","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","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}","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}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\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 vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\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 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\nambientColor=vec3(1.,1.,1.)-((vec3(1.,1.,1.)-ambientColor)*vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICROUGHNESSMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#ifdef METALLICROUGHNESSGSTOREINALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef METALLICROUGHNESSGSTOREINGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n\nvec3 baseColor=surfaceAlbedo.rgb;\n\nsurfaceAlbedo.rgb*=(1.0-metallicRoughness.r);\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\nmicroSurface=1.0-metallicRoughness.g;\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=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\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\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\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}","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 vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\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#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) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,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 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}","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}","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}","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}","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}","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}","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}","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}","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","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","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}","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}","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","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}"};
  61091. 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","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","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","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","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","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","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}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","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}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\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","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\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","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","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}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\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","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","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\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","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","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\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}","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)\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\nconst float shadowStrength=80.;\nfloat visibility=1.0-clamp(exp(shadowStrength*shadowPixelDepth)*shadowMapSample-darkness,0.,1.);\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,visibility,vOverloadedShadowIntensity.x);\n#else\nreturn visibility;\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","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\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"};
  61092. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero(),this._collisionMask=-1}return Object.defineProperty(i.prototype,\"collisionMask\",{get:function(){return this._collisionMask},set:function(t){this._collisionMask=isNaN(t)?-1:t},enumerable:!0,configurable:!0}),i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),!((n=t.Vector3.Dot(this._tempVector4,r))<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),(n=t.Vector3.Dot(this._tempVector4,r))>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var p=!1,P=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(p=!0,P=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!p){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,P);y.found&&(P=y.root,p=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,P),y.found&&(P=y.root,p=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,P),y.found&&(P=y.root,p=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,P),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(P=y.root,p=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,P),y.found&&(D=(v*y.root-R)/g)>=0&&D<=1&&(P=y.root,p=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint)),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,P),y.found&&(D=(v*y.root-R)/g)>=0&&D<=1&&(P=y.root,p=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint))}if(p){var x=P*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,.01);for(var t,s=this._collisionCache.getMeshes(),l=Object.keys(s),n=l.length,a=0;a<n;++a)if(t=l[a],parseInt(t)!=r){var c=s[t];c.checkCollisions&&this.checkCollision(c)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=.01?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);o.Matrix.FromArray(e.worldMatrixFromCache).multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(e){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius),new i(t,this._collisionCache,r).collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var s={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},l={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:s};postMessage(l,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(o){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\";var o;!function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(o=e.WorkerTaskType||(e.WorkerTaskType={}));var i;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(i=e.WorkerReplyType||(e.WorkerReplyType={}));var t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t}();t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Uint32Array(o.getIndices()||[])}},e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);var d=n?n.collisionMask:t.collisionMask;t._initialize(o,i,a);for(var l=0;l<this._scene.meshes.length;l++){var c=this._scene.meshes[l];c.isEnabled()&&c.checkCollisions&&c.subMeshes&&c!==n&&0!=(d&c.collisionGroup)&&c._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,r){void 0===r&&(r=1.401298e-45);var n=t-i;return-r<=n&&n<=r},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.set=function(t,i,r){return this.copyFromFloats(t,i,r)},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){return new r(t.r+(i.r-t.r)*n,t.g+(i.g-t.g)*n,t.b+(i.b-t.b)*n)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r.Random=function(){return new r(Math.random(),Math.random(),Math.random())},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.copyFromFloats=function(t,i,r,n){return this.r=t,this.g=i,this.b=r,this.a=n,this},t.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},t.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.set=function(t,i){return this.copyFromFloats(t,i)},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r(-this.x,-this.y)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s;return new r(.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h))},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s;return new r(t.x*a+n.x*u+i.x*m+o.x*y,t.y*a+n.y*u+i.y*m+o.y*y)},r.Lerp=function(t,i,n){return new r(t.x+(i.x-t.x)*n,t.y+(i.y-t.y)*n)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){return new r(t.x<i.x?t.x:i.x,t.y<i.y?t.y:i.y)},r.Maximize=function(t,i){return new r(t.x>i.x?t.x:i.x,t.y>i.y?t.y:i.y)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=o<0?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r(-this.x,-this.y,-this.z)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){return i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,this},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.prototype.set=function(t,i,r){return this.copyFromFloats(t,i,r)},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o;return e/(e-(r.Dot(i,n)-o))},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.Forward=function(){return new r(0,0,1)},r.Right=function(){return new r(1,0,0)},r.Left=function(){return new r(-1,0,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s;return new r(.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h))},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s;return new r(t.x*a+n.x*u+i.x*m+o.x*y,t.y*a+n.y*u+i.y*m+o.y*y,t.z*a+n.z*u+i.z*m+o.z*y)},r.Lerp=function(t,i,n){var o=new r(0,0,0);return r.LerpToRef(t,i,n,o),o},r.LerpToRef=function(t,i,r,n){n.x=t.x+(i.x-t.x)*r,n.y=t.y+(i.y-t.y)*r,n.z=t.z+(i.z-t.z)*r},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(M.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,.5,0,h+e/2,s/2+a,.5,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,-(t.y/o*2-1),2*t.z-1),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(t,i,r,n){var o=M.Quaternion[0];a.RotationQuaternionFromAxisToRef(t,i,r,o),o.toEulerAnglesToRef(n)},r}();t.Vector3=e;var s=function(){function r(t,i,r,n){this.x=t,this.y=i,this.z=r,this.w=n}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},r.prototype.getClassName=function(){return\"Vector4\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},r.prototype.subtractFromFloats=function(t,i,n,o){return new r(this.x-t,this.y-i,this.z-n,this.w-o)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-r,o.w=this.w-n,this},r.prototype.negate=function(){return new r(-this.x,-this.y,-this.z,-this.w)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t,this.w*t)},r.prototype.scaleToRef=function(t,i){return i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t,this},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e,r.w=t.w},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o,e){e.x=t*o.m[0]+i*o.m[4]+r*o.m[8],e.y=t*o.m[1]+i*o.m[5]+r*o.m[9],e.z=t*o.m[2]+i*o.m[6]+r*o.m[10],e.w=n},r}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){return this.width=t,this.height=i,this},t.prototype.set=function(t,i){return this.copyFromFloats(t,i)},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){return new t(this.width+i.width,this.height+i.height)},t.prototype.subtract=function(i){return new t(this.width-i.width,this.height-i.height)},t.Lerp=function(i,r,n){return new t(i.width+(r.width-i.width)*n,i.height+(r.height-i.height)*n)},t}();t.Size=h;var a=function(){function i(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},i.prototype.getClassName=function(){return\"Quaternion\"},i.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},i.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},i.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.multiply=function(t){var r=new i(0,0,0,1);return this.multiplyToRef(t,r),r},i.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),this},i.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},i.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},i.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},i.prototype.conjugate=function(){return new i(-this.x,-this.y,-this.z,this.w)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},i.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r=this.z,n=this.x,o=this.y,e=this.w,s=e*e,h=r*r,a=n*n,u=o*o,m=o*r-n*e;return m<-.4999999?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>.4999999?(t.y=2*Math.atan2(o,e),t.x=-Math.PI/2,t.z=0):(t.z=Math.atan2(2*(n*o+r*e),-h-a+u+s),t.x=Math.asin(-2*(r*o-n*e)),t.y=Math.atan2(2*(r*n+o*e),h-a-u+s)),this},i.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},i.prototype.fromRotationMatrix=function(t){return i.FromRotationMatrixToRef(t,this),this},i.FromRotationMatrix=function(t){var r=new i;return i.FromRotationMatrixToRef(t,r),r},i.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},i.Zero=function(){return new i(0,0,0,0)},i.Inverse=function(t){return new i(-t.x,-t.y,-t.z,t.w)},i.Identity=function(){return new i(0,0,0,1)},i.IsIdentity=function(t){return t&&0===t.x&&0===t.y&&0===t.z&&1===t.w},i.RotationAxis=function(t,r){return i.RotationAxisToRef(t,r,new i)},i.RotationAxisToRef=function(t,i,r){var n=Math.sin(i/2);return t.normalize(),r.w=Math.cos(i/2),r.x=t.x*n,r.y=t.y*n,r.z=t.z*n,r},i.FromArray=function(t,r){return r||(r=0),new i(t[r],t[r+1],t[r+2],t[r+3])},i.RotationYawPitchRoll=function(t,r,n){var o=new i;return i.RotationYawPitchRollToRef(t,r,n,o),o},i.RotationYawPitchRollToRef=function(t,i,r,n){var o=.5*r,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);n.x=c*u*a+y*m*h,n.y=y*m*a-c*u*h,n.z=c*m*h-y*u*a,n.w=c*m*a+y*u*h},i.RotationAlphaBetaGamma=function(t,r,n){var o=new i;return i.RotationAlphaBetaGammaToRef(t,r,n,o),o},i.RotationAlphaBetaGammaToRef=function(t,i,r,n){var o=.5*(r+t),e=.5*(r-t),s=.5*i;n.x=Math.cos(e)*Math.sin(s),n.y=Math.sin(e)*Math.sin(s),n.z=Math.sin(o)*Math.cos(s),n.w=Math.cos(o)*Math.cos(s)},i.RotationQuaternionFromAxis=function(t,r,n,o){var e=new i(0,0,0,0);return i.RotationQuaternionFromAxisToRef(t,r,n,e),e},i.RotationQuaternionFromAxisToRef=function(i,r,n,o){var e=M.Matrix[0];t.Matrix.FromXYZAxesToRef(i.normalize(),r.normalize(),n.normalize(),e),t.Quaternion.FromRotationMatrixToRef(e,o)},i.Slerp=function(t,r,n){var o=i.Identity();return i.SlerpToRef(t,r,n,o),o},i.SlerpToRef=function(t,i,r,n){var o,e,s=r,h=t.x*i.x+t.y*i.y+t.z*i.z+t.w*i.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}n.x=e*t.x+o*i.x,n.y=e*t.y+o*i.y,n.z=e*t.z+o*i.z,n.w=e*t.w+o*i.w},i}();t.Quaternion=a;var u=function(){function r(){this.m=new Float32Array(16)}return r.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},r.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],r=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*r)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*e)-this.m[3]*(this.m[4]*r-this.m[5]*o+this.m[6]*e)},r.prototype.toArray=function(){return this.m},r.prototype.asArray=function(){return this.toArray()},r.prototype.invert=function(){return this.invertToRef(this),this},r.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},r.prototype.add=function(t){var i=new r;return this.addToRef(t,i),i},r.prototype.addToRef=function(t,i){for(var r=0;r<16;r++)i.m[r]=this.m[r]+t.m[r];return this},r.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},r.prototype.invertToRef=function(t){var i=this.m[0],r=this.m[1],n=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),F=e*w-s*d+a*R,M=-(e*v-s*g+h*R),A=1/(i*T+r*_+n*F+o*M),b=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,N=s*y-h*m,V=e*c-a*u,q=e*y-h*u,D=e*m-s*u;return t.m[0]=T*A,t.m[4]=_*A,t.m[8]=F*A,t.m[12]=M*A,t.m[1]=-(r*z-n*w+o*v)*A,t.m[5]=(i*z-n*d+o*g)*A,t.m[9]=-(i*w-r*d+o*R)*A,t.m[13]=(i*v-r*g+n*R)*A,\nt.m[2]=(r*b-n*L+o*C)*A,t.m[6]=-(i*b-n*P+o*Z)*A,t.m[10]=(i*L-r*P+o*S)*A,t.m[14]=-(i*C-r*Z+n*S)*A,t.m[3]=-(r*I-n*H+o*N)*A,t.m[7]=(i*I-n*V+o*q)*A,t.m[11]=-(i*H-r*V+o*D)*A,t.m[15]=(i*N-r*q+n*D)*A,this},r.prototype.setTranslationFromFloats=function(t,i,r){return this.m[12]=t,this.m[13]=i,this.m[14]=r,this},r.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},r.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},r.prototype.getTranslationToRef=function(t){return t.x=this.m[12],t.y=this.m[13],t.z=this.m[14],this},r.prototype.removeRotationAndScaling=function(){return this.setRowFromFloats(0,1,0,0,0),this.setRowFromFloats(1,0,1,0,0),this.setRowFromFloats(2,0,0,1,0),this},r.prototype.multiply=function(t){var i=new r;return this.multiplyToRef(t,i),i},r.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this},r.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var r=0;r<16;r++)t[i+r]=this.m[r];return this},r.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},r.prototype.multiplyToArray=function(t,i,r){var n=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],F=t.m[6],M=t.m[7],A=t.m[8],b=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[r]=n*v+o*T+e*A+s*P,i[r+1]=n*d+o*_+e*b+s*Z,i[r+2]=n*g+o*F+e*L+s*S,i[r+3]=n*R+o*M+e*C+s*I,i[r+4]=h*v+a*T+u*A+m*P,i[r+5]=h*d+a*_+u*b+m*Z,i[r+6]=h*g+a*F+u*L+m*S,i[r+7]=h*R+a*M+u*C+m*I,i[r+8]=y*v+c*T+p*A+f*P,i[r+9]=y*d+c*_+p*b+f*Z,i[r+10]=y*g+c*F+p*L+f*S,i[r+11]=y*R+c*M+p*C+f*I,i[r+12]=x*v+l*T+z*A+w*P,i[r+13]=x*d+l*_+z*b+w*Z,i[r+14]=x*g+l*F+z*L+w*S,i[r+15]=x*R+l*M+z*C+w*I,this},r.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},r.prototype.clone=function(){return r.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])},r.prototype.getClassName=function(){return\"Matrix\"},r.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},r.prototype.decompose=function(t,n,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return t.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),t.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),t.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===t.x||0===t.y||0===t.z?(n.x=0,n.y=0,n.z=0,n.w=1,!1):(r.FromValuesToRef(this.m[0]/t.x,this.m[1]/t.x,this.m[2]/t.x,0,this.m[4]/t.y,this.m[5]/t.y,this.m[6]/t.y,0,this.m[8]/t.z,this.m[9]/t.z,this.m[10]/t.z,0,0,0,0,1,M.Matrix[0]),a.FromRotationMatrixToRef(M.Matrix[0],n),!0)},r.prototype.getRotationMatrix=function(){var t=r.Identity();return this.getRotationMatrixToRef(t),t},r.prototype.getRotationMatrixToRef=function(t){var i=this.m,n=i[0]*i[1]*i[2]*i[3]<0?-1:1,o=i[4]*i[5]*i[6]*i[7]<0?-1:1,e=i[8]*i[9]*i[10]*i[11]<0?-1:1,s=n*Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),h=o*Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),a=e*Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);return r.FromValuesToRef(i[0]/s,i[1]/s,i[2]/s,0,i[4]/h,i[5]/h,i[6]/h,0,i[8]/a,i[9]/a,i[10]/a,0,0,0,0,1,t),this},r.FromArray=function(t,i){var n=new r;return i||(i=0),r.FromArrayToRef(t,i,n),n},r.FromArrayToRef=function(t,i,r){for(var n=0;n<16;n++)r.m[n]=t[n+i]},r.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;o<16;o++)n.m[o]=t[o+i]*r},r.FromValuesToRef=function(t,i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=r,l.m[3]=n,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},r.prototype.getRow=function(t){if(t<0||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},r.prototype.setRow=function(t,i){if(t<0||t>3)return this;var r=4*t;return this.m[r+0]=i.x,this.m[r+1]=i.y,this.m[r+2]=i.z,this.m[r+3]=i.w,this},r.prototype.setRowFromFloats=function(t,i,r,n,o){if(t<0||t>3)return this;var e=4*t;return this.m[e+0]=i,this.m[e+1]=r,this.m[e+2]=n,this.m[e+3]=o,this},r.FromValues=function(t,i,n,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new r;return z.m[0]=t,z.m[1]=i,z.m[2]=n,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=x,z.m[15]=l,z},r.Compose=function(t,i,n){var o=r.Identity();return r.ComposeToRef(t,i,n,o),o},r.ComposeToRef=function(t,i,n,o){r.FromValuesToRef(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1,M.Matrix[1]),i.toRotationMatrix(M.Matrix[0]),M.Matrix[1].multiplyToRef(M.Matrix[0],o),o.setTranslation(n)},r.Identity=function(){return r.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},r.IdentityToRef=function(t){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},r.Zero=function(){return r.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},r.RotationX=function(t){var i=new r;return r.RotationXToRef(t,i),i},r.Invert=function(t){var i=new r;return t.invertToRef(i),i},r.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-r,i.m[6]=r,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationY=function(t){var i=new r;return r.RotationYToRef(t,i),i},r.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-r,i.m[8]=r,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationZ=function(t){var i=new r;return r.RotationZToRef(t,i),i},r.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=r,i.m[4]=-r,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationAxis=function(t,i){var n=r.Zero();return r.RotationAxisToRef(t,i,n),n},r.RotationAxisToRef=function(t,i,r){var n=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),r.m[0]=t.x*t.x*e+o,r.m[1]=t.x*t.y*e-t.z*n,r.m[2]=t.x*t.z*e+t.y*n,r.m[3]=0,r.m[4]=t.y*t.x*e+t.z*n,r.m[5]=t.y*t.y*e+o,r.m[6]=t.y*t.z*e-t.x*n,r.m[7]=0,r.m[8]=t.z*t.x*e-t.y*n,r.m[9]=t.z*t.y*e+t.x*n,r.m[10]=t.z*t.z*e+o,r.m[11]=0,r.m[15]=1},r.RotationYawPitchRoll=function(t,i,n){var o=new r;return r.RotationYawPitchRollToRef(t,i,n,o),o},r.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},r.Scaling=function(t,i,n){var o=r.Zero();return r.ScalingToRef(t,i,n,o),o},r.ScalingToRef=function(t,i,r,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=r,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.Translation=function(t,i,n){var o=r.Identity();return r.TranslationToRef(t,i,n,o),o},r.TranslationToRef=function(t,i,n,o){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,n,1,o)},r.Lerp=function(t,i,n){for(var o=r.Zero(),e=0;e<16;e++)o.m[e]=t.m[e]*(1-n)+i.m[e]*n;return o},r.DecomposeLerp=function(t,i,n){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);i.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return r.Compose(c,p,f)},r.LookAtLH=function(t,i,n){var o=r.Zero();return r.LookAtLHToRef(t,i,n,o),o},r.LookAtLHToRef=function(t,i,n,o){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.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,s,h,a,1,o)},r.LookAtRH=function(t,i,n){var o=r.Zero();return r.LookAtRHToRef(t,i,n,o),o},r.LookAtRHToRef=function(t,i,n,o){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.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,s,h,a,1,o)},r.OrthoLH=function(t,i,n,o){var e=r.Zero();return r.OrthoLHToRef(t,i,n,o,e),e},r.OrthoLHToRef=function(i,r,n,o,e){var s=n,h=o,a=2/i,u=2/r,m=2/(h-s),y=-(h+s)/(h-s);t.Matrix.FromValuesToRef(a,0,0,0,0,u,0,0,0,0,m,0,0,0,y,1,e)},r.OrthoOffCenterLH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterLHToRef=function(i,r,n,o,e,s,h){var a=e,u=s,m=2/(r-i),y=2/(o-n),c=2/(u-a),p=-(u+a)/(u-a),f=(i+r)/(i-r),x=(o+n)/(n-o);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,0,f,x,p,1,h)},r.OrthoOffCenterRH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterRHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterRHToRef=function(t,i,n,o,e,s,h){r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h.m[10]*=-1},r.PerspectiveLH=function(i,n,o,e){var s=r.Zero(),h=o,a=e,u=2*h/i,m=2*h/n,y=(a+h)/(a-h),c=-2*a*h/(a-h);return t.Matrix.FromValuesToRef(u,0,0,0,0,m,0,0,0,0,y,1,0,0,c,0,s),s},r.PerspectiveFovLH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovLHToRef(t,i,n,o,e),e},r.PerspectiveFovLHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,1,0,0,p,0,e)},r.PerspectiveFovRH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovRHToRef(t,i,n,o,e),e},r.PerspectiveFovRHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=-(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,-1,0,0,p,0,e)},r.PerspectiveFovWebVRToRef=function(t,i,r,n,o){void 0===o&&(o=!1);var e=o?-1:1,s=Math.tan(t.upDegrees*Math.PI/180),h=Math.tan(t.downDegrees*Math.PI/180),a=Math.tan(t.leftDegrees*Math.PI/180),u=Math.tan(t.rightDegrees*Math.PI/180),m=2/(a+u),y=2/(s+h);n.m[0]=m,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=y,n.m[6]=n.m[7]=0,n.m[8]=(a-u)*m*.5*e,n.m[9]=-((s-h)*y*.5)*e,n.m[10]=-(i+r)/(r-i)*e,n.m[11]=1*e,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=-(2*r*i)/(r-i)},r.GetFinalMatrix=function(t,i,n,o,e,s){var h=t.width,a=t.height,u=t.x,m=t.y,y=r.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return i.multiply(n).multiply(o).multiply(y)},r.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},r.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},r.Transpose=function(t){var i=new r;return i.m[0]=t.m[0],i.m[1]=t.m[4],i.m[2]=t.m[8],i.m[3]=t.m[12],i.m[4]=t.m[1],i.m[5]=t.m[5],i.m[6]=t.m[9],i.m[7]=t.m[13],i.m[8]=t.m[2],i.m[9]=t.m[6],i.m[10]=t.m[10],i.m[11]=t.m[14],i.m[12]=t.m[3],i.m[13]=t.m[7],i.m[14]=t.m[11],i.m[15]=t.m[15],i},r.Reflection=function(t){var i=new r;return r.ReflectionToRef(t,i),i},r.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},r.FromXYZAxesToRef=function(t,i,r,n){n.m[0]=t.x,n.m[1]=t.y,n.m[2]=t.z,n.m[3]=0,n.m[4]=i.x,n.m[5]=i.y,n.m[6]=i.z,n.m[7]=0,n.m[8]=r.x,n.m[9]=r.y,n.m[10]=r.z,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.FromQuaternionToRef=function(t,i){var r=t.x*t.x,n=t.y*t.y,o=t.z*t.z,e=t.x*t.y,s=t.z*t.w,h=t.z*t.x,a=t.y*t.w,u=t.y*t.z,m=t.x*t.w;i.m[0]=1-2*(n+o),i.m[1]=2*(e+s),i.m[2]=2*(h-a),i.m[3]=0,i.m[4]=2*(e-s),i.m[5]=1-2*(o+r),i.m[6]=2*(u+m),i.m[7]=0,i.m[8]=2*(h+a),i.m[9]=2*(u-m),i.m[10]=1-2*(n+r),i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i.m[15]=1},r}();u._tempQuaternion=new a,u._xAxis=e.Zero(),u._yAxis=e.Zero(),u._zAxis=e.Zero(),t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d;return new t(n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15])},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){return e.Dot(this.normal,t)<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;n<6;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;!function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\",t[t.BONE=2]=\"BONE\"}(t.Space||(t.Space={}));var p=function(){function t(){}return t}();p.X=new e(1,0,0),p.Y=new e(0,1,0),p.Z=new e(0,0,1),t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a;a-=(e*(m*a)+s*m+h*a-t)*(1/(3*e*m+2*s*a+h)),a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f;var x;!function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(x=t.Orientation||(t.Orientation={}));var l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,r){var n=r.subtract(i);return new t(Math.atan2(n.y,n.x))},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var z=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?x.CW:x.CCW,this.angle=l.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===x.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1];t+=this._points[0].subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&i<=u){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=w;var v=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,-1,0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){return(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){return(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.CreateCatmullRomSpline=function(i,r){var n=new Array;n.push(i[0].clone()),Array.prototype.push.apply(n,i),n.push(i[i.length-1].clone());for(var o=new Array,s=1/r,h=0;h<n.length-3;h++)for(var a=0,u=0;u<r;u++)o.push(e.CatmullRom(n[h],n[h+1],n[h+2],n[h+3],a)),a+=s;return h--,o.push(e.CatmullRom(n[h],n[h+1],n[h+2],n[h+3],a)),new t(o)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype.continue=function(i){for(var r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));return new t(n)},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var R=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=R;var T=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var _=function(){function t(t,i,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var F=function(){function t(){}return t}();F.Color3=[r.Black(),r.Black(),r.Black()],F.Vector2=[o.Zero(),o.Zero(),o.Zero()],F.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],F.Vector4=[s.Zero(),s.Zero(),s.Zero()],F.Quaternion=[a.Zero(),a.Zero()],F.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=F;var M=function(){function t(){}return t}();M.Vector3=[e.Zero()],M.Matrix=[u.Zero(),u.Zero()],M.Quaternion=[a.Zero()]}(BABYLON||(BABYLON={}));";
  61093. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  61094. module.exports = BABYLON;
  61095. };